blob: 8286007b047e9e0e3d8407658a32f89a621ae43e [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 {
332 result.push_back(CHECKED_NON_NEGATIVE(i));
333 }
334 return result;
335}
336
337void CalcPadding(uint32_t inputSize,
338 uint32_t filterSize,
339 uint32_t stride,
Pablo Tellof0bd6832019-04-26 17:58:13 +0100340 uint32_t dilation,
telsoa01c577f2c2018-08-31 09:22:23 +0100341 uint32_t& paddingFront,
342 uint32_t& paddingBack,
343 tflite::Padding padding)
344{
345 paddingFront = 0;
346 paddingBack = 0;
347 if (padding == tflite::Padding_SAME)
348 {
349 uint32_t outputSize = (inputSize + stride - 1) / stride;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100350 uint32_t dilatedSize = filterSize + (dilation - 1) * (filterSize - 1);
351 uint32_t temp = (outputSize - 1) * stride + dilatedSize;
telsoa01c577f2c2018-08-31 09:22:23 +0100352 if (temp > inputSize)
353 {
354 paddingFront = (temp - inputSize) / 2;
355 paddingBack = (temp - inputSize) - paddingFront;
356 }
357 }
358}
359
Kevin May7d96b162021-02-03 17:38:41 +0000360armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100361 const std::vector<unsigned int>& shapes,
362 const armnn::PermutationVector& dimensionMappings = {0, 1, 2, 3},
363 const bool outputTensor = false)
telsoa01c577f2c2018-08-31 09:22:23 +0100364{
365 armnn::DataType type;
366 CHECK_TENSOR_PTR(tensorPtr);
367
368 switch (tensorPtr->type)
369 {
370 case tflite::TensorType_UINT8:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000371 type = armnn::DataType::QAsymmU8;
telsoa01c577f2c2018-08-31 09:22:23 +0100372 break;
373 case tflite::TensorType_FLOAT32:
374 type = armnn::DataType::Float32;
375 break;
Finn Williamsed66d142019-12-06 09:55:55 +0000376 case tflite::TensorType_INT8:
Keith Davis67e6c542020-02-19 10:08:33 +0000377 if (tensorPtr->quantization->zero_point.size() == 1)
Ryan OShea03181ff2020-02-07 17:22:22 +0000378 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000379 // Per-tensor
Ryan OShea03181ff2020-02-07 17:22:22 +0000380 type = armnn::DataType::QAsymmS8;
381 }
382 else
383 {
Keith Davis0c2eeac2020-02-11 16:51:50 +0000384 // Per-channel
Ryan OShea03181ff2020-02-07 17:22:22 +0000385 type = armnn::DataType::QSymmS8;
386 }
Finn Williamsed66d142019-12-06 09:55:55 +0000387 break;
388 case tflite::TensorType_INT16:
Derek Lambertif90c56d2020-01-10 17:14:08 +0000389 type = armnn::DataType::QSymmS16;
Finn Williamsed66d142019-12-06 09:55:55 +0000390 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100391 case tflite::TensorType_INT32:
392 type = armnn::DataType::Signed32;
393 break;
Inki Daed4619e22020-09-10 15:33:54 +0900394 case tflite::TensorType_INT64:
395 type = armnn::DataType::Signed64;
396 break;
telsoa01c577f2c2018-08-31 09:22:23 +0100397 default:
398 {
399 CheckLocation location = CHECK_LOCATION();
400 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100401 fmt::format("Unsupported data type {} = {} for tensor: {}. {}",
402 tensorPtr->type,
403 tflite::EnumNameTensorType(tensorPtr->type),
404 tensorPtr->name,
405 location.AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100406 }
407 }
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100408 std::vector<unsigned int> safeShape = shapes;
Sadik Armagand109a4d2020-07-28 10:42:13 +0100409 bool isDynamic = false;
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100410 if (safeShape.size() == 0)
411 {
412 safeShape.push_back(1);
Sadik Armagand109a4d2020-07-28 10:42:13 +0100413 if (outputTensor)
414 {
415 isDynamic = true;
416 }
Narumol Prangnawarat4818d462019-04-17 11:22:38 +0100417 }
418
Keith Davisd305e1a2020-01-22 11:57:54 +0000419 float quantizationScale = 0.0f;
420 int32_t quantizationOffset = 0;
421
422 if (tensorPtr->quantization.get())
423 {
424 if (tensorPtr->quantization->scale.size() <= 1)
425 {
426 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
427 CHECK_VALID_SIZE(tensorPtr->quantization->zero_point.size(), 0, 1);
428
429 if (tensorPtr->quantization->scale.size() == 1)
430 {
431 quantizationScale = tensorPtr->quantization->scale[0];
432 }
433 if (tensorPtr->quantization->zero_point.size() == 1)
434 {
435 // NOTE: we lose precision here when converting from 64 bit to 32
Ryan OShea03181ff2020-02-07 17:22:22 +0000436 // but this is what we support at the moment in ArmNN
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100437 quantizationOffset = armnn::numeric_cast<int32_t>(tensorPtr->quantization->zero_point[0]);
Keith Davisd305e1a2020-01-22 11:57:54 +0000438 }
439
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100440 TensorShape tensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()),
Sadik Armagand109a4d2020-07-28 10:42:13 +0100441 safeShape.data());
442 if (isDynamic)
443 {
444 tensorShape = TensorShape(1, false);
445 }
446 armnn::TensorInfo result(tensorShape,
447 type,
448 quantizationScale,
449 quantizationOffset);
Keith Davisd305e1a2020-01-22 11:57:54 +0000450 return result;
451 }
452 else
453 {
454 std::vector<float> quantizationScales;
455 std::vector<int32_t> quantizationOffsets;
456
457 // Scale
458 std::copy(tensorPtr->quantization->scale.begin(),
459 tensorPtr->quantization->scale.end(),
460 std::back_inserter(quantizationScales));
461
Keith Davis0c2eeac2020-02-11 16:51:50 +0000462 // QSymmS8 Per-axis
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100463 TensorShape tensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()),
Sadik Armagand109a4d2020-07-28 10:42:13 +0100464 safeShape.data());
465 if (isDynamic)
466 {
467 tensorShape = TensorShape(1, false);
468 }
469 armnn::TensorInfo result(tensorShape,
470 type,
471 quantizationScales,
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100472 dimensionMappings[armnn::numeric_cast<unsigned int>(
Sadik Armagand109a4d2020-07-28 10:42:13 +0100473 tensorPtr->quantization->quantized_dimension)]);
Keith Davisd305e1a2020-01-22 11:57:54 +0000474 return result;
475 }
476 }
477 else
478 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100479 TensorShape tensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()),
Sadik Armagand109a4d2020-07-28 10:42:13 +0100480 safeShape.data());
481 if (isDynamic)
482 {
483 tensorShape = TensorShape(1, false);
484 }
485 armnn::TensorInfo result(tensorShape,
Keith Davisd305e1a2020-01-22 11:57:54 +0000486 type,
487 quantizationScale,
488 quantizationOffset);
489 return result;
490 }
telsoa01c577f2c2018-08-31 09:22:23 +0100491}
492
Kevin May7d96b162021-02-03 17:38:41 +0000493armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Keith Davis0c2eeac2020-02-11 16:51:50 +0000494 const armnn::PermutationVector& dimensionMappings = {0, 1, 2, 3})
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000495{
496 auto const & dimensions = AsUnsignedVector(tensorPtr->shape);
Keith Davis0c2eeac2020-02-11 16:51:50 +0000497 return ToTensorInfo(tensorPtr, dimensions, dimensionMappings);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +0000498}
499
Kevin May7d96b162021-02-03 17:38:41 +0000500armnn::TensorInfo ToTensorInfo(TfLiteParserImpl::TensorRawPtr tensorPtr,
Sadik Armagand109a4d2020-07-28 10:42:13 +0100501 const bool outputTensor)
502{
503 auto const & dimensions = AsUnsignedVector(tensorPtr->shape);
504 const armnn::PermutationVector& dimensionMappings = {0, 1, 2, 3};
505 return ToTensorInfo(tensorPtr, dimensions, dimensionMappings, outputTensor);
506}
507
telsoa01c577f2c2018-08-31 09:22:23 +0100508template<typename T>
509std::pair<armnn::ConstTensor, std::unique_ptr<T[]>>
Kevin May7d96b162021-02-03 17:38:41 +0000510CreateConstTensorImpl(TfLiteParserImpl::BufferRawPtr bufferPtr,
511 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +0000512 armnn::TensorInfo& tensorInfo,
513 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +0100514{
Jan Eilers8eb25602020-03-09 12:13:48 +0000515 IgnoreUnused(tensorPtr);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100516 ARMNN_ASSERT_MSG(tensorPtr != nullptr, "tensorPtr is null");
517 ARMNN_ASSERT_MSG(bufferPtr != nullptr,
James Ward58dec6b2020-09-11 17:32:44 +0100518 fmt::format("Buffer for buffer:{} is null", tensorPtr->buffer).c_str());
telsoa01c577f2c2018-08-31 09:22:23 +0100519
520 std::unique_ptr<T[]> data(new T[tensorInfo.GetNumElements()]);
Matteo Martincigh747ef822018-12-18 09:26:39 +0000521
522 if (permutationVector.has_value() && permutationVector.value().GetSize() > 0)
523 {
524 tensorInfo = armnnUtils::Permuted(tensorInfo, permutationVector.value());
Matteo Martincighd5b9e642019-01-04 18:01:21 +0000525 armnnUtils::Permute(tensorInfo.GetShape(), permutationVector.value(),
526 reinterpret_cast<const T*>(bufferPtr->data.data()), data.get(), sizeof(T));
Matteo Martincigh747ef822018-12-18 09:26:39 +0000527 }
528 else
529 {
530 ::memcpy(data.get(), bufferPtr->data.data(), tensorInfo.GetNumBytes());
531 }
532
telsoa01c577f2c2018-08-31 09:22:23 +0100533 return std::make_pair(ConstTensor(tensorInfo, data.get()), std::move(data));
534}
535
telsoa01c577f2c2018-08-31 09:22:23 +0100536armnn::LayerBindingId GenerateLayerBindingId(size_t subgraphIndex, size_t tensorIndex)
537{
538 // generate the binding id by shifting the tensor id by 8 bit
539 // and add the subgraph id, which allows 256 subgraphs
540 return static_cast<armnn::LayerBindingId>((tensorIndex<<8)+subgraphIndex);
541}
542
Aron Virginas-Tar70672f62019-01-23 14:00:00 +0000543bool CheckShape(const armnn::TensorShape& actual, const std::vector<int32_t>& expected)
544{
545 const unsigned int actualSize = actual.GetNumDimensions();
546 if (actualSize != expected.size())
547 {
548 return false;
549 }
550
551 for (unsigned int i = 0u; i < actualSize; i++)
552 {
553 if (expected[i] < 0 ||
554 actual[i] != static_cast<unsigned int>(expected[i]))
555 {
556 return false;
557 }
558 }
559
560 return true;
561}
562
James Conroy05102392020-06-24 15:39:55 +0100563void CheckMatchingQuantization(const TensorInfo& first,
564 const TensorInfo& second,
565 const std::string& descName,
566 std::string const& firstName,
567 std::string const& secondName)
568{
569 if (!first.IsQuantized() ||
570 !second.IsQuantized())
571 {
572 // Not a quantized type, ignore the validation
573 return;
574 }
575
576 DataType firstDataType = first.GetDataType();
577 DataType secondDataType = second.GetDataType();
578
579 if (firstDataType != secondDataType)
580 {
581 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
582 " must be of the same quantized type, " +
583 firstName + " is " + GetDataTypeName(firstDataType) + ", " +
584 secondName + " is " + GetDataTypeName(secondDataType));
585 }
586
587 if (!first.IsTypeSpaceMatch(second))
588 {
589 throw InvalidArgumentException(descName + ": " + firstName + " and " + secondName +
590 " must have the same quantization space, " +
591 firstName + " has offset " + std::to_string(first.GetQuantizationOffset()) +
592 " and scale " + std::to_string(first.GetQuantizationScale()) + ", " +
593 secondName + " has offset " + std::to_string(second.GetQuantizationOffset()) +
594 " and scale " + std::to_string(second.GetQuantizationScale()));
595 }
596}
597
telsoa01c577f2c2018-08-31 09:22:23 +0100598} // <anonymous>
599
Kevin May7d96b162021-02-03 17:38:41 +0000600TfLiteParserImpl::TfLiteParserImpl(const Optional<ITfLiteParser::TfLiteParserOptions>& options)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100601: m_Options(options)
602, m_Network(nullptr, nullptr)
Kevin May7d96b162021-02-03 17:38:41 +0000603, m_ParserFunctions(tflite::BuiltinOperator_MAX+1, &TfLiteParserImpl::ParseUnsupportedOperator)
telsoa01c577f2c2018-08-31 09:22:23 +0100604{
605 // register supported operators
Kevin May7d96b162021-02-03 17:38:41 +0000606 m_ParserFunctions[tflite::BuiltinOperator_ADD] = &TfLiteParserImpl::ParseAdd;
607 m_ParserFunctions[tflite::BuiltinOperator_AVERAGE_POOL_2D] = &TfLiteParserImpl::ParseAveragePool2D;
608 m_ParserFunctions[tflite::BuiltinOperator_BATCH_TO_SPACE_ND] = &TfLiteParserImpl::ParseBatchToSpaceND;
609 m_ParserFunctions[tflite::BuiltinOperator_CONCATENATION] = &TfLiteParserImpl::ParseConcatenation;
610 m_ParserFunctions[tflite::BuiltinOperator_CONV_2D] = &TfLiteParserImpl::ParseConv2D;
611 m_ParserFunctions[tflite::BuiltinOperator_CUSTOM] = &TfLiteParserImpl::ParseCustomOperator;
612 m_ParserFunctions[tflite::BuiltinOperator_DEPTH_TO_SPACE] = &TfLiteParserImpl::ParseDepthToSpace;
613 m_ParserFunctions[tflite::BuiltinOperator_DEPTHWISE_CONV_2D] = &TfLiteParserImpl::ParseDepthwiseConv2D;
614 m_ParserFunctions[tflite::BuiltinOperator_DEQUANTIZE] = &TfLiteParserImpl::ParseDequantize;
615 m_ParserFunctions[tflite::BuiltinOperator_ELU] = &TfLiteParserImpl::ParseElu;
616 m_ParserFunctions[tflite::BuiltinOperator_EXP] = &TfLiteParserImpl::ParseExp;
617 m_ParserFunctions[tflite::BuiltinOperator_FULLY_CONNECTED] = &TfLiteParserImpl::ParseFullyConnected;
618 m_ParserFunctions[tflite::BuiltinOperator_GATHER] = &TfLiteParserImpl::ParseGather;
619 m_ParserFunctions[tflite::BuiltinOperator_HARD_SWISH] = &TfLiteParserImpl::ParseHardSwish;
620 m_ParserFunctions[tflite::BuiltinOperator_LEAKY_RELU] = &TfLiteParserImpl::ParseLeakyRelu;
621 m_ParserFunctions[tflite::BuiltinOperator_LOGISTIC] = &TfLiteParserImpl::ParseLogistic;
622 m_ParserFunctions[tflite::BuiltinOperator_L2_NORMALIZATION] = &TfLiteParserImpl::ParseL2Normalization;
623 m_ParserFunctions[tflite::BuiltinOperator_MAX_POOL_2D] = &TfLiteParserImpl::ParseMaxPool2D;
624 m_ParserFunctions[tflite::BuiltinOperator_MAXIMUM] = &TfLiteParserImpl::ParseMaximum;
625 m_ParserFunctions[tflite::BuiltinOperator_MEAN] = &TfLiteParserImpl::ParseMean;
626 m_ParserFunctions[tflite::BuiltinOperator_MINIMUM] = &TfLiteParserImpl::ParseMinimum;
627 m_ParserFunctions[tflite::BuiltinOperator_MUL] = &TfLiteParserImpl::ParseMul;
628 m_ParserFunctions[tflite::BuiltinOperator_NEG] = &TfLiteParserImpl::ParseNeg;
629 m_ParserFunctions[tflite::BuiltinOperator_PACK] = &TfLiteParserImpl::ParsePack;
630 m_ParserFunctions[tflite::BuiltinOperator_PAD] = &TfLiteParserImpl::ParsePad;
631 m_ParserFunctions[tflite::BuiltinOperator_QUANTIZE] = &TfLiteParserImpl::ParseQuantize;
632 m_ParserFunctions[tflite::BuiltinOperator_RELU] = &TfLiteParserImpl::ParseRelu;
633 m_ParserFunctions[tflite::BuiltinOperator_RELU6] = &TfLiteParserImpl::ParseRelu6;
Sadik Armagana2747482021-02-09 10:28:54 +0000634 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MAX] = &TfLiteParserImpl::ParseReduceMax;
635 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MIN] = &TfLiteParserImpl::ParseReduceMin;
Kevin May7d96b162021-02-03 17:38:41 +0000636 m_ParserFunctions[tflite::BuiltinOperator_RESHAPE] = &TfLiteParserImpl::ParseReshape;
637 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_BILINEAR] = &TfLiteParserImpl::ParseResizeBilinear;
638 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_NEAREST_NEIGHBOR] = &TfLiteParserImpl::ParseResizeNearestNeighbor;
639 m_ParserFunctions[tflite::BuiltinOperator_SLICE] = &TfLiteParserImpl::ParseSlice;
640 m_ParserFunctions[tflite::BuiltinOperator_SOFTMAX] = &TfLiteParserImpl::ParseSoftmax;
641 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_BATCH_ND] = &TfLiteParserImpl::ParseSpaceToBatchND;
642 m_ParserFunctions[tflite::BuiltinOperator_SPLIT] = &TfLiteParserImpl::ParseSplit;
643 m_ParserFunctions[tflite::BuiltinOperator_SPLIT_V] = &TfLiteParserImpl::ParseSplitV;
644 m_ParserFunctions[tflite::BuiltinOperator_SQUEEZE] = &TfLiteParserImpl::ParseSqueeze;
645 m_ParserFunctions[tflite::BuiltinOperator_STRIDED_SLICE] = &TfLiteParserImpl::ParseStridedSlice;
646 m_ParserFunctions[tflite::BuiltinOperator_SUB] = &TfLiteParserImpl::ParseSub;
647 m_ParserFunctions[tflite::BuiltinOperator_SUM] = &TfLiteParserImpl::ParseSum;
648 m_ParserFunctions[tflite::BuiltinOperator_TANH] = &TfLiteParserImpl::ParseTanH;
649 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE] = &TfLiteParserImpl::ParseTranspose;
650 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE_CONV] = &TfLiteParserImpl::ParseTransposeConv;
651 m_ParserFunctions[tflite::BuiltinOperator_UNPACK] = &TfLiteParserImpl::ParseUnpack;
652 m_ParserFunctions[tflite::BuiltinOperator_DIV] = &TfLiteParserImpl::ParseDiv;
653 m_ParserFunctions[tflite::BuiltinOperator_ARG_MAX] = &TfLiteParserImpl::ParseArgMax;
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100654 // register supported custom operators
Kevin May7d96b162021-02-03 17:38:41 +0000655 m_CustomParserFunctions["TFLite_Detection_PostProcess"] = &TfLiteParserImpl::ParseDetectionPostProcess;
telsoa01c577f2c2018-08-31 09:22:23 +0100656}
657
Kevin May7d96b162021-02-03 17:38:41 +0000658void TfLiteParserImpl::ResetParser()
telsoa01c577f2c2018-08-31 09:22:23 +0100659{
660 m_Network = armnn::INetworkPtr(nullptr, nullptr);
661 m_Model = nullptr;
662 m_SubgraphConnections.clear();
663}
664
Kevin May7d96b162021-02-03 17:38:41 +0000665INetworkPtr TfLiteParserImpl::CreateNetworkFromBinaryFile(const char* graphFile)
telsoa01c577f2c2018-08-31 09:22:23 +0100666{
667 ResetParser();
668 m_Model = LoadModelFromFile(graphFile);
669 return CreateNetworkFromModel();
670}
671
Kevin May7d96b162021-02-03 17:38:41 +0000672INetworkPtr TfLiteParserImpl::CreateNetworkFromBinary(const std::vector<uint8_t> & binaryContent)
telsoa01c577f2c2018-08-31 09:22:23 +0100673{
674 ResetParser();
675 m_Model = LoadModelFromBinary(binaryContent.data(), binaryContent.size());
676 return CreateNetworkFromModel();
677}
678
Kevin May7d96b162021-02-03 17:38:41 +0000679INetworkPtr TfLiteParserImpl::CreateNetworkFromModel()
telsoa01c577f2c2018-08-31 09:22:23 +0100680{
Sadik Armagand109a4d2020-07-28 10:42:13 +0100681
682 using NetworkOptions = std::vector<BackendOptions>;
683 NetworkOptions networkOptions = {};
684 if (m_Options && m_Options.value().m_InferAndValidate)
685 {
686 BackendOptions shapeInferenceMethodOption("ShapeInferenceMethod",
687 {
688 { "InferAndValidate", true }
689 });
690
691 networkOptions.push_back(shapeInferenceMethodOption);
692 }
693
694 m_Network = INetwork::Create(networkOptions);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100695 ARMNN_ASSERT(m_Model.get() != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +0100696
telsoa01c577f2c2018-08-31 09:22:23 +0100697 if (m_Model->subgraphs.size() != 1)
698 {
699 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100700 fmt::format("Current TfLite parser only supports 1 subgraph. Current one has: {} {}",
701 m_Model->subgraphs.size(),
702 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100703 }
704
705 size_t subgraphIndex = 0;
Colm Donelan6350d272020-06-09 16:56:25 +0100706 size_t operatorIndex = 0;
707 try
telsoa01c577f2c2018-08-31 09:22:23 +0100708 {
Colm Donelan6350d272020-06-09 16:56:25 +0100709 for (SubgraphPtr const& subgraph : m_Model->subgraphs)
telsoa01c577f2c2018-08-31 09:22:23 +0100710 {
Colm Donelan6350d272020-06-09 16:56:25 +0100711 m_SubgraphConnections.emplace_back(subgraph->tensors.size());
712 for (OperatorPtr const& op : subgraph->operators)
telsoa01c577f2c2018-08-31 09:22:23 +0100713 {
Colm Donelan6350d272020-06-09 16:56:25 +0100714 auto const& opCodePtr = m_Model->operator_codes[op->opcode_index];
telsoa01c577f2c2018-08-31 09:22:23 +0100715 auto builtinCode = opCodePtr->builtin_code;
716
717 if (builtinCode > tflite::BuiltinOperator_MAX)
718 {
James Ward58dec6b2020-09-11 17:32:44 +0100719 throw ParseException(fmt::format("Operator code {} is out of range 0-{}. "
720 "subgraph:{} operator idx:{}. {}",
721 builtinCode, tflite::BuiltinOperator_MAX, subgraphIndex,
722 operatorIndex, CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100723 }
724
725 // lookup and call the parser function
Colm Donelan6350d272020-06-09 16:56:25 +0100726 auto& parserFunction = m_ParserFunctions[builtinCode];
telsoa01c577f2c2018-08-31 09:22:23 +0100727 (this->*parserFunction)(subgraphIndex, operatorIndex);
Colm Donelan6350d272020-06-09 16:56:25 +0100728 ++operatorIndex;
telsoa01c577f2c2018-08-31 09:22:23 +0100729 }
telsoa01c577f2c2018-08-31 09:22:23 +0100730
Colm Donelan6350d272020-06-09 16:56:25 +0100731 SetupInputLayers(subgraphIndex);
732 SetupOutputLayers(subgraphIndex);
733 SetupConstantLayers(subgraphIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100734
Colm Donelan6350d272020-06-09 16:56:25 +0100735 ++subgraphIndex;
736 operatorIndex = 0;
telsoa01c577f2c2018-08-31 09:22:23 +0100737 }
telsoa01c577f2c2018-08-31 09:22:23 +0100738 }
Colm Donelan6350d272020-06-09 16:56:25 +0100739 catch (const ParseException& e)
telsoa01c577f2c2018-08-31 09:22:23 +0100740 {
Colm Donelan6350d272020-06-09 16:56:25 +0100741 std::stringstream errorString;
742 errorString << "Failed to parse operator #" << operatorIndex << " within subgraph #"
743 << subgraphIndex << " error: " << e.what();
744 ARMNN_LOG(error) << errorString.str();
745 std::stringstream errors;
746 errors << errorString.str() << "\n";
telsoa01c577f2c2018-08-31 09:22:23 +0100747 throw ParseException(errors.str());
748 }
749
750 // establish the connections from the layer outputs to the inputs of the subsequent layers
Colm Donelan6350d272020-06-09 16:56:25 +0100751 for (subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100752 {
753 for (size_t tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
754 {
755 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot != nullptr)
756 {
757 for (size_t inputSlotIdx = 0;
758 inputSlotIdx < m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size();
759 ++inputSlotIdx)
760 {
761 m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot->Connect(
762 *(m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots[inputSlotIdx]));
763 }
764 }
765 }
766 }
767
768 return std::move(m_Network);
769}
770
Kevin May7d96b162021-02-03 17:38:41 +0000771void TfLiteParserImpl::RegisterProducerOfTensor(size_t subgraphIndex,
772 size_t tensorIndex,
773 armnn::IOutputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100774{
775 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100776 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
777 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100778
779 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
780
781 // assuming there is only one producer for that tensor
782 if (tensorSlots.outputSlot != nullptr)
783 {
James Ward58dec6b2020-09-11 17:32:44 +0100784 throw ParseException(fmt::format("Another layer has already registered itself as the producer of "
785 "subgraph:{} tensor:{} {}",
786 subgraphIndex,
787 tensorIndex,
788 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +0100789 }
790
791 tensorSlots.outputSlot = slot;
792}
793
Kevin May7d96b162021-02-03 17:38:41 +0000794void TfLiteParserImpl::RegisterConsumerOfTensor(size_t subgraphIndex,
795 size_t tensorIndex,
796 armnn::IInputSlot* slot)
telsoa01c577f2c2018-08-31 09:22:23 +0100797{
798 CHECK_TENSOR(m_Model, subgraphIndex, tensorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100799 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
800 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100801
Finn Williamsd4fa5452021-03-01 12:31:41 +0000802 TensorSlots& tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +0100803 tensorSlots.inputSlots.push_back(slot);
804}
805
Kevin May7d96b162021-02-03 17:38:41 +0000806void TfLiteParserImpl::ParseCustomOperator(size_t subgraphIndex, size_t operatorIndex)
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100807{
808 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
809
810 // NOTE: By default we presume the custom operator is not supported
Kevin May7d96b162021-02-03 17:38:41 +0000811 auto customParserFunction = &TfLiteParserImpl::ParseUnsupportedOperator;
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100812
813 // Identify custom code defined for custom operator
814 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
815 const auto& customCode = m_Model->operator_codes[operatorPtr->opcode_index]->custom_code;
816
817 // Find parser function that correspondes to custom code (if any)
818 auto iterator = m_CustomParserFunctions.find(customCode);
819 if (iterator != m_CustomParserFunctions.end())
820 {
821 customParserFunction = iterator->second;
822 }
823
824 // Run parser function
825 (this->*customParserFunction)(subgraphIndex, operatorIndex);
826}
827
Kevin May7d96b162021-02-03 17:38:41 +0000828void TfLiteParserImpl::ParseUnsupportedOperator(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100829{
830 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100831
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100832 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
833
834 auto opcodeIndex = operatorPtr->opcode_index;
835 auto opcode = m_Model->operator_codes[opcodeIndex]->builtin_code;
836
837 if (!m_Options || !m_Options.value().m_StandInLayerForUnsupported)
838 {
839 // Do not add StandInLayer, throw ParseException instead
840 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +0100841 fmt::format("Operator not supported. "
842 "subgraph:{} operator:{} "
843 "opcode_index:{} opcode:{} / {} {}",
844 subgraphIndex,
845 operatorIndex,
846 opcodeIndex,
847 opcode,
848 tflite::EnumNameBuiltinOperator(opcode),
849 CHECK_LOCATION().AsString()));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100850 }
851
852 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
853 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
854
Matthew Sloyan589e3e82020-09-11 16:17:48 +0100855 const unsigned int numInputs = armnn::numeric_cast<unsigned int>(inputs.size());
856 const unsigned int numOutputs = armnn::numeric_cast<unsigned int>(outputs.size());
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100857
858 StandInDescriptor descriptor(numInputs, numOutputs);
James Ward58dec6b2020-09-11 17:32:44 +0100859 auto layerName = fmt::format("StandIn:{}:{}:{}", subgraphIndex, operatorIndex, opcode);
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100860
861 // Add a non-executable StandInLayer as a placeholder for any unsupported operator
862 IConnectableLayer* layer = m_Network->AddStandInLayer(descriptor, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +0100863 ARMNN_ASSERT(layer != nullptr);
864
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100865 for (unsigned int i = 0u; i < numOutputs; ++i)
866 {
Sadik Armagand109a4d2020-07-28 10:42:13 +0100867 layer->GetOutputSlot(i).SetTensorInfo(ToTensorInfo(outputs[i], true));
Aron Virginas-Tarc975f922019-10-23 17:38:17 +0100868 }
869
870 auto inputTensorIds = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
871 auto outputTensorIds = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
872
873 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIds);
874 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIds);
telsoa01c577f2c2018-08-31 09:22:23 +0100875}
876
Kevin May7d96b162021-02-03 17:38:41 +0000877void TfLiteParserImpl::ParseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100878{
879 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
880
881 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
882 const auto * options = operatorPtr->builtin_options.AsConv2DOptions();
883
884 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
885
886 Convolution2dDescriptor desc;
887 desc.m_BiasEnabled = false;
888 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
889 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +0000890 desc.m_DataLayout = armnn::DataLayout::NHWC;
Pablo Tellof0bd6832019-04-26 17:58:13 +0100891 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
892 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +0000893
telsoa01c577f2c2018-08-31 09:22:23 +0100894 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
895 CHECK_VALID_SIZE(inputs.size(), 2, 3);
896
897 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
898 CHECK_VALID_SIZE(outputs.size(), 1);
899
900 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
901 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
902
903 // assuming input is NHWC
904 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
905 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
906
907 // assuming the filter is OHWI : Output, H, W, Input
908 // which is essentially the same as NHWC
909 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
910 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
911
Pablo Tellof0bd6832019-04-26 17:58:13 +0100912 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
913 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
914 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
915 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +0100916
Finn Williamsd4fa5452021-03-01 12:31:41 +0000917 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
Matthew Jackson74bf7da2019-08-16 16:51:42 +0100918 armnn::IConnectableLayer* layer = nullptr;
telsoa01c577f2c2018-08-31 09:22:23 +0100919
James Ward58dec6b2020-09-11 17:32:44 +0100920 auto layerName = fmt::format("Conv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +0100921
922 if (inputs.size() == 3)
923 {
924 desc.m_BiasEnabled = true;
925 armnn::TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +0000926 auto biasTensorAndData = CreateConstTensorNonPermuted(inputs[2], biasTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +0100927 layer = m_Network->AddConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +0000928 filterTensorAndData,
929 Optional<ConstTensor>(biasTensorAndData),
telsoa01c577f2c2018-08-31 09:22:23 +0100930 layerName.c_str());
931 }
932 else
933 {
934 layer = m_Network->AddConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +0000935 filterTensorAndData,
Matteo Martincighfc598e12019-05-14 10:36:13 +0100936 EmptyOptional(),
telsoa01c577f2c2018-08-31 09:22:23 +0100937 layerName.c_str());
938 }
939
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +0100940 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +0100941
Sadik Armagand109a4d2020-07-28 10:42:13 +0100942 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +0000943 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +0100944
945 // register the input connection slots for the layer, connections are made after all layers have been created
946 // only the tensors for the inputs are relevant, exclude the const tensors
947 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +0000948 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
telsoa01c577f2c2018-08-31 09:22:23 +0100949
jimfly01c25411c2018-11-14 17:47:22 +0000950 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +0100951 // register the output connection slots for the layer, connections are made after all layers have been created
952 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
953 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
954}
955
Kevin May7d96b162021-02-03 17:38:41 +0000956void TfLiteParserImpl::ParseDepthwiseConv2D(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +0100957{
958 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
959
960 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
961 const auto * options = operatorPtr->builtin_options.AsDepthwiseConv2DOptions();
962
963 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
964
965 DepthwiseConvolution2dDescriptor desc;
966 desc.m_BiasEnabled = false;
967 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
968 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
jimfly01c25411c2018-11-14 17:47:22 +0000969 desc.m_DataLayout = armnn::DataLayout::NHWC;
Matthew Jacksond6a9dee2019-07-22 13:53:24 +0100970 CHECKED_NON_NEGATIVE(options->depth_multiplier);
telsoa01c577f2c2018-08-31 09:22:23 +0100971
972 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
973 CHECK_VALID_SIZE(inputs.size(), 2, 3);
974 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
975 CHECK_VALID_SIZE(outputs.size(), 1);
Pablo Tellof0bd6832019-04-26 17:58:13 +0100976 desc.m_DilationX = CHECKED_NON_NEGATIVE(options->dilation_w_factor);
977 desc.m_DilationY = CHECKED_NON_NEGATIVE(options->dilation_h_factor);
Kevin May83add212019-03-26 11:39:19 +0000978
Keith Davis0c2eeac2020-02-11 16:51:50 +0000979 // Mappings from TensorflowLite filter tensors to the ArmNN filter tensors (ArmNN weights have to be [M, I, H, W])
980 PermutationVector permutationVector{ 2, 3, 1, 0 }; // [H, W, I, M] -> [M, I, H, W]
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +0100981
telsoa01c577f2c2018-08-31 09:22:23 +0100982 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Keith Davis0c2eeac2020-02-11 16:51:50 +0000983 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1], permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +0100984
Matteo Martincigh747ef822018-12-18 09:26:39 +0000985 // Assuming input is NHWC
telsoa01c577f2c2018-08-31 09:22:23 +0100986 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
987 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
Matteo Martincigh747ef822018-12-18 09:26:39 +0000988
989 // TensorflowLite weights come in the format [1, H, W, I * M]
telsoa01c577f2c2018-08-31 09:22:23 +0100990 unsigned int filterHeight = filterTensorInfo.GetShape()[1];
991 unsigned int filterWidth = filterTensorInfo.GetShape()[2];
992
Matteo Martincigh747ef822018-12-18 09:26:39 +0000993 // Reshape weights as [ H, W, I, M ]
994 filterTensorInfo.SetShape({ filterHeight,
995 filterWidth,
996 inputTensorInfo.GetShape()[3],
997 filterTensorInfo.GetShape()[3] / inputTensorInfo.GetShape()[3] });
998
Pablo Tellof0bd6832019-04-26 17:58:13 +0100999 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1000 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1001 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1002 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
telsoa01c577f2c2018-08-31 09:22:23 +01001003
Finn Williamsd4fa5452021-03-01 12:31:41 +00001004 auto filterTensorAndData = CreateConstTensorPermuted(inputs[1], filterTensorInfo, permutationVector);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001005 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001006 auto layerName = fmt::format("DepthwiseConv2D:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001007
1008 if (inputs.size() == 3)
1009 {
1010 desc.m_BiasEnabled = true;
1011 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00001012 auto biasTensorAndData = CreateConstTensorNonPermuted(inputs[2], biasTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001013 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
1014 filterTensorAndData.first,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001015 Optional<ConstTensor>(biasTensorAndData),
telsoa01c577f2c2018-08-31 09:22:23 +01001016 layerName.c_str());
1017 }
1018 else
1019 {
1020 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
1021 filterTensorAndData.first,
Matteo Martincighfc598e12019-05-14 10:36:13 +01001022 EmptyOptional(),
telsoa01c577f2c2018-08-31 09:22:23 +01001023 layerName.c_str());
1024 }
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001025 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001026
Sadik Armagand109a4d2020-07-28 10:42:13 +01001027 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
jimfly01c25411c2018-11-14 17:47:22 +00001028 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
telsoa01c577f2c2018-08-31 09:22:23 +01001029
1030 // register the input connection slots for the layer, connections are made after all layers have been created
1031 // only the tensors for the inputs are relevant, exclude the const tensors
1032 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001033 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
telsoa01c577f2c2018-08-31 09:22:23 +01001034
jimfly01c25411c2018-11-14 17:47:22 +00001035 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
telsoa01c577f2c2018-08-31 09:22:23 +01001036 // register the output connection slots for the layer, connections are made after all layers have been created
1037 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1038 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1039}
1040
Kevin May7d96b162021-02-03 17:38:41 +00001041void TfLiteParserImpl::ParseDequantize(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsed66d142019-12-06 09:55:55 +00001042{
1043 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1044
1045 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1046 CHECK_VALID_SIZE(inputs.size(), 1);
1047
1048 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1049 CHECK_VALID_SIZE(outputs.size(), 1);
1050
James Ward58dec6b2020-09-11 17:32:44 +01001051 auto layerName = fmt::format("Dequantize:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsed66d142019-12-06 09:55:55 +00001052
1053 IConnectableLayer* layer = m_Network->AddDequantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001054 ARMNN_ASSERT(layer != nullptr);
Finn Williamsed66d142019-12-06 09:55:55 +00001055
Sadik Armagand109a4d2020-07-28 10:42:13 +01001056 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Finn Williamsed66d142019-12-06 09:55:55 +00001057 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1058
1059 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1060 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1061
1062 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1063 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1064}
1065
Kevin May7d96b162021-02-03 17:38:41 +00001066void TfLiteParserImpl::ParseExp(size_t subgraphIndex, size_t operatorIndex)
Derek Lambertif0176992020-04-28 13:37:49 +01001067{
1068 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1069
1070 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1071 CHECK_VALID_SIZE(inputs.size(), 1);
1072
1073 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1074 CHECK_VALID_SIZE(outputs.size(), 1);
1075
James Ward58dec6b2020-09-11 17:32:44 +01001076 auto layerName = fmt::format("Exp:{}:{}", subgraphIndex, operatorIndex);
Derek Lambertif0176992020-04-28 13:37:49 +01001077
1078 ElementwiseUnaryDescriptor desc;
1079 desc.m_Operation = UnaryOperation::Exp;
1080 IConnectableLayer* layer = m_Network->AddElementwiseUnaryLayer(desc, layerName.c_str());
1081 ARMNN_ASSERT(layer != nullptr);
1082
Sadik Armagand109a4d2020-07-28 10:42:13 +01001083 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Derek Lambertif0176992020-04-28 13:37:49 +01001084 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1085
1086 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1087 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1088
1089 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1090 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1091}
1092
Kevin May7d96b162021-02-03 17:38:41 +00001093void TfLiteParserImpl::ParseTranspose(size_t subgraphIndex, size_t operatorIndex)
Keith Davis4cd29a02019-09-09 14:49:20 +01001094{
1095 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1096
1097 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Kevin May85d92602019-09-27 17:21:06 +01001098 CHECK_VALID_SIZE(inputs.size(), 1, 2);
Keith Davis4cd29a02019-09-09 14:49:20 +01001099
1100 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1101 CHECK_VALID_SIZE(outputs.size(), 1);
1102
James Ward58dec6b2020-09-11 17:32:44 +01001103 auto layerName = fmt::format("Transpose:{}:{}", subgraphIndex, operatorIndex);
Mike Kelly08759e22020-03-02 11:41:31 +00001104 TransposeDescriptor desc;
Keith Davis4cd29a02019-09-09 14:49:20 +01001105
josh minorba424d22019-11-13 10:55:17 -06001106 if (inputs.size() == 2)
Kevin May85d92602019-09-27 17:21:06 +01001107 {
1108 armnn::TensorInfo permuteTensorInfo = ToTensorInfo(inputs[1]);
1109 BufferRawPtr permuteBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
josh minorba424d22019-11-13 10:55:17 -06001110 auto numPermVecElements = permuteTensorInfo.GetNumElements();
1111 std::vector<unsigned int> permuteShape(numPermVecElements);
Kevin May85d92602019-09-27 17:21:06 +01001112 ::memcpy(permuteShape.data(), permuteBufferPtr->data.data(), permuteTensorInfo.GetNumBytes());
Mike Kelly08759e22020-03-02 11:41:31 +00001113 PermutationVector permutationVector(permuteShape.data(), permuteTensorInfo.GetNumElements());
Kevin May85d92602019-09-27 17:21:06 +01001114
Mike Kelly08759e22020-03-02 11:41:31 +00001115 desc = TransposeDescriptor(permutationVector);
Kevin May85d92602019-09-27 17:21:06 +01001116 }
1117
James Conroy05102392020-06-24 15:39:55 +01001118 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001119 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001120 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
Keith Davis4cd29a02019-09-09 14:49:20 +01001121
James Conroy05102392020-06-24 15:39:55 +01001122 IConnectableLayer* layer = m_Network->AddTransposeLayer(desc, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001123 ARMNN_ASSERT(layer != nullptr);
Keith Davis4cd29a02019-09-09 14:49:20 +01001124 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1125
1126 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1127 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1128
1129 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1130 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1131}
1132
Kevin May7d96b162021-02-03 17:38:41 +00001133void TfLiteParserImpl::ParseTransposeConv(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001134{
1135 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1136
1137 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1138 const auto * options = operatorPtr->builtin_options.AsTransposeConvOptions();
1139
1140 TransposeConvolution2dDescriptor desc;
1141 desc.m_BiasEnabled = false;
1142 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1143 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1144 desc.m_DataLayout = armnn::DataLayout::NHWC;
1145
1146 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
David Monahan61683802021-01-12 09:11:07 +00001147 if (inputs.size() == 4)
1148 {
1149 desc.m_BiasEnabled = true;
1150 }
1151 else
1152 {
1153 CHECK_VALID_SIZE(inputs.size(), 3);
1154 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001155
1156 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1157 CHECK_VALID_SIZE(outputs.size(), 1);
1158
Colm Donelan0ad3ef12020-07-03 15:54:28 +01001159 if (inputs[0])
1160 {
1161 armnn::TensorInfo tensorInfo = ToTensorInfo(inputs[0]);
1162 std::vector<int> output_shape(tensorInfo.GetNumElements());
1163 if (tensorInfo.GetDataType() == DataType::Signed32)
1164 {
1165 ::memcpy(output_shape.data(), GetBuffer(m_Model, inputs[0]->buffer)->data.data(), tensorInfo.GetNumBytes());
1166 }
1167 if (tensorInfo.GetDataType() == DataType::QAsymmU8)
1168 {
1169 for(unsigned int i=0; i < tensorInfo.GetNumElements(); i++)
1170 {
1171 output_shape[i] = GetBuffer(m_Model, inputs[0]->buffer)->data.data()[i];
1172 }
1173 }
1174 // Change from signed to unsigned int to store in TransposeConvolution2dDescriptor.
1175 for (int dimension : output_shape)
1176 {
1177 desc.m_OutputShape.push_back(static_cast<unsigned int>(dimension));
1178 }
1179 desc.m_OutputShapeEnabled = true;
1180 }
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001181 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[2]);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001182 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
1183
1184 // TfLite uses NHWC tensors
1185 const unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1186 const unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1187
1188 const unsigned int filterHeight = filterTensorInfo.GetShape()[1];
1189 const unsigned int filterWidth = filterTensorInfo.GetShape()[2];
1190
1191 CalcPadding(inputHeight,
1192 filterHeight,
1193 desc.m_StrideY,
1194 1, // DilationY
1195 desc.m_PadTop,
1196 desc.m_PadBottom,
1197 options->padding);
1198
1199 CalcPadding(inputWidth,
1200 filterWidth,
1201 desc.m_StrideX,
1202 1, // DilationX
1203 desc.m_PadLeft,
1204 desc.m_PadRight,
1205 options->padding);
1206
Finn Williamsd4fa5452021-03-01 12:31:41 +00001207 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001208
1209 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01001210 auto layerName = fmt::format("TransposeConv:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001211
David Monahan61683802021-01-12 09:11:07 +00001212 if (desc.m_BiasEnabled)
1213 {
1214 auto biasTensorInfo = ToTensorInfo(inputs[3]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00001215 auto biasConstTensor = CreateConstTensorNonPermuted(inputs[3], biasTensorInfo);
David Monahan61683802021-01-12 09:11:07 +00001216 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001217 filterTensorAndData,
1218 biasConstTensor,
David Monahan61683802021-01-12 09:11:07 +00001219 layerName.c_str());
1220 }
1221 else
1222 {
1223 layer = m_Network->AddTransposeConvolution2dLayer(desc,
Finn Williamsd4fa5452021-03-01 12:31:41 +00001224 filterTensorAndData,
David Monahan61683802021-01-12 09:11:07 +00001225 EmptyOptional(),
1226 layerName.c_str());
1227 }
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001228
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001229 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001230
Sadik Armagand109a4d2020-07-28 10:42:13 +01001231 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001232 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1233
1234 // only the tensors for the inputs are relevant, exclude the const (filter) tensor
1235 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Matthew Jacksonccb25ea2019-08-20 17:18:33 +01001236 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[2]});
Matthew Jackson74bf7da2019-08-16 16:51:42 +01001237
1238 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1239 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1240}
1241
Kevin May7d96b162021-02-03 17:38:41 +00001242void TfLiteParserImpl::ParseAveragePool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001243{
1244 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Average);
1245}
1246
Kevin May7d96b162021-02-03 17:38:41 +00001247void TfLiteParserImpl::ParseBatchToSpaceND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001248{
1249 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1250
1251 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1252 CHECK_VALID_SIZE(inputs.size(), 3);
1253
1254 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1255 CHECK_VALID_SIZE(outputs.size(), 1);
1256
1257 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1258 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1259
1260 armnn::TensorInfo cropsTensorInfo = ToTensorInfo(inputs[2]);
1261 BufferRawPtr cropsBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1262
1263 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1264 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1265
1266 std::vector<unsigned int> cropsVector(cropsTensorInfo.GetNumElements());
1267 ::memcpy(cropsVector.data(), cropsBufferPtr->data.data(), cropsTensorInfo.GetNumBytes());
1268
1269 size_t step = 2;
1270 std::vector<std::pair<unsigned int, unsigned int>> crops;
1271 for (unsigned int i = 0; i < cropsTensorInfo.GetNumElements() / step; ++i)
1272 {
1273 crops.emplace_back(cropsVector[i * step], cropsVector[i * step + 1]);
1274 }
1275
1276 armnn::BatchToSpaceNdDescriptor desc;
1277 desc.m_BlockShape = blockShape;
1278 desc.m_Crops = crops;
1279 desc.m_DataLayout = armnn::DataLayout::NHWC;
1280
James Ward58dec6b2020-09-11 17:32:44 +01001281 auto layerName = fmt::format("BatchToSpaceND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001282
James Conroy05102392020-06-24 15:39:55 +01001283 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001284 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001285 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1286
1287 IConnectableLayer* layer = m_Network->AddBatchToSpaceNdLayer(desc, layerName.c_str());
1288 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesdb947e22019-02-08 18:52:21 -02001289 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1290
1291 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1292 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1293
1294 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1295 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1296}
1297
Kevin May7d96b162021-02-03 17:38:41 +00001298void TfLiteParserImpl::ParseL2Normalization(size_t subgraphIndex, size_t operatorIndex)
Matthew Jackson28c94572019-07-18 10:47:03 +01001299{
1300 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1301
1302 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1303 CHECK_VALID_SIZE(inputs.size(), 1);
1304
1305 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1306 CHECK_VALID_SIZE(outputs.size(), 1);
1307
1308 L2NormalizationDescriptor desc;
1309 desc.m_DataLayout = armnn::DataLayout::NHWC;
James Ward58dec6b2020-09-11 17:32:44 +01001310 auto layerName = fmt::format("L2Normalization:{}:{}", subgraphIndex, operatorIndex);
Matthew Jackson28c94572019-07-18 10:47:03 +01001311 IConnectableLayer* layer = m_Network->AddL2NormalizationLayer(desc, layerName.c_str());
1312
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001313 ARMNN_ASSERT(layer != nullptr);
Matthew Jackson28c94572019-07-18 10:47:03 +01001314
Sadik Armagand109a4d2020-07-28 10:42:13 +01001315 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jackson28c94572019-07-18 10:47:03 +01001316 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1317
1318 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1319 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1320
1321 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1322 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1323}
1324
Kevin May7d96b162021-02-03 17:38:41 +00001325void TfLiteParserImpl::ParseMaxPool2D(size_t subgraphIndex, size_t operatorIndex)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001326{
1327 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Max);
1328}
1329
Kevin May7d96b162021-02-03 17:38:41 +00001330void TfLiteParserImpl::ParseMaximum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001331{
1332 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1333
1334 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1335 CHECK_VALID_SIZE(inputs.size(), 2);
1336
1337 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1338 CHECK_VALID_SIZE(outputs.size(), 1);
1339
James Ward58dec6b2020-09-11 17:32:44 +01001340 auto layerName = fmt::format("Maximum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001341
1342 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1343 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1344 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001345
Sadik Armagand109a4d2020-07-28 10:42:13 +01001346 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001347 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1348
1349 IConnectableLayer* layer = m_Network->AddMaximumLayer(layerName.c_str());
1350 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001351 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1352
1353 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001354 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesb8d805e2019-02-12 22:57:13 -02001355
1356 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1357 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1358}
1359
Kevin May7d96b162021-02-03 17:38:41 +00001360void TfLiteParserImpl::ParseMinimum(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001361{
1362 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1363
1364 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1365 CHECK_VALID_SIZE(inputs.size(), 2);
1366
1367 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1368 CHECK_VALID_SIZE(outputs.size(), 1);
1369
James Ward58dec6b2020-09-11 17:32:44 +01001370 auto layerName = fmt::format("Minimum:{}:{}", subgraphIndex, operatorIndex);
James Conroy05102392020-06-24 15:39:55 +01001371
1372 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1373 TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1374 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName, "Input 0", "Input 1");
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001375
Sadik Armagand109a4d2020-07-28 10:42:13 +01001376 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001377 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1378
1379 IConnectableLayer* layer = m_Network->AddMinimumLayer(layerName.c_str());
1380 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001381 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1382
1383 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001384 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalves8f6d7a72019-02-12 22:58:18 -02001385
1386 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1387 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1388}
1389
Kevin May7d96b162021-02-03 17:38:41 +00001390void TfLiteParserImpl::ParsePool(size_t subgraphIndex,
1391 size_t operatorIndex,
1392 PoolingAlgorithm algorithm)
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001393{
1394 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1395
1396 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1397 const auto * options = operatorPtr->builtin_options.AsPool2DOptions();
1398
1399 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
1400
1401 std::string layerName;
1402
1403 switch (algorithm)
1404 {
1405 case PoolingAlgorithm::Average:
1406 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001407 fmt::format("AveragePool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001408 break;
1409 case PoolingAlgorithm::Max:
1410 layerName =
James Ward58dec6b2020-09-11 17:32:44 +01001411 fmt::format("MaxPool2D:{}:{}", subgraphIndex, operatorIndex);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001412 break;
1413 default:
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001414 ARMNN_ASSERT_MSG(false, "Unsupported Pooling Algorithm");
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001415 }
1416
1417 Pooling2dDescriptor desc;
1418
1419 desc.m_PoolType = algorithm;
1420 desc.m_StrideX = CHECKED_NON_NEGATIVE(options->stride_w);
1421 desc.m_StrideY = CHECKED_NON_NEGATIVE(options->stride_h);
1422 desc.m_PoolWidth = CHECKED_NON_NEGATIVE(options->filter_width);
1423 desc.m_PoolHeight = CHECKED_NON_NEGATIVE(options->filter_height);
1424 desc.m_PaddingMethod = PaddingMethod::Exclude;
1425 desc.m_OutputShapeRounding = OutputShapeRounding::Floor;
jimfly01c25411c2018-11-14 17:47:22 +00001426 desc.m_DataLayout = armnn::DataLayout::NHWC;
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001427
1428 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1429 CHECK_VALID_SIZE(inputs.size(), 1);
1430 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1431
1432 // assuming input is NHWC
1433 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1434 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1435
Pablo Tellof0bd6832019-04-26 17:58:13 +01001436 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, 1u,
1437 desc.m_PadTop, desc.m_PadBottom, options->padding);
1438 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, 1u,
1439 desc.m_PadLeft, desc.m_PadRight, options->padding);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001440
1441 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1442 CHECK_VALID_SIZE(outputs.size(), 1);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001443
Sadik Armagand109a4d2020-07-28 10:42:13 +01001444 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001445 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1446
1447 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, layerName.c_str());
1448 ARMNN_ASSERT(layer != nullptr);
jimfly01c25411c2018-11-14 17:47:22 +00001449 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001450
1451 // register the input connection slots for the layer, connections are made after all layers have been created
1452 // only the tensors for the inputs are relevant, exclude the const tensors
1453 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
jimfly01c25411c2018-11-14 17:47:22 +00001454 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001455
jimfly01c25411c2018-11-14 17:47:22 +00001456 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Nattapat Chaimanowongb66504b2018-10-17 15:19:14 +01001457 // register the output connection slots for the layer, connections are made after all layers have been created
1458 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1459 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1460}
1461
Kevin May7d96b162021-02-03 17:38:41 +00001462void TfLiteParserImpl::ParseSlice(size_t subgraphIndex, size_t operatorIndex)
josh minorba424d22019-11-13 10:55:17 -06001463{
1464 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1465
1466 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1467 CHECK_VALID_SIZE(inputs.size(), 3);
1468 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1469 CHECK_VALID_SIZE(outputs.size(), 1);
1470
1471 SliceDescriptor desc;
1472
1473 // set begin tensor info for slice descriptor
1474 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
1475 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1476
1477 std::vector<unsigned int> begin(beginTensorInfo.GetNumElements());
1478 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
1479
1480 // set size tensor info for slice descriptor
1481 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[2]);
1482 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1483
1484 std::vector<unsigned int> size(sizeTensorInfo.GetNumElements());
1485 ::memcpy(size.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
1486 desc = SliceDescriptor(begin, size);
1487
James Ward58dec6b2020-09-11 17:32:44 +01001488 auto layerName = fmt::format("Slice:{}:{}", subgraphIndex, operatorIndex);
josh minorba424d22019-11-13 10:55:17 -06001489
James Conroy05102392020-06-24 15:39:55 +01001490 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001491 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001492 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1493
1494 IConnectableLayer* const layer = m_Network->AddSliceLayer(desc, layerName.c_str());
josh minorba424d22019-11-13 10:55:17 -06001495 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1496
1497 // register the input connection slots for the layer, connections are made after all layers have been created
1498 // only the tensors for the inputs are relevant, exclude the const tensors
1499 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1500 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1501
1502 // register the output connection slots for the layer, connections are made after all layers have been created
1503 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1504 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1505}
1506
Kevin May7d96b162021-02-03 17:38:41 +00001507void TfLiteParserImpl::ParseSoftmax(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001508{
1509 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1510 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1511 const auto * options = operatorPtr->builtin_options.AsSoftmaxOptions();
1512
1513 SoftmaxDescriptor desc;
1514 desc.m_Beta = options->beta;
1515
1516 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1517 CHECK_VALID_SIZE(inputs.size(), 1);
1518 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1519 CHECK_VALID_SIZE(outputs.size(), 1);
1520
James Ward58dec6b2020-09-11 17:32:44 +01001521 auto layerName = fmt::format("Softmax:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001522 IConnectableLayer* const layer = m_Network->AddSoftmaxLayer(desc, layerName.c_str());
1523
Sadik Armagand109a4d2020-07-28 10:42:13 +01001524 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
telsoa01c577f2c2018-08-31 09:22:23 +01001525 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1526
1527 // register the input connection slots for the layer, connections are made after all layers have been created
1528 // only the tensors for the inputs are relevant, exclude the const tensors
1529 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1530 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1531
1532 // register the output connection slots for the layer, connections are made after all layers have been created
1533 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1534 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1535}
1536
Kevin May7d96b162021-02-03 17:38:41 +00001537void TfLiteParserImpl::ParseSpaceToBatchND(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001538{
1539 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1540
1541 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1542 CHECK_VALID_SIZE(inputs.size(), 3);
1543
1544 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1545 CHECK_VALID_SIZE(outputs.size(), 1);
1546
1547 armnn::TensorInfo blockShapeTensorInfo = ToTensorInfo(inputs[1]);
1548 BufferRawPtr blockShapeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1549
1550 armnn::TensorInfo padListTensorInfo = ToTensorInfo(inputs[2]);
1551 BufferRawPtr padListBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1552
1553 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1554 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1555
1556 std::vector<unsigned int> padListVector(padListTensorInfo.GetNumElements());
1557 ::memcpy(padListVector.data(), padListBufferPtr->data.data(), padListTensorInfo.GetNumBytes());
1558
1559 size_t step = 2;
1560 std::vector<std::pair<unsigned int, unsigned int>> padList;
1561 for (unsigned int i = 0; i < padListTensorInfo.GetNumElements() / step; ++i)
1562 {
1563 padList.emplace_back(padListVector[i * step], padListVector[i * step + 1]);
1564 }
1565
1566 armnn::SpaceToBatchNdDescriptor desc;
1567 desc.m_BlockShape = blockShape;
1568 desc.m_PadList = padList;
1569 desc.m_DataLayout = armnn::DataLayout::NHWC;
1570
James Ward58dec6b2020-09-11 17:32:44 +01001571 auto layerName = fmt::format("SpaceToBatchND:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001572
James Conroy05102392020-06-24 15:39:55 +01001573 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001574 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001575 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
1576
1577 IConnectableLayer* layer = m_Network->AddSpaceToBatchNdLayer(desc, layerName.c_str());
1578 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbaded142019-02-08 19:02:48 -02001579 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1580
1581 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1582 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1583
1584 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1585 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1586}
1587
Kevin May7d96b162021-02-03 17:38:41 +00001588armnn::TensorInfo TfLiteParserImpl::OutputShapeOfSqueeze(const std::vector<uint32_t> & squeezeDimsIn,
1589 const armnn::TensorInfo & inputTensorInfo)
telsoa01c577f2c2018-08-31 09:22:23 +01001590{
1591 CHECK_VALID_SIZE(squeezeDimsIn.size(), 0, 1, 2, 3, 4);
1592 std::vector<uint32_t> squeezeDims = squeezeDimsIn;
1593 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
1594
1595 if (inputTensorInfo.GetNumDimensions() > 4)
1596 {
1597 std::stringstream ss;
1598 ss << "Input tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
1599 << " shape:" << inputTensorInfo.GetShape() << " "
1600 << CHECK_LOCATION().AsString();
1601 throw ParseException(ss.str());
1602 }
1603
1604 if (squeezeDims.empty())
1605 {
1606 squeezeDims.assign(dimensionSequence,
1607 dimensionSequence+inputTensorInfo.GetNumDimensions());
1608 }
1609
1610 std::vector<uint32_t> outputDims;
1611 for(unsigned int i = 0; i < inputTensorInfo.GetNumDimensions(); i++)
1612 {
1613 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
1614 auto currentDimension = inputTensorInfo.GetShape()[i];
1615 if (skipSqueeze || currentDimension != 1)
1616 {
1617 outputDims.push_back(currentDimension);
1618 }
1619 }
1620
1621 if (outputDims.size() > 4)
1622 {
1623 std::stringstream ss;
1624 ss << "Output tensor has unexpected number of dimensions:" << inputTensorInfo.GetNumDimensions()
1625 << " shape:" << inputTensorInfo.GetShape() << " "
1626 << CHECK_LOCATION().AsString();
1627 throw ParseException(ss.str());
1628 }
1629
1630 TensorShape outShape = TensorShape(static_cast<unsigned int>(outputDims.size()),
1631 outputDims.data());
1632
1633 // we need to preserve the tensor type and the quantization data as well
1634 TensorInfo outTensorInfo = inputTensorInfo;
1635 outTensorInfo.SetShape(outShape);
1636
1637 return outTensorInfo;
1638}
1639
Kevin May7d96b162021-02-03 17:38:41 +00001640void TfLiteParserImpl::ParseSqueeze(size_t subgraphIndex, size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01001641{
1642 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1643
1644 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1645 CHECK_VALID_SIZE(inputs.size(), 1);
1646
1647 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1648 CHECK_VALID_SIZE(outputs.size(), 1);
1649
1650 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1651 const auto * options = operatorPtr->builtin_options.AsSqueezeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01001652 auto layerName = fmt::format("Squeeze:{}:{}", subgraphIndex, operatorIndex);
telsoa01c577f2c2018-08-31 09:22:23 +01001653
1654 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1655 armnn::TensorInfo outputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00001656 TfLiteParserImpl::OutputShapeOfSqueeze(AsUnsignedVector(options->squeeze_dims),
telsoa01c577f2c2018-08-31 09:22:23 +01001657 inputTensorInfo);
James Conroy05102392020-06-24 15:39:55 +01001658 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
telsoa01c577f2c2018-08-31 09:22:23 +01001659
1660 ReshapeDescriptor reshapeDesc;
1661 reshapeDesc.m_TargetShape = outputTensorInfo.GetShape();
1662
telsoa01c577f2c2018-08-31 09:22:23 +01001663 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001664 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01001665 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1666
1667 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1668 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1669
1670 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1671 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1672}
1673
Kevin May7d96b162021-02-03 17:38:41 +00001674void TfLiteParserImpl::ParseStridedSlice(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001675{
1676 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1677
1678 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1679 CHECK_VALID_SIZE(inputs.size(), 4);
1680
1681 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1682 CHECK_VALID_SIZE(outputs.size(), 1);
1683
1684 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1685 const auto * options = operatorPtr->builtin_options.AsStridedSliceOptions();
1686
1687 StridedSliceDescriptor desc;
1688 desc.m_BeginMask = options->begin_mask;
1689 desc.m_EllipsisMask = options->ellipsis_mask;
1690 desc.m_EndMask = options->end_mask;
1691 desc.m_NewAxisMask = options->new_axis_mask;
1692 desc.m_ShrinkAxisMask = options->shrink_axis_mask;
1693 desc.m_DataLayout = armnn::DataLayout::NHWC;
1694
1695 armnn::TensorInfo beginTensorInfo = ToTensorInfo(inputs[1]);
1696 BufferRawPtr beginBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1697
1698 std::vector<int> begin(beginTensorInfo.GetNumElements());
1699 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.GetNumBytes());
1700
1701 armnn::TensorInfo endTensorInfo = ToTensorInfo(inputs[2]);
1702 BufferRawPtr endBufferPtr = GetBuffer(m_Model, inputs[2]->buffer);
1703
1704 std::vector<int> end(endTensorInfo.GetNumElements());
1705 ::memcpy(end.data(), endBufferPtr->data.data(), endTensorInfo.GetNumBytes());
1706
1707 armnn::TensorInfo strideTensorInfo = ToTensorInfo(inputs[3]);
1708 BufferRawPtr strideBufferPtr = GetBuffer(m_Model, inputs[3]->buffer);
1709
1710 std::vector<int> stride(strideTensorInfo.GetNumElements());
1711 ::memcpy(stride.data(), strideBufferPtr->data.data(), strideTensorInfo.GetNumBytes());
1712
1713 desc.m_Begin = begin;
1714 desc.m_End = end;
1715 desc.m_Stride = stride;
1716
James Ward58dec6b2020-09-11 17:32:44 +01001717 auto layerName = fmt::format("StridedSlice:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001718 IConnectableLayer* layer = m_Network->AddStridedSliceLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001719 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001720
Sadik Armagand109a4d2020-07-28 10:42:13 +01001721 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves451d95b2019-02-12 22:59:22 -02001722 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1723
1724 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1725 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1726
1727 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1728 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1729}
1730
Kevin May7d96b162021-02-03 17:38:41 +00001731void TfLiteParserImpl::ParseSub(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001732{
1733 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1734
1735 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1736 const auto * options = operatorPtr->builtin_options.AsSubOptions();
1737
1738 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1739 CHECK_VALID_SIZE(inputs.size(), 2);
1740
1741 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1742 CHECK_VALID_SIZE(outputs.size(), 1);
1743
1744 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1745 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1746
James Ward58dec6b2020-09-11 17:32:44 +01001747 auto layerName = fmt::format("Sub:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001748 IConnectableLayer* layer = m_Network->AddSubtractionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001749 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001750
Sadik Armagand109a4d2020-07-28 10:42:13 +01001751 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001752 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1753
1754 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001755 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesbbeae262019-02-07 18:37:39 -02001756
1757 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1758
1759 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1760 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1761}
1762
Kevin May7d96b162021-02-03 17:38:41 +00001763void TfLiteParserImpl::ParseDiv(size_t subgraphIndex, size_t operatorIndex)
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301764{
1765 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1766
1767 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1768 const auto * options = operatorPtr->builtin_options.AsDivOptions();
1769
1770 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1771 CHECK_VALID_SIZE(inputs.size(), 2);
1772
1773 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1774 CHECK_VALID_SIZE(outputs.size(), 1);
1775
1776 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1777 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1778
James Ward58dec6b2020-09-11 17:32:44 +01001779 auto layerName = fmt::format("Div:{}:{}", subgraphIndex, operatorIndex);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301780 IConnectableLayer* layer = m_Network->AddDivisionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001781 ARMNN_ASSERT(layer != nullptr);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301782
Sadik Armagand109a4d2020-07-28 10:42:13 +01001783 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301784 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1785
1786 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001787 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Darshan Patel42b3d7d2020-05-25 22:30:07 +05301788 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1789
1790 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1791 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1792}
1793
Kevin May7d96b162021-02-03 17:38:41 +00001794void TfLiteParserImpl::ParseAdd(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001795{
1796 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1797
1798 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1799 const auto * options = operatorPtr->builtin_options.AsAddOptions();
1800
1801 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1802 CHECK_VALID_SIZE(inputs.size(), 2);
1803
1804 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1805 CHECK_VALID_SIZE(outputs.size(), 1);
1806
Bruno Goncalves9c761a62018-12-27 14:20:35 -02001807 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1808 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1809
James Ward58dec6b2020-09-11 17:32:44 +01001810 auto layerName = fmt::format("Add:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001811 IConnectableLayer* layer = m_Network->AddAdditionLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001812 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001813
Sadik Armagand109a4d2020-07-28 10:42:13 +01001814 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001815 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1816
1817 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001818 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesd4ac6a42018-12-18 12:56:22 -02001819 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1820
1821 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1822 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1823}
1824
Kevin May7d96b162021-02-03 17:38:41 +00001825void TfLiteParserImpl::ParseMul(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001826{
1827 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1828
1829 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1830 const auto * options = operatorPtr->builtin_options.AsMulOptions();
1831
1832 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1833 CHECK_VALID_SIZE(inputs.size(), 2);
1834
1835 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1836 CHECK_VALID_SIZE(outputs.size(), 1);
1837
Bruno Goncalves9c761a62018-12-27 14:20:35 -02001838 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1839 armnn::TensorInfo input1TensorInfo = ToTensorInfo(inputs[1]);
1840
James Ward58dec6b2020-09-11 17:32:44 +01001841 auto layerName = fmt::format("Mul:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001842 IConnectableLayer* layer = m_Network->AddMultiplicationLayer(layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001843 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001844
Sadik Armagand109a4d2020-07-28 10:42:13 +01001845 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001846 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1847
1848 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat16f82f92020-09-14 16:12:44 +01001849 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
Bruno Goncalvesf803f782018-12-18 13:40:30 -02001850 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1851
1852 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1853 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1854}
1855
Kevin May7d96b162021-02-03 17:38:41 +00001856void TfLiteParserImpl::ParseMean(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001857{
1858 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1859
1860 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1861
1862 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1863 CHECK_VALID_SIZE(outputs.size(), 1);
1864
1865 armnn::TensorInfo dimTensorInfo = ToTensorInfo(inputs[1]);
1866 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1867
1868 armnn::MeanDescriptor desc;
1869 std::vector<unsigned int> axis(dimTensorInfo.GetNumElements());
1870 ::memcpy(axis.data(), bufferPtr->data.data(), dimTensorInfo.GetNumBytes());
1871 desc.m_Axis = axis;
1872
1873 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001874 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001875
1876 desc.m_KeepDims =
1877 inputTensorInfo.GetNumDimensions() == outputTensorInfo.GetNumDimensions() ?
1878 true : false;
1879
James Ward58dec6b2020-09-11 17:32:44 +01001880 auto layerName = fmt::format("Mean:{}:{}", subgraphIndex, operatorIndex);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001881 IConnectableLayer* layer = m_Network->AddMeanLayer(desc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01001882 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves2235cee2018-12-19 12:51:45 -02001883
1884 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1885
1886 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1887 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1888
1889 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1890 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1891}
1892
Kevin May7d96b162021-02-03 17:38:41 +00001893void TfLiteParserImpl::ParseNeg(size_t subgraphIndex, size_t operatorIndex)
Darshan Patel83fcf982020-05-26 22:22:42 +05301894{
1895 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1896
1897 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1898 CHECK_VALID_SIZE(inputs.size(), 1);
1899
1900 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1901 CHECK_VALID_SIZE(outputs.size(), 1);
1902
James Ward58dec6b2020-09-11 17:32:44 +01001903 auto layerName = fmt::format("Neg:{}:{}", subgraphIndex, operatorIndex);
Darshan Patel83fcf982020-05-26 22:22:42 +05301904 armnn::ElementwiseUnaryDescriptor descriptor(armnn::UnaryOperation::Neg);
1905 IConnectableLayer* layer = m_Network->AddElementwiseUnaryLayer(descriptor, layerName.c_str());
1906 ARMNN_ASSERT(layer != nullptr);
1907
Sadik Armagand109a4d2020-07-28 10:42:13 +01001908 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Darshan Patel83fcf982020-05-26 22:22:42 +05301909 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1910
1911 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1912 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1913
1914 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1915 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1916}
1917
Kevin May7d96b162021-02-03 17:38:41 +00001918void TfLiteParserImpl::ParsePad(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001919{
1920 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1921
Kevin May7d96b162021-02-03 17:38:41 +00001922 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001923
Kevin May7d96b162021-02-03 17:38:41 +00001924 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001925 CHECK_VALID_SIZE(outputs.size(), 1);
1926
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00001927 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
1928
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001929 armnn::TensorInfo padTensorInfo = ToTensorInfo(inputs[1]);
1930 BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
1931
1932 std::vector<unsigned int> padBuffer(padTensorInfo.GetNumElements());
1933 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.GetNumBytes());
1934
1935 size_t step = 2;
1936 armnn::PadDescriptor desc;
Narumol Prangnawarat8719d222020-11-27 16:57:56 +00001937 if (inputTensorInfo.IsQuantized())
1938 {
1939 desc.m_PadValue = static_cast<float>(inputTensorInfo.GetQuantizationOffset());
1940 }
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001941 for (unsigned int i = 0; i < padTensorInfo.GetNumElements() / step; ++i)
1942 {
1943 desc.m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
1944 }
1945
James Ward58dec6b2020-09-11 17:32:44 +01001946 auto layerName = fmt::format("Pad:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01001947 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01001948
1949 IConnectableLayer* layer = m_Network->AddPadLayer(desc, layerName.c_str());
1950 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves6c2355b2018-12-19 12:52:01 -02001951 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1952
1953 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1954 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1955
1956 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1957 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1958}
1959
Kevin May7d96b162021-02-03 17:38:41 +00001960void TfLiteParserImpl::ParseQuantize(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan66dedc72019-12-10 16:32:07 +00001961{
1962 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1963
1964 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
1965 CHECK_VALID_SIZE(inputs.size(), 1);
1966
1967 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
1968 CHECK_VALID_SIZE(outputs.size(), 1);
1969
James Ward58dec6b2020-09-11 17:32:44 +01001970 auto layerName = fmt::format("Quantize:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan66dedc72019-12-10 16:32:07 +00001971
1972 IConnectableLayer* layer = m_Network->AddQuantizeLayer(layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01001973 ARMNN_ASSERT(layer != nullptr);
Sadik Armagan66dedc72019-12-10 16:32:07 +00001974
Sadik Armagand109a4d2020-07-28 10:42:13 +01001975 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan66dedc72019-12-10 16:32:07 +00001976 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1977
1978 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1979 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1980
1981 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1982 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1983}
Finn Williamsc42c3842019-01-22 14:18:11 +00001984
Kevin May7d96b162021-02-03 17:38:41 +00001985void TfLiteParserImpl::ParseRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01001986{
Finn Williamsc42c3842019-01-22 14:18:11 +00001987 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::ReLu);
Sadik Armagan58f39192018-09-17 14:14:39 +01001988}
1989
Kevin May7d96b162021-02-03 17:38:41 +00001990void TfLiteParserImpl::ParseRelu6(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan58f39192018-09-17 14:14:39 +01001991{
Finn Williamsc42c3842019-01-22 14:18:11 +00001992 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::BoundedReLu);
1993}
Sadik Armagan58f39192018-09-17 14:14:39 +01001994
Kevin May7d96b162021-02-03 17:38:41 +00001995void TfLiteParserImpl::ParseLeakyRelu(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan12239e72020-05-27 11:06:17 +01001996{
Jan Eilers2f746b32020-07-28 14:00:06 +01001997 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::LeakyReLu);
Sadik Armagan12239e72020-05-27 11:06:17 +01001998}
1999
Kevin May7d96b162021-02-03 17:38:41 +00002000void TfLiteParserImpl::ParseLogistic(size_t subgraphIndex, size_t operatorIndex)
Finn Williamsc42c3842019-01-22 14:18:11 +00002001{
2002 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Sigmoid);
2003}
2004
Kevin May7d96b162021-02-03 17:38:41 +00002005void TfLiteParserImpl::ParseTanH(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd99851762019-04-09 09:37:38 +01002006{
2007 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::TanH);
2008}
2009
Kevin May7d96b162021-02-03 17:38:41 +00002010void TfLiteParserImpl::ParseElu(size_t subgraphIndex, size_t operatorIndex)
Matthew Sloyan7515d072020-12-16 12:50:01 +00002011{
2012 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::Elu);
2013}
2014
Kevin May7d96b162021-02-03 17:38:41 +00002015void TfLiteParserImpl::ParseHardSwish(size_t subgraphIndex, size_t operatorIndex)
Jan Eilers2f746b32020-07-28 14:00:06 +01002016{
2017 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::HardSwish);
2018}
Finn Williamsc42c3842019-01-22 14:18:11 +00002019
Kevin May7d96b162021-02-03 17:38:41 +00002020void TfLiteParserImpl::ParseActivation(size_t subgraphIndex, size_t operatorIndex, ActivationFunction activationType)
Finn Williamsc42c3842019-01-22 14:18:11 +00002021{
2022 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan58f39192018-09-17 14:14:39 +01002023 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Jan Eilers8eb25602020-03-09 12:13:48 +00002024 IgnoreUnused(operatorPtr);
Sadik Armagan58f39192018-09-17 14:14:39 +01002025
2026 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2027 CHECK_VALID_SIZE(inputs.size(), 1);
2028
2029 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2030 CHECK_VALID_SIZE(outputs.size(), 1);
2031
James Ward58dec6b2020-09-11 17:32:44 +01002032 auto layerName = fmt::format("Activation:");
Sadik Armagan58f39192018-09-17 14:14:39 +01002033 ActivationDescriptor activationDesc;
Finn Williamsc42c3842019-01-22 14:18:11 +00002034 activationDesc.m_Function = activationType;
2035
2036 switch (activationType)
2037 {
2038 case ActivationFunction::ReLu:
2039 {
James Ward58dec6b2020-09-11 17:32:44 +01002040 layerName += fmt::format("RELU:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002041 break;
2042 }
2043 case ActivationFunction::BoundedReLu:
2044 {
James Ward58dec6b2020-09-11 17:32:44 +01002045 layerName += fmt::format("RELU6:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002046 activationDesc.m_A = 6.0f;
2047 activationDesc.m_B = 0.0f;
2048 break;
2049 }
2050 case ActivationFunction::Sigmoid:
2051 {
James Ward58dec6b2020-09-11 17:32:44 +01002052 layerName += fmt::format("SIGMOID:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsc42c3842019-01-22 14:18:11 +00002053 break;
2054 }
Nina Drozd99851762019-04-09 09:37:38 +01002055 case ActivationFunction::TanH:
2056 {
James Ward58dec6b2020-09-11 17:32:44 +01002057 layerName += fmt::format("TANH:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd99851762019-04-09 09:37:38 +01002058 activationDesc.m_A = 1.0f;
2059 activationDesc.m_B = 1.0f;
2060 break;
2061 }
Sadik Armagan12239e72020-05-27 11:06:17 +01002062 case ActivationFunction::LeakyReLu:
2063 {
James Ward58dec6b2020-09-11 17:32:44 +01002064 layerName += fmt::format("LEAKYRELU:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan12239e72020-05-27 11:06:17 +01002065 const auto * options = operatorPtr->builtin_options.AsLeakyReluOptions();
2066 activationDesc.m_A = options->alpha;
2067 break;
2068 }
Matthew Sloyan7515d072020-12-16 12:50:01 +00002069 case ActivationFunction::Elu:
2070 {
2071 layerName += fmt::format("ELU:{}:{}", subgraphIndex, operatorIndex);
2072 activationDesc.m_A = 1.0f;
2073 break;
2074 }
Jan Eilers2f746b32020-07-28 14:00:06 +01002075 case ActivationFunction::HardSwish:
Matthew Sloyan7515d072020-12-16 12:50:01 +00002076 {
James Ward58dec6b2020-09-11 17:32:44 +01002077 layerName += fmt::format("HARDSWISH:{}:{}", subgraphIndex, operatorIndex);
Jan Eilers2f746b32020-07-28 14:00:06 +01002078 break;
Matthew Sloyan7515d072020-12-16 12:50:01 +00002079 }
Finn Williamsc42c3842019-01-22 14:18:11 +00002080 default:
2081 {
2082 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002083 fmt::format("Unexpected ActivationFunction[{}] when creating layerName {} ",
2084 static_cast<int>(activationType), CHECK_LOCATION().AsString()));
Finn Williamsc42c3842019-01-22 14:18:11 +00002085 }
2086 }
2087
2088 IConnectableLayer* const layer = m_Network->AddActivationLayer(activationDesc, layerName.c_str());
Sadik Armagan58f39192018-09-17 14:14:39 +01002089
Sadik Armagand109a4d2020-07-28 10:42:13 +01002090 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan58f39192018-09-17 14:14:39 +01002091 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2092
2093 // register the input connection slots for the layer, connections are made after all layers have been created
2094 // only the tensors for the inputs are relevant, exclude the const tensors
2095 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2096 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2097
2098 // register the output connection slots for the layer, connections are made after all layers have been created
2099 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2100 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2101}
Kevin May7d96b162021-02-03 17:38:41 +00002102armnn::TensorInfo TfLiteParserImpl::OutputShapeOfReshape(const armnn::TensorInfo & inputTensorInfo,
2103 const std::vector<int32_t> & targetDimsIn)
Sadikb94967b2018-09-19 15:30:00 +01002104{
2105 std::vector<unsigned int> outputDims(targetDimsIn.begin(), targetDimsIn.end());
2106 const auto stretchDim = std::find(targetDimsIn.begin(), targetDimsIn.end(), -1);
2107
2108 if (stretchDim != targetDimsIn.end())
2109 {
2110 if (std::find(std::next(stretchDim), targetDimsIn.end(), -1) != targetDimsIn.end())
2111 {
2112 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002113 fmt::format("At most one component of shape can be -1 {}", CHECK_LOCATION().AsString()));
Sadikb94967b2018-09-19 15:30:00 +01002114 }
2115
2116 auto targetNumElements =
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002117 armnn::numeric_cast<unsigned int>(
Sadikb94967b2018-09-19 15:30:00 +01002118 std::accumulate(targetDimsIn.begin(), targetDimsIn.end(), -1, std::multiplies<int32_t>()));
2119
2120 auto stretchIndex = static_cast<size_t>(std::distance(targetDimsIn.begin(), stretchDim));
2121 outputDims[stretchIndex] = inputTensorInfo.GetNumElements() / targetNumElements;
2122 }
2123
2124 TensorShape outputShape = TensorShape(static_cast<unsigned int>(outputDims.size()), outputDims.data());
2125
2126 TensorInfo reshapeInfo = inputTensorInfo;
2127 reshapeInfo.SetShape(outputShape);
2128
2129 return reshapeInfo;
2130}
2131
Kevin May7d96b162021-02-03 17:38:41 +00002132void TfLiteParserImpl::ParseReshape(size_t subgraphIndex, size_t operatorIndex)
Sadikb94967b2018-09-19 15:30:00 +01002133{
2134 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2135
2136 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002137
2138 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2139 CHECK_VALID_SIZE(outputs.size(), 1);
2140
2141 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2142 const auto * options = operatorPtr->builtin_options.AsReshapeOptions();
James Ward58dec6b2020-09-11 17:32:44 +01002143 auto layerName = fmt::format("Reshape:{}:{}", subgraphIndex, operatorIndex);
Sadikb94967b2018-09-19 15:30:00 +01002144
2145 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
kevmay0171972a82018-12-17 14:28:03 +00002146 armnn::TensorInfo actualOutputTensorInfo = ToTensorInfo(outputs[0]);
James Conroy05102392020-06-24 15:39:55 +01002147 CheckMatchingQuantization(inputTensorInfo, actualOutputTensorInfo, layerName, "Input 0", "Output 0");
Derek Lambertic9e52792020-03-11 11:42:26 +00002148
Jan Eilersbac9b352020-07-13 13:40:24 +01002149 // Extracting new shape for the output
2150 // There are two ways it can be passed
2151 // * First is to define the target shape in the operator built-in options
2152 // * Second is to pass it as a second input tensor
Derek Lambertic9e52792020-03-11 11:42:26 +00002153 std::vector<int32_t> targetShape;
Jan Eilersbac9b352020-07-13 13:40:24 +01002154 bool targetShapeFound = false;
2155 // Check if built-in options were given
2156 if (options != nullptr)
Derek Lambertic9e52792020-03-11 11:42:26 +00002157 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002158 // make sure the parameter is given
2159 if (options->new_shape.empty() == false)
Derek Lambertic9e52792020-03-11 11:42:26 +00002160 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002161 targetShape = options->new_shape;
2162 targetShapeFound = true;
Derek Lambertif4a953f2020-03-17 14:25:57 +00002163 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002164 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002165
2166 // If there is no built-in option given or if the built-in new_shape parameter was empty
2167 if (!targetShapeFound)
Derek Lambertic9e52792020-03-11 11:42:26 +00002168 {
Jan Eilersbac9b352020-07-13 13:40:24 +01002169 // Check for a second input tensor
2170 if (inputs.size() > 1 && inputs[1] != nullptr)
2171 {
2172 if (inputs[1]->is_variable)
2173 {
2174 ARMNN_THROW_PARSE_EXCEPTION( "Target shapes defined in non-const input tensors is not supported");
2175 }
2176
2177 if (inputs[1]->shape.size() != 1)
2178 {
2179 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not a 1D tensor");
2180 }
2181
2182 if (inputs[1]->type != tflite::TensorType_INT32)
2183 {
2184 ARMNN_THROW_PARSE_EXCEPTION("Target 'shape' input is not an int32 type");
2185 }
2186
2187 // Extract target shape from input
2188 auto bufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2189 auto values = reinterpret_cast<const int32_t*>(bufferPtr->data.data());
Sadik Armagan19a1c032021-01-20 12:17:00 +00002190 if (!values)
2191 {
2192 ARMNN_THROW_PARSE_EXCEPTION("Reshape operator target shape input buffer data is null");
2193 }
Jan Eilersbac9b352020-07-13 13:40:24 +01002194 for (int i=0; i < inputs[1]->shape[0]; ++i)
2195 {
2196 targetShape.push_back(values[i]);
2197 }
2198 }
2199 else
Derek Lambertic9e52792020-03-11 11:42:26 +00002200 {
2201 ARMNN_THROW_PARSE_EXCEPTION("Target shape not defined in reshape parameters or input tensor. "
2202 "At least one method required");
2203 }
Derek Lambertic9e52792020-03-11 11:42:26 +00002204 }
2205
kevmay0171972a82018-12-17 14:28:03 +00002206 armnn::TensorInfo reshapeOutputTensorInfo =
Kevin May7d96b162021-02-03 17:38:41 +00002207 TfLiteParserImpl::OutputShapeOfReshape(inputTensorInfo, targetShape);
Sadikb94967b2018-09-19 15:30:00 +01002208
kevmay0171972a82018-12-17 14:28:03 +00002209 // Check for valid input size and that reshape parameters equal output shape
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002210 const armnn::TensorShape& reshapeOutputTensorShape = reshapeOutputTensorInfo.GetShape();
2211 if (inputs.size() > 1 && !CheckShape(reshapeOutputTensorShape, outputs[0]->shape))
kevmay0171972a82018-12-17 14:28:03 +00002212 {
2213 std::stringstream ss;
2214 ss << "New shape defined in reshape parameters "
Aron Virginas-Tar70672f62019-01-23 14:00:00 +00002215 << reshapeOutputTensorShape
kevmay0171972a82018-12-17 14:28:03 +00002216 << " does not equal output shape "
2217 << actualOutputTensorInfo.GetShape()
2218 << ": "
2219 << CHECK_LOCATION().AsString();
2220 throw ParseException(ss.str());
2221 }
2222
Sadikb94967b2018-09-19 15:30:00 +01002223 ReshapeDescriptor reshapeDesc;
kevmay0171972a82018-12-17 14:28:03 +00002224 reshapeDesc.m_TargetShape = reshapeOutputTensorInfo.GetShape();
Sadikb94967b2018-09-19 15:30:00 +01002225
Sadikb94967b2018-09-19 15:30:00 +01002226 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002227 ARMNN_ASSERT(layer != nullptr);
kevmay0171972a82018-12-17 14:28:03 +00002228 layer->GetOutputSlot(0).SetTensorInfo(reshapeOutputTensorInfo);
Sadikb94967b2018-09-19 15:30:00 +01002229
2230 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2231 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2232
2233 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2234 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2235}
2236
Kevin May7d96b162021-02-03 17:38:41 +00002237void TfLiteParserImpl::ParseResizeBilinear(size_t subgraphIndex, size_t operatorIndex)
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002238{
Sadik Armagana3b31f02019-12-05 09:08:53 +00002239 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::Bilinear);
2240}
2241
Kevin May7d96b162021-02-03 17:38:41 +00002242void TfLiteParserImpl::ParseResizeNearestNeighbor(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002243{
2244 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::NearestNeighbor);
2245}
2246
Kevin May7d96b162021-02-03 17:38:41 +00002247void TfLiteParserImpl::ParseResize(size_t subgraphIndex, size_t operatorIndex, ResizeMethod resizeMethod)
Sadik Armagana3b31f02019-12-05 09:08:53 +00002248{
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002249 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2250
2251 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2252 CHECK_VALID_SIZE(inputs.size(), 2);
2253
2254 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2255 CHECK_VALID_SIZE(outputs.size(), 1);
2256
2257 armnn::TensorInfo sizeTensorInfo = ToTensorInfo(inputs[1]);
2258
2259 // Data for the parsed tensor args (size) must be stored locally.
2260 std::vector<int32_t> sizeTensorData(sizeTensorInfo.GetNumElements());
2261
2262 BufferRawPtr sizeBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2263 ::memcpy(sizeTensorData.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
2264
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002265 ResizeDescriptor desc;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002266 desc.m_Method = resizeMethod;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002267 desc.m_TargetHeight = static_cast<uint32_t> (sizeTensorData[0]);
Aron Virginas-Tar169d2f12019-07-01 19:01:44 +01002268 desc.m_TargetWidth = static_cast<uint32_t> (sizeTensorData[1]);
2269 desc.m_DataLayout = armnn::DataLayout::NHWC;
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002270
James Ward58dec6b2020-09-11 17:32:44 +01002271 auto layerName = fmt::format("Resize:");
Sadik Armagana3b31f02019-12-05 09:08:53 +00002272
2273 switch (resizeMethod)
2274 {
2275 case ResizeMethod::Bilinear:
2276 {
James Ward58dec6b2020-09-11 17:32:44 +01002277 layerName += fmt::format("BILINEAR:{}:{}", subgraphIndex, operatorIndex);
Sang-Hoon Park820eb142020-01-08 10:25:24 +00002278
2279 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2280 const auto * options = operatorPtr->builtin_options.AsResizeBilinearOptions();
2281
David Monahan4a0c9b92020-05-30 09:48:39 +01002282 desc.m_AlignCorners = options->align_corners;
Sadik Armagana3b31f02019-12-05 09:08:53 +00002283 break;
2284 }
2285 case ResizeMethod::NearestNeighbor:
2286 {
James Ward58dec6b2020-09-11 17:32:44 +01002287 layerName += fmt::format("NEARESTNEIGHBOR:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagana3b31f02019-12-05 09:08:53 +00002288 break;
2289 }
2290 default:
2291 {
2292 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002293 fmt::format("Unexpected ResizeMethod[{}] when creating layerName {} ",
2294 static_cast<int>(resizeMethod), CHECK_LOCATION().AsString()));
Sadik Armagana3b31f02019-12-05 09:08:53 +00002295 }
2296 }
2297
James Conroy05102392020-06-24 15:39:55 +01002298 TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002299 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002300 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName, "Input 0", "Output 0");
2301
2302 IConnectableLayer* layer = m_Network->AddResizeLayer(desc, layerName.c_str());
2303 ARMNN_ASSERT(layer != nullptr);
Bruno Goncalves3f58ddb2019-02-07 18:40:11 -02002304 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2305
2306 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2307 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2308
2309 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2310 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2311}
2312
Kevin May7d96b162021-02-03 17:38:41 +00002313void TfLiteParserImpl::ParseConcatenation(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan479045b2018-10-01 11:51:37 +01002314{
2315 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2316
2317 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2318 const auto * options = operatorPtr->builtin_options.AsConcatenationOptions();
2319
2320 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
2321
2322 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2323 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2324 CHECK_VALID_SIZE(outputs.size(), 1);
2325
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002326 unsigned int numConcatView = static_cast<unsigned int>(inputs.size());
2327 uint32_t inputRank = ToTensorInfo(inputs[0]).GetNumDimensions();
Sadik Armagan479045b2018-10-01 11:51:37 +01002328
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002329 const unsigned int concatDimInput = static_cast<unsigned int>(
2330 (static_cast<int>(inputRank) + options->axis) % static_cast<int>(inputRank));
Sadik Armagan479045b2018-10-01 11:51:37 +01002331
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002332 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatView), inputRank);
2333 concatDescriptor.SetConcatAxis(concatDimInput);
Sadik Armagan479045b2018-10-01 11:51:37 +01002334
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002335 unsigned int mergeDimOrigin = 0;
Sadik Armagan479045b2018-10-01 11:51:37 +01002336
2337 for (unsigned int viewIndex = 0; viewIndex < numConcatView; ++viewIndex)
2338 {
2339 TensorInfo inputTensorInfo = ToTensorInfo(inputs[viewIndex]);
2340
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002341 // This set up concatDescriptor view origin
2342 armnnUtils::ProcessConcatInputTensorInfo(
2343 inputTensorInfo, concatDescriptor, concatDimInput, viewIndex, mergeDimOrigin);
Sadik Armagan479045b2018-10-01 11:51:37 +01002344 }
2345
James Ward58dec6b2020-09-11 17:32:44 +01002346 auto layerName = fmt::format("Concatenation:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagand109a4d2020-07-28 10:42:13 +01002347 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
James Conroy05102392020-06-24 15:39:55 +01002348
Jim Flynn906f9462019-05-10 13:55:21 +01002349 IConnectableLayer* layer = m_Network->AddConcatLayer(concatDescriptor, layerName.c_str());
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002350 ARMNN_ASSERT(layer != nullptr);
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002351 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Sadik Armagan479045b2018-10-01 11:51:37 +01002352
James Conroy05102392020-06-24 15:39:55 +01002353 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002354 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
Sadik Armagan479045b2018-10-01 11:51:37 +01002355
Nattapat Chaimanowong5e9d2982019-01-25 13:20:39 +00002356 // add fused activation layer
2357 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
Sadik Armagan479045b2018-10-01 11:51:37 +01002358
Sadik Armagan479045b2018-10-01 11:51:37 +01002359 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2360 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2361}
2362
Kevin May7d96b162021-02-03 17:38:41 +00002363void TfLiteParserImpl::ParseFullyConnected(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002364{
2365 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2366
2367 const auto & operatorRfr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2368 const auto options = operatorRfr->builtin_options.AsFullyConnectedOptions();
2369
2370 CHECK_SUPPORTED_FUSED_ACTIVATION(options, subgraphIndex, operatorIndex);
2371
2372 FullyConnectedDescriptor desc;
2373 desc.m_BiasEnabled = false;
Nattapat Chaimanowongd8eee592018-10-26 10:24:14 +01002374 desc.m_TransposeWeightMatrix = true;
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002375
2376 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2377 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2378 CHECK_VALID_SIZE(outputs.size(), 1);
2379
2380 armnn::TensorInfo filterTensorInfo = ToTensorInfo(inputs[1]);
2381
2382 // Fully Connected Layer accepts two dimensional weights input
2383 int32_t weightsDimension = static_cast<int32_t>(filterTensorInfo.GetNumDimensions());
2384 if (weightsDimension != 2)
2385 {
2386 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002387 fmt::format("Dimension {} for Fully Connected weights is not supported by Armnn. "
2388 "Node {}",
2389 weightsDimension,
2390 CHECK_LOCATION().AsString()));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002391 }
2392
Matthew Jackson74bf7da2019-08-16 16:51:42 +01002393 armnn::IConnectableLayer* layer = nullptr;
James Ward58dec6b2020-09-11 17:32:44 +01002394 auto layerName = fmt::format("FullyConnected:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002395
Finn Williamsd4fa5452021-03-01 12:31:41 +00002396 Optional<ConstTensor> filterOptionalConstTensor;
2397
2398 desc.m_ConstantWeights = IsConstTensor(inputs[1]);
2399
2400 // Either both weights and biases need to be inputs or both weights and biases need to be constant
2401 if (inputs.size() == 3 && desc.m_ConstantWeights != IsConstTensor(inputs[2]))
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002402 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00002403 throw ParseException(
2404 fmt::format("Weights and bias are not compatible."
2405 "Node {}",
2406 CHECK_LOCATION().AsString()));
2407 }
2408
2409 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2410 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0]};
2411 if (desc.m_ConstantWeights)
2412 {
2413 filterOptionalConstTensor = Optional<ConstTensor>(CreateConstTensorNonPermuted(inputs[1], filterTensorInfo));
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002414 }
2415 else
2416 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00002417 // Non const weights will need to be registered as inputs
2418 tensorIndexesToRegister.emplace_back(inputTensorIndexes[1]);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002419 }
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002420
Finn Williamsd4fa5452021-03-01 12:31:41 +00002421 Optional<ConstTensor> biasOptionalConstTensor;
2422 if (inputs.size() == 3)
2423 {
2424 desc.m_BiasEnabled = true;
2425 if (desc.m_ConstantWeights)
2426 {
2427 TensorInfo biasTensorInfo = ToTensorInfo(inputs[2]);
2428 biasOptionalConstTensor = Optional<ConstTensor>(CreateConstTensorNonPermuted(inputs[2], biasTensorInfo));
2429 }
2430 else
2431 {
2432 // Non const biases will need to be registered as inputs
2433 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
2434 }
2435 }
2436
2437 layer = m_Network->AddFullyConnectedLayer(desc,
2438 filterOptionalConstTensor,
2439 biasOptionalConstTensor,
2440 layerName.c_str());
2441
2442 ARMNN_ASSERT(layer != nullptr);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002443 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2444
Finn Williamsd4fa5452021-03-01 12:31:41 +00002445 unsigned int startingSlotIndex = 0;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002446 if (inputTensorInfo.GetNumDimensions() > 2)
2447 {
2448 // Add reshape to flatten to 2D [batch_size, input_size],
2449 // where "input_size" corresponds to the number of inputs to the layer,
2450 // matching the second dimension of weights,
2451 // and "batch_size" is calculated by dividing the number of elements by "input_size".
2452 std::vector<unsigned int> reshapedDimensions(2);
2453 reshapedDimensions[1] = filterTensorInfo.GetShape()[1];
2454 reshapedDimensions[0] = inputTensorInfo.GetNumElements() / reshapedDimensions[1];
2455
2456 if (inputTensorInfo.GetNumElements() % reshapedDimensions[1] != 0)
2457 {
2458 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002459 fmt::format("Failed to deduce input tensor shape from filter size {} {}",
2460 reshapedDimensions[1],
2461 CHECK_LOCATION().AsString()));
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002462 }
2463
2464 armnn::TensorInfo reshapedTensorInfo = ToTensorInfo(inputs[0]);
2465 reshapedTensorInfo.SetShape(armnn::TensorShape{ 2, reshapedDimensions.data() });
2466
James Ward58dec6b2020-09-11 17:32:44 +01002467 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Finn Williamsd4fa5452021-03-01 12:31:41 +00002468 armnn::ReshapeDescriptor reshapeDescriptor;
2469 reshapeDescriptor.m_TargetShape = reshapedTensorInfo.GetShape();
2470 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(reshapeDescriptor, layerName.c_str());
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002471
2472 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedTensorInfo);
2473 reshapeLayer->GetOutputSlot(0).Connect(layer->GetInputSlot(0));
2474
2475 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {inputTensorIndexes[0]});
Finn Williamsd4fa5452021-03-01 12:31:41 +00002476 // Fc layer connects to the reshape layer, so we skip the first input slot when registering fc's input slots
2477 tensorIndexesToRegister.erase(tensorIndexesToRegister.begin());
2478 startingSlotIndex = 1;
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002479 }
Finn Williamsd4fa5452021-03-01 12:31:41 +00002480
2481 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister, startingSlotIndex);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002482
Sadik Armagand109a4d2020-07-28 10:42:13 +01002483 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002484 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2485
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002486 // we need to add the activation layer and fortunately we don't need to care about the data layout
2487 armnn::IConnectableLayer* fusedActivationLayer = AddFusedActivationLayer(layer, 0,
2488 options->fused_activation_function);
Narumol Prangnawarat501f4d42019-04-24 15:52:20 +01002489
Sadik Armagan8853c1f2018-10-22 09:04:18 +01002490 // register the output connection slots for the layer, connections are made after all layers have been created
2491 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2492 RegisterOutputSlots(subgraphIndex, operatorIndex, fusedActivationLayer, {outputTensorIndexes[0]});
2493}
2494
Kevin May7d96b162021-02-03 17:38:41 +00002495void TfLiteParserImpl::ParseDetectionPostProcess(size_t subgraphIndex, size_t operatorIndex)
keidav011b3e2ea2019-02-21 10:07:37 +00002496{
2497 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2498
2499 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2500
2501 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2502 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2503 CHECK_VALID_SIZE(outputs.size(), 4);
2504
2505 // Obtain custom options from flexbuffers
2506 auto custom_options = operatorPtr->custom_options;
2507 const flexbuffers::Map& m = flexbuffers::GetRoot(custom_options.data(), custom_options.size()).AsMap();
2508
2509 // Obtain descriptor information from tf lite
2510 DetectionPostProcessDescriptor desc;
2511 desc.m_MaxDetections = m["max_detections"].AsUInt32();
2512 desc.m_MaxClassesPerDetection = m["max_classes_per_detection"].AsUInt32();
2513 desc.m_NmsScoreThreshold = m["nms_score_threshold"].AsFloat();
2514 desc.m_NmsIouThreshold = m["nms_iou_threshold"].AsFloat();
2515 desc.m_NumClasses = m["num_classes"].AsUInt32();
2516 desc.m_ScaleH = m["h_scale"].AsFloat();
2517 desc.m_ScaleW = m["w_scale"].AsFloat();
2518 desc.m_ScaleX = m["x_scale"].AsFloat();
2519 desc.m_ScaleY = m["y_scale"].AsFloat();
2520
keidav0107d58c72019-02-26 11:57:39 +00002521 if (!(m["use_regular_nms"].IsNull()))
keidav011b3e2ea2019-02-21 10:07:37 +00002522 {
keidav0107d58c72019-02-26 11:57:39 +00002523 desc.m_UseRegularNms = m["use_regular_nms"].AsBool();
keidav011b3e2ea2019-02-21 10:07:37 +00002524 }
2525 if (!(m["detections_per_class"].IsNull()))
2526 {
2527 desc.m_DetectionsPerClass = m["detections_per_class"].AsUInt32();
2528 }
2529
2530 if (desc.m_NmsIouThreshold <= 0.0f || desc.m_NmsIouThreshold > 1.0f)
2531 {
2532 throw InvalidArgumentException("DetectionPostProcessTFLiteParser: Intersection over union threshold "
2533 "must be positive and less than or equal to 1.");
2534 }
2535
2536 armnn::TensorInfo anchorTensorInfo = ToTensorInfo(inputs[2]);
Finn Williamsd4fa5452021-03-01 12:31:41 +00002537 auto anchorTensorAndData = CreateConstTensorNonPermuted(inputs[2], anchorTensorInfo);
keidav011b3e2ea2019-02-21 10:07:37 +00002538
James Ward58dec6b2020-09-11 17:32:44 +01002539 auto layerName = fmt::format("DetectionPostProcess:{}:{}", subgraphIndex, operatorIndex);
Finn Williamsd4fa5452021-03-01 12:31:41 +00002540 IConnectableLayer* layer = m_Network->AddDetectionPostProcessLayer(desc, anchorTensorAndData,
keidav011b3e2ea2019-02-21 10:07:37 +00002541 layerName.c_str());
2542
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002543 ARMNN_ASSERT(layer != nullptr);
keidav011b3e2ea2019-02-21 10:07:37 +00002544
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00002545 // The model does not specify the output shapes.
2546 // The output shapes are calculated from the max_detection and max_classes_per_detection.
2547 unsigned int numDetectedBox = desc.m_MaxDetections * desc.m_MaxClassesPerDetection;
2548 m_OverridenOutputShapes.push_back({ 1, numDetectedBox, 4 });
2549 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
2550 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
2551 m_OverridenOutputShapes.push_back({ 1 });
2552
keidav011b3e2ea2019-02-21 10:07:37 +00002553 for (unsigned int i = 0 ; i < outputs.size() ; ++i)
2554 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00002555 armnn::TensorInfo detectionBoxOutputTensorInfo = ToTensorInfo(outputs[i], m_OverridenOutputShapes[i]);
keidav011b3e2ea2019-02-21 10:07:37 +00002556 layer->GetOutputSlot(i).SetTensorInfo(detectionBoxOutputTensorInfo);
2557 }
2558
2559 // Register the input connection slots for the layer, connections are made after all layers have been created
2560 // only the tensors for the inputs are relevant, exclude the const tensors
2561 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2562 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2563
2564 // Register the output connection slots for the layer, connections are made after all layers have been created
2565 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2566 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0],
2567 outputTensorIndexes[1],
2568 outputTensorIndexes[2],
2569 outputTensorIndexes[3]});
2570}
2571
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002572/// The TfLite Pack operator is equivalent to the ArmNN Stack operator
Kevin May7d96b162021-02-03 17:38:41 +00002573void TfLiteParserImpl::ParsePack(size_t subgraphIndex, size_t operatorIndex)
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002574{
2575 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2576
2577 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2578 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2579 CHECK_VALID_SIZE(outputs.size(), 1);
2580
2581 if (inputs.size() < 1)
2582 {
2583 throw ParseException("Pack must have at least one input.");
2584 }
2585
2586 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2587 const auto* options = operatorPtr->builtin_options.AsPackOptions();
2588
2589 StackDescriptor desc;
2590 desc.m_Axis = static_cast<uint32_t>(options->axis);
2591 desc.m_NumInputs = static_cast<uint32_t>(inputs.size());
2592
2593 // Use the tensor shape of the first input as the "correct" input shape in the descriptor
2594 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2595 desc.m_InputShape = inputTensorInfo.GetShape();
2596
James Ward58dec6b2020-09-11 17:32:44 +01002597 auto layerName = fmt::format("Pack:{}:{}", subgraphIndex, operatorIndex);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002598 IConnectableLayer* layer = m_Network->AddStackLayer(desc, layerName.c_str());
2599
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002600 ARMNN_ASSERT(layer != nullptr);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002601
Sadik Armagand109a4d2020-07-28 10:42:13 +01002602 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
Matthew Jacksonbcca1f42019-07-16 11:39:21 +01002603 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2604
2605 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2606 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
2607
2608 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2609 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2610}
2611
Kevin May7d96b162021-02-03 17:38:41 +00002612void TfLiteParserImpl::ParseUnpack(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd200e3802019-04-15 09:47:39 +01002613{
2614 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2615
2616 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2617 const auto * options = operatorPtr->builtin_options.AsUnpackOptions();
2618
2619 // This unpackAxis indicates the axis to unpack
2620 const unsigned int unpackAxis = CHECKED_NON_NEGATIVE(options->axis);
2621
2622 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2623 CHECK_VALID_SIZE(inputs.size(), 1);
2624
2625 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002626
2627 if (unpackAxis >= inputTensorInfo.GetNumDimensions())
2628 {
2629 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002630 fmt::format("The unpack axis: {} cannot be greater than or equal to "
2631 "the number of input dimension {} {}",
2632 unpackAxis,
2633 inputTensorInfo.GetNumDimensions(),
2634 CHECK_LOCATION().AsString()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002635 }
2636
Nina Drozd200e3802019-04-15 09:47:39 +01002637 unsigned int unpackNum = CHECKED_NON_NEGATIVE(options->num);
2638 // If num is not defined, automatically infer from the length of the dimension axis.
2639 if(unpackNum == 0)
2640 {
2641 unpackNum = inputTensorInfo.GetShape()[unpackAxis];
2642 }
2643
2644 // If unpack number cannot be inferred and is still zero, throw ParseException.
2645 if(unpackNum == 0)
2646 {
2647 throw ParseException("Number to unpack must greater than zero.");
2648 }
2649
2650 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2651 CHECK_VALID_SIZE(outputs.size(), unpackNum);
2652
2653 auto inputDimSize = inputTensorInfo.GetNumDimensions();
2654 std::vector<unsigned int> unpackDimSizes(inputDimSize);
2655
2656 // Add current input shape to unpackDimSizes
2657 for (unsigned int i = 0; i < inputDimSize; ++i)
2658 {
2659 unpackDimSizes[i] = inputTensorInfo.GetShape()[i];
2660 }
2661
2662 if (unpackDimSizes[unpackAxis] != unpackNum)
2663 {
2664 throw ParseException("Number to unpack must be the same as length of the dimension to "
2665 "unpack along.");
2666 }
2667
2668 unpackDimSizes[unpackAxis] /= unpackNum;
2669
2670 SplitterDescriptor splitDesc(unpackNum, static_cast<unsigned int>(unpackDimSizes.size()));
2671 for (unsigned int j = 0; j < unpackNum; ++j)
2672 {
2673 // Set the size of the views.
2674 for (unsigned int dimIdx = 0; dimIdx < unpackDimSizes.size(); ++dimIdx)
2675 {
2676 splitDesc.SetViewSize(j, dimIdx, unpackDimSizes[dimIdx]);
2677 }
2678 splitDesc.SetViewOriginCoord(j, unpackAxis, unpackDimSizes[unpackAxis] * j);
2679 }
2680
James Ward58dec6b2020-09-11 17:32:44 +01002681 auto layerName = fmt::format("Unpack:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd200e3802019-04-15 09:47:39 +01002682 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002683 ARMNN_ASSERT(layer != nullptr);
Nina Drozd200e3802019-04-15 09:47:39 +01002684
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002685 TensorShape splitOutShape = TensorShape(static_cast<unsigned int>(unpackDimSizes.size()),
2686 unpackDimSizes.data());
2687
Nina Drozd200e3802019-04-15 09:47:39 +01002688 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2689 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2690
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002691 // Create reshape to remove the unpacked dimension for unpack operator of each output from Splitter.
2692 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
2693 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01002694 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[k], true);
James Ward58dec6b2020-09-11 17:32:44 +01002695 std::string reshapeLayerName = fmt::format("Reshape_for:{}", layer->GetName());
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002696 armnn::ReshapeDescriptor desc;
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01002697 desc.m_TargetShape = outputTensorInfo.GetShape();
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002698 armnn::IConnectableLayer* reshapeLayer = m_Network->AddReshapeLayer(desc, layerName.c_str());
2699
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01002700 layer->GetOutputSlot(k).SetTensorInfo(armnn::TensorInfo(splitOutShape,
2701 outputTensorInfo.GetDataType(),
2702 outputTensorInfo.GetQuantizationScale(),
2703 outputTensorInfo.GetQuantizationOffset()));
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002704 layer->GetOutputSlot(k).Connect(reshapeLayer->GetInputSlot(0));
2705
Narumol Prangnawarat2c526462019-10-21 14:58:26 +01002706 reshapeLayer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
Narumol Prangnawarat672de572019-04-23 15:28:06 +01002707
2708 uint32_t reshapedOutputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[k]);
2709 armnn::IOutputSlot* slot = &(reshapeLayer->GetOutputSlot(0));
2710 RegisterProducerOfTensor(subgraphIndex, reshapedOutputId, slot);
2711 }
Nina Drozd200e3802019-04-15 09:47:39 +01002712}
2713
Kevin May7d96b162021-02-03 17:38:41 +00002714void TfLiteParserImpl::ParseSplit(size_t subgraphIndex, size_t operatorIndex)
Nina Drozd0324f482019-04-08 10:52:10 +01002715{
2716 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2717
2718 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2719 const auto * options = operatorPtr->builtin_options.AsSplitOptions();
2720
2721 const unsigned int numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
2722
Nina Drozd200e3802019-04-15 09:47:39 +01002723 // If number of splits cannot be inferred and is zero, throw ParseException.
2724 if(numSplits == 0)
2725 {
2726 throw ParseException("Number to splits must greater than zero.");
2727 }
2728
Nina Drozd0324f482019-04-08 10:52:10 +01002729 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2730 CHECK_VALID_SIZE(inputs.size(), 2);
2731 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2732 CHECK_VALID_SIZE(outputs.size(), numSplits);
2733
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002734 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[1]);
2735 armnn::TensorInfo axisTensorInfo = ToTensorInfo(inputs[0]);
Nina Drozd0324f482019-04-08 10:52:10 +01002736
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002737 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
2738 std::vector<unsigned int> axisData(axisTensorInfo.GetNumElements());
2739 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
2740
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01002741 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002742 const unsigned int splitDim = axisData[0];
Nina Drozd0324f482019-04-08 10:52:10 +01002743
Nina Drozd0324f482019-04-08 10:52:10 +01002744 auto inputDimSize = inputTensorInfo.GetNumDimensions();
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002745 if (inputDimSize > MaxNumOfTensorDimensions)
Nina Drozd0324f482019-04-08 10:52:10 +01002746 {
2747 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002748 fmt::format("The number of dimensions: {} for input tensors of the split op cannot be greater than {} {}",
2749 inputTensorInfo.GetNumDimensions(),
2750 MaxNumOfTensorDimensions,
2751 CHECK_LOCATION().AsString()));
Nina Drozd0324f482019-04-08 10:52:10 +01002752 }
2753
2754 std::vector<unsigned int> splitterDimSizes(inputDimSize);
2755
2756 // Add current input shape to splitterDimSizes
2757 for (unsigned int i = 0; i < inputDimSize; ++i)
2758 {
2759 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
2760 }
2761
2762 if (splitterDimSizes[splitDim] % numSplits != 0)
2763 {
2764 throw ParseException("Number of splits must evenly divide the dimension");
2765 }
2766 splitterDimSizes[splitDim] /= numSplits;
2767
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002768 SplitterDescriptor splitDesc(numSplits, inputDimSize);
Nina Drozd0324f482019-04-08 10:52:10 +01002769 for (unsigned int j = 0; j < numSplits; ++j)
2770 {
2771 // Set the size of the views.
2772 for (unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
2773 {
2774 splitDesc.SetViewSize(j, dimIdx, splitterDimSizes[dimIdx]);
2775 }
2776 splitDesc.SetViewOriginCoord(j, splitDim, splitterDimSizes[splitDim] * j);
2777 }
2778
James Ward58dec6b2020-09-11 17:32:44 +01002779 auto layerName = fmt::format("Split:{}:{}", subgraphIndex, operatorIndex);
Nina Drozd0324f482019-04-08 10:52:10 +01002780 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002781 ARMNN_ASSERT(layer != nullptr);
Nina Drozd0324f482019-04-08 10:52:10 +01002782
2783 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
Narumol Prangnawarat17660e62019-04-18 16:56:19 +01002784 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[1]});
Nina Drozd0324f482019-04-08 10:52:10 +01002785
Nina Drozd0324f482019-04-08 10:52:10 +01002786 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
2787 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01002788 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Francis Murtagh98d6b3d2019-10-21 10:52:54 +01002789 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
Nina Drozd0324f482019-04-08 10:52:10 +01002790 }
2791
2792 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2793 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2794}
2795
Derek Lambertif0176992020-04-28 13:37:49 +01002796unsigned int ComputeWrappedIndex(int idx, unsigned int numDimsIn)
2797{
2798 int numDims = armnn::numeric_cast<int>(numDimsIn);
2799 int v = idx < 0 ? numDims + idx : idx;
2800 ARMNN_ASSERT(v >= 0);
2801 ARMNN_ASSERT(v < numDims);
2802
2803 return static_cast<unsigned int>(v);
2804}
2805
Kevin May7d96b162021-02-03 17:38:41 +00002806void TfLiteParserImpl::ParseSplitV(size_t subgraphIndex, size_t operatorIndex)
Derek Lambertif0176992020-04-28 13:37:49 +01002807{
2808 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2809
2810 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
Ryan OShea86704732020-05-26 11:41:04 +01002811 const auto * options = operatorPtr->builtin_options.AsSplitVOptions();
Derek Lambertif0176992020-04-28 13:37:49 +01002812
2813 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2814 CHECK_VALID_SIZE(inputs.size(), 3);
2815
2816 auto& inputTensor = inputs[0];
2817 auto& splitsTensor = inputs[1];
2818 auto& axisTensor = inputs[2];
2819
2820 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputTensor);
2821 armnn::TensorInfo splitsInfo = ToTensorInfo(splitsTensor);
2822 armnn::TensorInfo axisTensorInfo = ToTensorInfo(axisTensor);
2823 ARMNN_ASSERT(axisTensorInfo.GetNumElements() == 1);
2824
2825 // Inputs
2826 auto inputDimSize = inputTensorInfo.GetNumDimensions();
2827 if (inputDimSize > MaxNumOfTensorDimensions)
2828 {
2829 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01002830 fmt::format("The number of dimensions: {} for input tensors of the "
2831 "SplitV op cannot be greater than {} {}",
2832 inputTensorInfo.GetNumDimensions(),
2833 MaxNumOfTensorDimensions,
2834 CHECK_LOCATION().AsString()));
Derek Lambertif0176992020-04-28 13:37:49 +01002835 }
2836
2837 // Get split axis
2838 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, axisTensor->buffer);
2839 std::vector<int> axisData(axisTensorInfo.GetNumElements());
2840 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.GetNumBytes());
2841 const unsigned int splitDim = ComputeWrappedIndex(axisData[0], inputTensorInfo.GetNumDimensions());
2842
Derek Lambertif0176992020-04-28 13:37:49 +01002843 // Set split sizes
Derek Lambertif0176992020-04-28 13:37:49 +01002844 CHECK_VALID_SIZE(splitsInfo.GetNumDimensions(), 1);
Ryan OShea86704732020-05-26 11:41:04 +01002845 unsigned int numSplits{0};
2846
2847 if(options)
Derek Lambertif0176992020-04-28 13:37:49 +01002848 {
2849 numSplits = CHECKED_NON_NEGATIVE(options->num_splits);
Derek Lambertif0176992020-04-28 13:37:49 +01002850 }
2851 else
2852 {
Ryan OShea86704732020-05-26 11:41:04 +01002853 numSplits = splitsInfo.GetNumElements();
Derek Lambertif0176992020-04-28 13:37:49 +01002854 }
2855
2856 if (numSplits <=0)
2857 {
2858 throw ParseException("SplitV has invalid number of splits");
2859 }
2860
Jan Eilersc0761e92020-06-29 16:48:44 +01002861 std::vector<int> splitsData(numSplits);
Ryan OShea86704732020-05-26 11:41:04 +01002862 BufferRawPtr splitsBufferPtr = GetBuffer(m_Model, splitsTensor->buffer);
Jan Eilersc0761e92020-06-29 16:48:44 +01002863 ::memcpy(splitsData.data(), splitsBufferPtr->data.data(), splitsInfo.GetNumBytes());
Ryan OShea86704732020-05-26 11:41:04 +01002864
Jan Eilersc0761e92020-06-29 16:48:44 +01002865 unsigned int idx = 0;
Ryan OShea86704732020-05-26 11:41:04 +01002866 int numInferred{0};
2867 unsigned int inferIdx{0};
2868 int splitSum{0};
2869 for (auto split : splitsData)
2870 {
2871 if (split < 0)
2872 {
2873 numInferred++;
2874 inferIdx = idx;
2875 }
2876 else
2877 {
2878 splitSum += split;
2879 }
2880 idx++;
2881 }
2882 // Check for inferred Axis
2883 if (numInferred == 0)
2884 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002885 if (splitSum != armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]))
Ryan OShea86704732020-05-26 11:41:04 +01002886 {
2887 throw ParseException("SplitV split_sizes does not sum to the dimension of value along split_dim.");
2888 }
2889 }
2890 else if (numInferred == 1)
2891 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002892 splitsData[inferIdx] = armnn::numeric_cast<int>(inputTensorInfo.GetShape()[splitDim]) - splitSum;
Ryan OShea86704732020-05-26 11:41:04 +01002893 }
2894 else
2895 {
2896 throw ParseException("Cannot infer split size for more than one split");
2897 }
2898
Derek Lambertif0176992020-04-28 13:37:49 +01002899 //Ouput size validation
2900 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2901 CHECK_VALID_SIZE(outputs.size(), numSplits);
2902
2903 // Setup Armnn descriptor
2904 SplitterDescriptor splitDesc(numSplits, inputDimSize);
2905 unsigned int accumSplit = 0;
2906 for (unsigned int j = 0; j < numSplits; ++j)
2907 {
Matthew Sloyan589e3e82020-09-11 16:17:48 +01002908 unsigned int splitSize = armnn::numeric_cast<unsigned int>(splitsData[j]);
Derek Lambertif0176992020-04-28 13:37:49 +01002909
2910 // Set the size of the views.
2911 for (unsigned int dimIdx = 0; dimIdx < inputTensorInfo.GetNumDimensions(); ++dimIdx)
2912 {
2913 unsigned int dimSize = inputTensorInfo.GetShape()[dimIdx];
2914 if (dimIdx == splitDim)
2915 {
2916 dimSize = splitSize;
2917 }
2918 splitDesc.SetViewSize(j, dimIdx, dimSize);
2919 }
2920
2921 splitDesc.SetViewOriginCoord(j, splitDim, accumSplit);
2922 accumSplit += splitSize;
2923 }
2924
James Ward58dec6b2020-09-11 17:32:44 +01002925 auto layerName = fmt::format("SplitV:{}:{}", subgraphIndex, operatorIndex);
Derek Lambertif0176992020-04-28 13:37:49 +01002926 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
James Conroy05102392020-06-24 15:39:55 +01002927 ARMNN_ASSERT(layer != nullptr);
Derek Lambertif0176992020-04-28 13:37:49 +01002928
2929 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2930 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2931
2932 for (unsigned int k = 0; k < layer->GetNumOutputSlots(); ++k)
2933 {
Sadik Armagand109a4d2020-07-28 10:42:13 +01002934 armnn::TensorInfo tensorInfo = ToTensorInfo(outputs[k], true);
Derek Lambertif0176992020-04-28 13:37:49 +01002935 layer->GetOutputSlot(k).SetTensorInfo(tensorInfo);
2936 }
2937
2938 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2939 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2940}
2941
Kevin May7d96b162021-02-03 17:38:41 +00002942void TfLiteParserImpl::ParseArgMax(size_t subgraphIndex, size_t operatorIndex)
Inki Daed4619e22020-09-10 15:33:54 +09002943{
2944 const auto &operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2945 const auto *options = operatorPtr->builtin_options.AsArgMaxOptions();
2946
2947 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2948 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
2949 CHECK_VALID_SIZE(inputs.size(), 2);
2950
2951 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
2952 CHECK_VALID_SIZE(outputs.size(), 1);
2953
James Ward58dec6b2020-09-11 17:32:44 +01002954 auto layerName = fmt::format("ArgMax:{}:{}", subgraphIndex, operatorIndex);
Inki Daed4619e22020-09-10 15:33:54 +09002955
2956 armnn::TensorInfo sizeTensorInfo0 = ToTensorInfo(inputs[0]);
2957 armnn::TensorInfo sizeTensorInfo1 = ToTensorInfo(inputs[1]);
2958
2959 // Get const axis value from model and set it to descriptor.
2960 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
2961
2962 ArgMinMaxDescriptor desc;
2963 desc.m_Axis = axisBufferPtr->data.data()[0];
2964 // If output_type is int32 then set Signed32 else Signed64. Default type is Signed64.
2965 desc.m_Output_Type = options->output_type == 3 ? armnn::DataType::Signed32 : armnn::DataType::Signed64;
2966 desc.m_Function = ArgMinMaxFunction::Max;
2967
2968 // Register a ArgMax layer.
2969 IConnectableLayer *layer = m_Network->AddArgMinMaxLayer(desc, layerName.c_str());
2970
2971 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
2972 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
2973
2974 // Register input tensor to the layer.
2975 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2976 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2977
2978 // Register output tensor to the layer.
2979 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2980 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2981}
2982
Kevin May7d96b162021-02-03 17:38:41 +00002983void TfLiteParserImpl::ParseGather(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00002984{
2985 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2986
Kevin May7d96b162021-02-03 17:38:41 +00002987 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00002988 CHECK_VALID_SIZE(inputs.size(), 2);
Kevin May7d96b162021-02-03 17:38:41 +00002989 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00002990 CHECK_VALID_SIZE(outputs.size(), 1);
2991
2992 armnn::TensorInfo inputTensorInfo = ToTensorInfo(inputs[0]);
2993 armnn::TensorInfo indicesTensorInfo = ToTensorInfo(inputs[1]);
2994 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
2995
2996 armnn::GatherDescriptor gatherDescriptor;
2997
2998 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2999 const auto * options = operatorPtr->builtin_options.AsGatherOptions();
3000 auto axis = options->axis;
3001
3002 auto inputDimensions = static_cast<int32_t>(inputTensorInfo.GetNumDimensions());
3003 auto indicesDimensions = indicesTensorInfo.GetNumDimensions();
3004 auto outputDimensions = outputTensorInfo.GetNumDimensions();
3005 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3006 {
3007 throw ParseException(
3008 fmt::format("Operation has invalid axis: {} It is out of bounds [ -{}, {} ) {}",
3009 axis,
3010 inputDimensions, inputDimensions,
3011 CHECK_LOCATION().AsString()));
3012 }
3013 if (outputDimensions != static_cast<unsigned int>(inputDimensions) + indicesDimensions - 1)
3014 {
3015 throw ParseException(
3016 fmt::format("Operation has invalid output dimensions: {} Output must be an ({} + {} - 1) -D tensor {}",
3017 outputDimensions,
3018 inputDimensions, indicesDimensions,
3019 CHECK_LOCATION().AsString()));
3020 }
3021
3022 gatherDescriptor.m_Axis = axis;
3023
3024 auto layerName = fmt::format("Gather:{}:{}", subgraphIndex, operatorIndex);
3025 IConnectableLayer* layer = m_Network->AddGatherLayer(gatherDescriptor, layerName.c_str());
3026 ARMNN_ASSERT(layer != nullptr);
3027 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3028
3029 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3030 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3031
3032 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3033 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3034}
3035
Kevin May7d96b162021-02-03 17:38:41 +00003036void TfLiteParserImpl::ParseDepthToSpace(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan26868492021-01-22 14:25:31 +00003037{
3038 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3039
Kevin May7d96b162021-02-03 17:38:41 +00003040 TfLiteParserImpl::TensorRawPtrVector inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003041 CHECK_VALID_SIZE(inputs.size(), 1);
Kevin May7d96b162021-02-03 17:38:41 +00003042 TfLiteParserImpl::TensorRawPtrVector outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
Sadik Armagan26868492021-01-22 14:25:31 +00003043 CHECK_VALID_SIZE(outputs.size(), 1);
3044
3045 armnn::DepthToSpaceDescriptor descriptor;
3046
3047 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3048 const auto * options = operatorPtr->builtin_options.AsDepthToSpaceOptions();
3049 auto blockSize = options->block_size;
3050 if (blockSize < 2)
3051 {
3052 throw ParseException(
3053 fmt::format("Operation has invalid block size: {} Block size should be >= 2 {}",
3054 blockSize,
3055 CHECK_LOCATION().AsString()));
3056 }
3057 descriptor.m_BlockSize = armnn::numeric_cast<uint32_t>(blockSize);
3058
3059 auto layerName = fmt::format("DepthToSpace:{}:{}", subgraphIndex, operatorIndex);
3060 IConnectableLayer* layer = m_Network->AddDepthToSpaceLayer(descriptor, layerName.c_str());
3061 ARMNN_ASSERT(layer != nullptr);
3062 TensorInfo outputTensorInfo = ToTensorInfo(outputs[0], true);
3063 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3064
3065 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3066 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3067
3068 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3069 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3070}
3071
Kevin May7d96b162021-02-03 17:38:41 +00003072void TfLiteParserImpl::ParseSum(size_t subgraphIndex, size_t operatorIndex)
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003073{
Sadik Armagana2747482021-02-09 10:28:54 +00003074 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Sum);
3075}
3076
3077void TfLiteParserImpl::ParseReduceMax(size_t subgraphIndex, size_t operatorIndex)
3078{
3079 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Max);
3080}
3081
3082void TfLiteParserImpl::ParseReduceMin(size_t subgraphIndex, size_t operatorIndex)
3083{
3084 ParseReduce(subgraphIndex, operatorIndex, armnn::ReduceOperation::Min);
3085}
3086
3087void TfLiteParserImpl::ParseReduce(size_t subgraphIndex, size_t operatorIndex, ReduceOperation reduceOperation)
3088{
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003089 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3090
3091 const auto &operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3092 const auto *options = operatorPtr->builtin_options.AsReducerOptions();
3093
3094 auto inputs = GetInputs(m_Model, subgraphIndex, operatorIndex);
3095 CHECK_VALID_SIZE(inputs.size(), 2);
3096
3097 auto outputs = GetOutputs(m_Model, subgraphIndex, operatorIndex);
3098 CHECK_VALID_SIZE(outputs.size(), 1);
3099
Sadik Armagana2747482021-02-09 10:28:54 +00003100 auto layerName = fmt::format("Reduce:{}:{}", subgraphIndex, operatorIndex);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003101
3102 armnn::TensorInfo inputTensorInfo0 = ToTensorInfo(inputs[0]);
3103 armnn::TensorInfo inputTensorInfo1 = ToTensorInfo(inputs[1]);
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003104
3105 ReduceDescriptor desc;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003106 BufferRawPtr axisBufferPtr = GetBuffer(m_Model, inputs[1]->buffer);
3107 // Get const axis value from model and set it to descriptor.
3108 if (axisBufferPtr != nullptr)
3109 {
Sadik Armagan49bdb792021-02-11 13:57:07 +00003110 std::vector<int32_t> axisData(inputTensorInfo1.GetNumElements());
3111 ::memcpy(axisData.data(), axisBufferPtr->data.data(), inputTensorInfo1.GetNumBytes());
3112
3113 // Convert the axis to unsigned int and remove duplicates.
3114 auto rank = static_cast<int32_t>(inputTensorInfo0.GetNumDimensions());
3115 std::set<unsigned int> uniqueAxis;
3116 std::transform(axisData.begin(),
3117 axisData.end(),
3118 std::inserter(uniqueAxis, uniqueAxis.begin()),
3119 [rank](int i)->unsigned int{
3120 return static_cast<uint32_t>(((i + rank) % rank)); });
3121 desc.m_vAxis.assign(uniqueAxis.begin(), uniqueAxis.end());
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003122 }
Sadik Armagana2747482021-02-09 10:28:54 +00003123 else
3124 {
3125 for (uint32_t i = 0; i < inputTensorInfo0.GetNumDimensions(); ++i)
3126 {
3127 desc.m_vAxis.push_back(i);
3128 }
3129 }
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003130
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003131 desc.m_KeepDims = options->keep_dims;
Sadik Armagana2747482021-02-09 10:28:54 +00003132 desc.m_ReduceOperation = reduceOperation;
Sadik Armagan0c3ea5b2021-02-03 09:29:30 +00003133
3134 // Register a new layer object, Sum.
3135 IConnectableLayer *layer = m_Network->AddReduceLayer(desc, layerName.c_str());
3136
3137 armnn::TensorInfo outputTensorInfo = ToTensorInfo(outputs[0]);
3138 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
3139
3140 // Register input tensor to the layer.
3141 auto inputTensorIndexes = AsUnsignedVector(GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3142 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3143
3144 // Register output tensor to the layer.
3145 auto outputTensorIndexes = AsUnsignedVector(GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3146 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3147}
3148
Kevin May7d96b162021-02-03 17:38:41 +00003149armnn::IConnectableLayer* TfLiteParserImpl::AddFusedActivationLayer(armnn::IConnectableLayer* prevLayer,
3150 unsigned int outputSlot,
3151 tflite::ActivationFunctionType activationType)
telsoa01c577f2c2018-08-31 09:22:23 +01003152{
3153 ActivationDescriptor activationDesc;
3154 std::string layerName = prevLayer->GetName();
3155
3156 switch(activationType)
3157 {
3158 case tflite::ActivationFunctionType_NONE:
3159 {
3160 // this is a no-op: return previous layer
3161 return prevLayer;
3162 }
3163 case tflite::ActivationFunctionType_RELU:
3164 {
3165 activationDesc.m_Function = ActivationFunction::ReLu;
3166 layerName += ":RELU";
3167 break;
3168 }
3169 case tflite::ActivationFunctionType_RELU6:
3170 {
3171 activationDesc.m_Function = ActivationFunction::BoundedReLu;
3172 activationDesc.m_A = 6.0f;
3173 activationDesc.m_B = 0.0f;
3174 layerName += ":RELU6";
3175 break;
3176 }
3177 case tflite::ActivationFunctionType_TANH:
3178 {
3179 activationDesc.m_Function = ActivationFunction::TanH;
3180 activationDesc.m_A = 1.0f;
3181 activationDesc.m_B = 1.0f;
3182 layerName += ":TANH";
3183 break;
3184 }
3185
3186 // I only put these here as a reminder what others we could support
3187 case tflite::ActivationFunctionType_RELU_N1_TO_1:
3188 case tflite::ActivationFunctionType_SIGN_BIT:
3189 default:
3190 {
3191 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003192 fmt::format("TfLite parser doesn't suppport fused activation: "
3193 "{}/{} {} ",
3194 activationType,
3195 tflite::EnumNameActivationFunctionType(activationType),
3196 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003197
3198 }
3199 }
3200
3201 IConnectableLayer* activationLayer =
3202 m_Network->AddActivationLayer(activationDesc, layerName.c_str());
3203
3204 auto & prevOutputSlot = prevLayer->GetOutputSlot(outputSlot);
3205 prevOutputSlot.Connect(activationLayer->GetInputSlot(0));
3206 activationLayer->GetOutputSlot(0).SetTensorInfo(prevOutputSlot.GetTensorInfo());
3207 return activationLayer;
3208}
3209
Kevin May7d96b162021-02-03 17:38:41 +00003210TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromFile(const char * fileName)
telsoa01c577f2c2018-08-31 09:22:23 +01003211{
3212 if (fileName == nullptr)
3213 {
James Ward58dec6b2020-09-11 17:32:44 +01003214 throw InvalidArgumentException(fmt::format("Invalid (null) file name {}",
telsoa01c577f2c2018-08-31 09:22:23 +01003215 CHECK_LOCATION().AsString()));
3216 }
Francis Murtagh532a29d2020-06-29 11:50:01 +01003217 std::error_code errorCode;
3218 fs::path pathToFile(fileName);
3219 if (!fs::exists(pathToFile, errorCode))
telsoa01c577f2c2018-08-31 09:22:23 +01003220 {
James Ward58dec6b2020-09-11 17:32:44 +01003221 //fmt::format() could not be used here (format error)
3222 std::stringstream msg;
3223 msg << "Cannot find the file (" << fileName << ") errorCode: " << errorCode
3224 << " " << CHECK_LOCATION().AsString();
3225
3226 throw FileNotFoundException(msg.str());
telsoa01c577f2c2018-08-31 09:22:23 +01003227 }
3228 std::ifstream file(fileName, std::ios::binary);
3229 std::string fileContent((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
3230 return LoadModelFromBinary(reinterpret_cast<const uint8_t *>(fileContent.c_str()),
3231 fileContent.size());
3232}
3233
Kevin May7d96b162021-02-03 17:38:41 +00003234TfLiteParserImpl::ModelPtr TfLiteParserImpl::LoadModelFromBinary(const uint8_t * binaryContent, size_t len)
telsoa01c577f2c2018-08-31 09:22:23 +01003235{
3236 if (binaryContent == nullptr)
3237 {
James Ward58dec6b2020-09-11 17:32:44 +01003238 throw InvalidArgumentException(fmt::format("Invalid (null) binary content {}",
telsoa01c577f2c2018-08-31 09:22:23 +01003239 CHECK_LOCATION().AsString()));
3240 }
3241 flatbuffers::Verifier verifier(binaryContent, len);
3242 if (verifier.VerifyBuffer<tflite::Model>() == false)
3243 {
3244 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003245 fmt::format("Buffer doesn't conform to the expected Tensorflow Lite "
3246 "flatbuffers format. size:{} {}",
3247 len,
3248 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003249 }
3250 return tflite::UnPackModel(binaryContent);
3251}
3252
Kevin May7d96b162021-02-03 17:38:41 +00003253TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetInputs(const ModelPtr & model,
3254 size_t subgraphIndex,
3255 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003256{
3257 CHECK_MODEL(model, subgraphIndex, operatorIndex);
3258
Derek Lambertiff05cc52019-04-26 13:05:17 +01003259 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3260 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003261
3262 size_t inputCount = operatorPtr->inputs.size();
3263 TensorRawPtrVector result(inputCount);
3264 for (size_t i=0; i<inputCount; ++i)
3265 {
3266 uint32_t inputId = CHECKED_NON_NEGATIVE(operatorPtr->inputs[i]);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003267 result[i] = subgraphPtr->tensors[inputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01003268 }
3269 return result;
3270}
3271
Kevin May7d96b162021-02-03 17:38:41 +00003272TfLiteParserImpl::TensorRawPtrVector TfLiteParserImpl::GetOutputs(const ModelPtr & model,
3273 size_t subgraphIndex,
3274 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003275{
3276 CHECK_MODEL(model, subgraphIndex, operatorIndex);
3277
Derek Lambertiff05cc52019-04-26 13:05:17 +01003278 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3279 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003280
3281 size_t outputCount = operatorPtr->outputs.size();
3282 TensorRawPtrVector result(outputCount);
3283 for (size_t i=0; i<outputCount; ++i)
3284 {
3285 uint32_t outputId = CHECKED_NON_NEGATIVE(operatorPtr->outputs[i]);
3286 CHECK_TENSOR(model, subgraphIndex, outputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003287 result[i] = subgraphPtr->tensors[outputId].get();
telsoa01c577f2c2018-08-31 09:22:23 +01003288 }
3289 return result;
3290}
3291
Kevin May7d96b162021-02-03 17:38:41 +00003292TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphInputs(const ModelPtr & model,
3293 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003294{
3295 CHECK_SUBGRAPH(model, subgraphIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003296 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003297
Derek Lambertiff05cc52019-04-26 13:05:17 +01003298 size_t inputCount = subgraphPtr->inputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01003299 TensorIdRawPtrVector result(inputCount);
3300 for (size_t i=0; i<inputCount; ++i)
3301 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01003302 uint32_t inputId = CHECKED_NON_NEGATIVE(subgraphPtr->inputs[i]);
telsoa01c577f2c2018-08-31 09:22:23 +01003303 CHECK_TENSOR(model, subgraphIndex, inputId);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003304 result[i] = std::make_pair(inputId, subgraphPtr->tensors[inputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01003305 }
3306 return result;
3307}
3308
Kevin May7d96b162021-02-03 17:38:41 +00003309TfLiteParserImpl::TensorIdRawPtrVector TfLiteParserImpl::GetSubgraphOutputs(const ModelPtr & model,
3310 size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003311{
3312 CHECK_SUBGRAPH(model, subgraphIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003313 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003314
Derek Lambertiff05cc52019-04-26 13:05:17 +01003315 size_t outputCount = subgraphPtr->outputs.size();
telsoa01c577f2c2018-08-31 09:22:23 +01003316 TensorIdRawPtrVector result(outputCount);
3317 for (size_t i=0; i<outputCount; ++i)
3318 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01003319 uint32_t outputId = CHECKED_NON_NEGATIVE(subgraphPtr->outputs[i]);
3320 result[i] = std::make_pair(outputId, subgraphPtr->tensors[outputId].get());
telsoa01c577f2c2018-08-31 09:22:23 +01003321 }
3322 return result;
3323}
3324
Kevin May7d96b162021-02-03 17:38:41 +00003325std::vector<int32_t>& TfLiteParserImpl::GetInputTensorIds(const ModelPtr& model,
3326 size_t subgraphIndex,
3327 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003328{
3329 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003330 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3331 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003332 return operatorPtr->inputs;
3333}
3334
Kevin May7d96b162021-02-03 17:38:41 +00003335std::vector<int32_t>& TfLiteParserImpl::GetOutputTensorIds(const ModelPtr& model,
3336 size_t subgraphIndex,
3337 size_t operatorIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003338{
3339 CHECK_MODEL(model, subgraphIndex, operatorIndex);
Derek Lambertiff05cc52019-04-26 13:05:17 +01003340 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3341 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
telsoa01c577f2c2018-08-31 09:22:23 +01003342 return operatorPtr->outputs;
3343}
3344
Kevin May7d96b162021-02-03 17:38:41 +00003345void TfLiteParserImpl::RegisterInputSlots(size_t subgraphIndex,
3346 size_t operatorIndex,
3347 IConnectableLayer* layer,
Finn Williamsd4fa5452021-03-01 12:31:41 +00003348 const std::vector<unsigned int>& tensorIndexes,
3349 unsigned int startingSlotIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003350{
3351 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003352 ARMNN_ASSERT(layer != nullptr);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003353 if (tensorIndexes.size() + startingSlotIndex != layer->GetNumInputSlots())
telsoa01c577f2c2018-08-31 09:22:23 +01003354 {
3355 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003356 fmt::format("The number of tensor inputs ({}) does not match the number expected ({})"
3357 " for subgraph:{} operator index:{} {}",
3358 tensorIndexes.size(),
3359 layer->GetNumInputSlots(),
3360 subgraphIndex,
3361 operatorIndex,
3362 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003363 }
3364
Finn Williamsd4fa5452021-03-01 12:31:41 +00003365 for (unsigned int index = 0; index < tensorIndexes.size() ; ++index)
telsoa01c577f2c2018-08-31 09:22:23 +01003366 {
Finn Williamsd4fa5452021-03-01 12:31:41 +00003367 unsigned int tensorIndex = tensorIndexes[index];
3368 armnn::IInputSlot* slot = &(layer->GetInputSlot(startingSlotIndex + index));
telsoa01c577f2c2018-08-31 09:22:23 +01003369 RegisterConsumerOfTensor(subgraphIndex, tensorIndex, slot);
3370 }
3371}
3372
Kevin May7d96b162021-02-03 17:38:41 +00003373void TfLiteParserImpl::RegisterOutputSlots(size_t subgraphIndex,
3374 size_t operatorIndex,
3375 IConnectableLayer* layer,
3376 const std::vector<unsigned int>& tensorIndexes)
telsoa01c577f2c2018-08-31 09:22:23 +01003377{
3378 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +01003379 ARMNN_ASSERT(layer != nullptr);
telsoa01c577f2c2018-08-31 09:22:23 +01003380 if (tensorIndexes.size() != layer->GetNumOutputSlots())
3381 {
3382 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003383 fmt::format("The number of tensor outputs ({}) does not match the number expected ({})"
3384 " for subgraph:{} operator index:{} {}",
3385 tensorIndexes.size(),
3386 layer->GetNumOutputSlots(),
3387 subgraphIndex,
3388 operatorIndex,
3389 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003390 }
3391
3392 for (unsigned int slotIndex = 0; slotIndex < layer->GetNumOutputSlots(); ++slotIndex)
3393 {
3394 unsigned int tensorIndex = tensorIndexes[slotIndex];
3395 armnn::IOutputSlot* slot = &(layer->GetOutputSlot(slotIndex));
3396 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
3397 }
3398}
3399
Kevin May7d96b162021-02-03 17:38:41 +00003400void TfLiteParserImpl::SetupInputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003401{
3402 CHECK_SUBGRAPH(m_Model, subgraphIndex);
3403
3404 auto inputs = GetSubgraphInputs(m_Model, subgraphIndex);
3405 for (auto const & tensorIdAndPtr : inputs)
3406 {
3407 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
3408 IConnectableLayer* layer =
3409 m_Network->AddInputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
3410
3411 auto tensorInfo = ToTensorInfo(tensorIdAndPtr.second);
3412 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
3413
3414 RegisterOutputSlots(subgraphIndex,
3415 VIRTUAL_OPERATOR_ID,
3416 layer,
3417 { static_cast<uint32_t>(tensorIdAndPtr.first) });
3418 }
3419}
3420
Kevin May7d96b162021-02-03 17:38:41 +00003421void TfLiteParserImpl::SetupOutputLayers(size_t subgraphIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003422{
3423 CHECK_SUBGRAPH(m_Model, subgraphIndex);
3424
3425 auto outputs = GetSubgraphOutputs(m_Model, subgraphIndex);
3426 for (auto const & tensorIdAndPtr : outputs)
3427 {
3428 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
3429 IConnectableLayer* layer =
3430 m_Network->AddOutputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
3431
3432 RegisterInputSlots(subgraphIndex,
3433 VIRTUAL_OPERATOR_ID,
3434 layer,
3435 { static_cast<uint32_t>(tensorIdAndPtr.first) });
3436 }
3437}
3438
Kevin May7d96b162021-02-03 17:38:41 +00003439void TfLiteParserImpl::SetupConstantLayers(size_t subgraphIndex)
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003440{
3441 CHECK_SUBGRAPH(m_Model, subgraphIndex);
3442
Derek Lambertiff05cc52019-04-26 13:05:17 +01003443 const auto & subgraphPtr = m_Model->subgraphs[subgraphIndex];
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003444 for (unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
3445 {
3446 for (unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
3447 {
3448 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot == nullptr &&
3449 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
3450 {
Derek Lambertiff05cc52019-04-26 13:05:17 +01003451 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003452 armnn::TensorInfo tensorInfo = ToTensorInfo(tensorPtr);
Finn Williamsd4fa5452021-03-01 12:31:41 +00003453 auto tensorAndData = CreateConstTensorNonPermuted(tensorPtr, tensorInfo);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003454
James Ward58dec6b2020-09-11 17:32:44 +01003455 std::string layerName = fmt::format("Constant:{}", tensorPtr->name);
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003456 IConnectableLayer *layer =
Finn Williamsd4fa5452021-03-01 12:31:41 +00003457 m_Network->AddConstantLayer(tensorAndData, layerName.c_str());
Bruno Goncalves3d7efe92018-12-27 14:21:43 -02003458
3459 layer->GetOutputSlot(0).SetTensorInfo(tensorInfo);
3460 RegisterOutputSlots(subgraphIndex,
3461 VIRTUAL_OPERATOR_ID,
3462 layer,
3463 { tensorIndex });
3464
3465 }
3466 }
3467 }
3468}
3469
telsoa01c577f2c2018-08-31 09:22:23 +01003470// example usage: BufferRawPtr bufferPtr = GetBuffer(m_Model, inputs[0]->buffer);
Kevin May7d96b162021-02-03 17:38:41 +00003471TfLiteParserImpl::BufferRawPtr TfLiteParserImpl::GetBuffer(const ModelPtr& model, size_t bufferIndex)
telsoa01c577f2c2018-08-31 09:22:23 +01003472{
3473 CHECK_BUFFER(model, bufferIndex);
3474 return model->buffers[bufferIndex].get();
3475}
3476
Matteo Martincigh747ef822018-12-18 09:26:39 +00003477template<typename T>
Kevin May7d96b162021-02-03 17:38:41 +00003478std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
3479TfLiteParserImpl::CreateConstTensorAndStoreData(TfLiteParserImpl::BufferRawPtr bufferPtr,
3480 TfLiteParserImpl::TensorRawPtr tensorPtr,
Matteo Martincigh747ef822018-12-18 09:26:39 +00003481 armnn::TensorInfo& tensorInfo,
3482 armnn::Optional<armnn::PermutationVector&> permutationVector)
3483{
3484 auto constData = CreateConstTensorImpl<T>(bufferPtr,
3485 tensorPtr,
3486 tensorInfo,
3487 permutationVector);
Kevin May7d96b162021-02-03 17:38:41 +00003488 TfLiteParserImpl::SupportedDataStorage storage(std::move(constData.second));
Matteo Martincigh747ef822018-12-18 09:26:39 +00003489 return std::make_pair(constData.first, std::move(storage));
3490}
3491
Finn Williamsd4fa5452021-03-01 12:31:41 +00003492bool TfLiteParserImpl::IsConstTensor(TensorRawPtr tensorPtr)
3493{
3494 CHECK_TENSOR_PTR(tensorPtr);
3495 return !tensorPtr->is_variable;
3496}
3497
3498
Kevin May7d96b162021-02-03 17:38:41 +00003499std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
Finn Williamsd4fa5452021-03-01 12:31:41 +00003500TfLiteParserImpl::CreateConstTensorPermuted(TensorRawPtr tensorPtr,
3501 armnn::TensorInfo& tensorInfo,
3502 armnn::Optional<armnn::PermutationVector&> permutationVector)
telsoa01c577f2c2018-08-31 09:22:23 +01003503{
3504 CHECK_TENSOR_PTR(tensorPtr);
3505 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
3506 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
3507
3508 switch (tensorInfo.GetDataType())
3509 {
3510 case armnn::DataType::Float32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00003511 return CreateConstTensorAndStoreData<float>(bufferPtr,
3512 tensorPtr,
3513 tensorInfo,
3514 permutationVector);
Derek Lambertif90c56d2020-01-10 17:14:08 +00003515 case armnn::DataType::QAsymmU8:
Matteo Martincigh747ef822018-12-18 09:26:39 +00003516 return CreateConstTensorAndStoreData<uint8_t>(bufferPtr,
3517 tensorPtr,
3518 tensorInfo,
3519 permutationVector);
Keith Davisd305e1a2020-01-22 11:57:54 +00003520 case armnn::DataType::QSymmS8:
3521 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
3522 tensorPtr,
3523 tensorInfo,
3524 permutationVector);
Keith Davis67e6c542020-02-19 10:08:33 +00003525 case armnn::DataType::QAsymmS8:
3526 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
3527 tensorPtr,
3528 tensorInfo,
3529 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01003530 case armnn::DataType::Signed32:
Matteo Martincigh747ef822018-12-18 09:26:39 +00003531 return CreateConstTensorAndStoreData<int32_t>(bufferPtr,
3532 tensorPtr,
3533 tensorInfo,
3534 permutationVector);
telsoa01c577f2c2018-08-31 09:22:23 +01003535 default:
3536 {
3537 std::stringstream errString;
3538 errString << "Unexpected datatype when creating const tensor: "
3539 << armnn::GetDataTypeName(tensorInfo.GetDataType())
3540 << " shape:" << tensorInfo.GetShape()
3541 << CHECK_LOCATION().AsString();
3542 throw ParseException(errString.str());
3543 }
3544 }
3545}
3546
Finn Williamsd4fa5452021-03-01 12:31:41 +00003547armnn::ConstTensor TfLiteParserImpl::CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
3548 armnn::TensorInfo& tensorInfo)
3549{
3550 CHECK_TENSOR_PTR(tensorPtr);
3551 auto bufferPtr = GetBuffer(m_Model, tensorPtr->buffer);
3552 CHECK_BUFFER_SIZE(bufferPtr, tensorInfo, tensorPtr->buffer);
3553
3554 return ConstTensor(tensorInfo, bufferPtr->data.data());
3555}
3556
Kevin May7d96b162021-02-03 17:38:41 +00003557BindingPointInfo TfLiteParserImpl::GetNetworkInputBindingInfo(size_t subgraphId,
3558 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01003559{
3560 CHECK_SUBGRAPH(m_Model, subgraphId);
3561 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
3562 for (auto const & input : inputs)
3563 {
3564 if (input.second->name == name)
3565 {
3566 auto bindingId = GenerateLayerBindingId(subgraphId, input.first);
3567 return std::make_pair(bindingId, ToTensorInfo(input.second));
3568 }
3569 }
3570
3571 std::stringstream bindings;
3572 for (auto const & input : inputs)
3573 {
3574 bindings << "'" << input.second->name << "' ";
3575 }
3576
3577 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003578 fmt::format("No input binding found for subgraph:{} and name:{}. "
3579 "Possible inputs are: [{}] {}",
3580 subgraphId,
3581 name,
3582 bindings.str(),
3583 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003584}
3585
Kevin May7d96b162021-02-03 17:38:41 +00003586BindingPointInfo TfLiteParserImpl::GetNetworkOutputBindingInfo(size_t subgraphId,
3587 const std::string& name) const
telsoa01c577f2c2018-08-31 09:22:23 +01003588{
3589 CHECK_SUBGRAPH(m_Model, subgraphId);
3590 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003591 for (unsigned int i = 0; i < outputs.size(); ++i)
telsoa01c577f2c2018-08-31 09:22:23 +01003592 {
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003593 auto const output = outputs[i];
telsoa01c577f2c2018-08-31 09:22:23 +01003594 if (output.second->name == name)
3595 {
3596 auto bindingId = GenerateLayerBindingId(subgraphId, output.first);
Narumol Prangnawarat4628d052019-02-25 17:26:05 +00003597 std::vector<unsigned int> shape = m_OverridenOutputShapes.size() > 0 ?
3598 m_OverridenOutputShapes[i] : AsUnsignedVector(output.second->shape);
3599 return std::make_pair(bindingId, ToTensorInfo(output.second, shape));
telsoa01c577f2c2018-08-31 09:22:23 +01003600 }
3601 }
3602
3603 std::stringstream bindings;
3604 for (auto const & output : outputs)
3605 {
3606 bindings << "'" << output.second->name << "' ";
3607 }
3608
3609 throw ParseException(
James Ward58dec6b2020-09-11 17:32:44 +01003610 fmt::format("No output binding found for subgraph:{} and name:{}. "
3611 "Possible outputs are: [{}] {}",
3612 subgraphId,
3613 name,
3614 bindings.str(),
3615 CHECK_LOCATION().AsString()));
telsoa01c577f2c2018-08-31 09:22:23 +01003616}
3617
Kevin May7d96b162021-02-03 17:38:41 +00003618size_t TfLiteParserImpl::GetSubgraphCount() const
telsoa01c577f2c2018-08-31 09:22:23 +01003619{
3620 return m_Model->subgraphs.size();
3621}
3622
Kevin May7d96b162021-02-03 17:38:41 +00003623std::vector<std::string> TfLiteParserImpl::GetSubgraphInputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01003624{
3625 CHECK_SUBGRAPH(m_Model, subgraphId);
3626 auto inputs = GetSubgraphInputs(m_Model, subgraphId);
3627 std::vector<std::string> result;
3628 result.reserve(inputs.size());
3629 for (auto const & input : inputs)
3630 {
3631 result.push_back(input.second->name);
3632 }
3633 return result;
3634}
3635
Kevin May7d96b162021-02-03 17:38:41 +00003636std::vector<std::string> TfLiteParserImpl::GetSubgraphOutputTensorNames(size_t subgraphId) const
telsoa01c577f2c2018-08-31 09:22:23 +01003637{
3638 CHECK_SUBGRAPH(m_Model, subgraphId);
3639 auto outputs = GetSubgraphOutputs(m_Model, subgraphId);
3640 std::vector<std::string> result;
3641 result.reserve(outputs.size());
3642 for (auto const & output : outputs)
3643 {
3644 result.push_back(output.second->name);
3645 }
3646 return result;
3647}
3648
Matthew Sloyanac001ee2021-02-03 10:43:04 +00003649const std::string TfLiteParserImpl::GetVersion()
3650{
3651 return TFLITE_PARSER_VERSION;
3652}
3653
Kevin May7d96b162021-02-03 17:38:41 +00003654TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<float[]> && data)
telsoa01c577f2c2018-08-31 09:22:23 +01003655: m_FloatData(std::move(data))
3656, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00003657, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01003658, m_Int32Data(nullptr)
3659{
3660}
3661
Kevin May7d96b162021-02-03 17:38:41 +00003662TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<uint8_t[]> && data)
telsoa01c577f2c2018-08-31 09:22:23 +01003663: m_FloatData(nullptr)
3664, m_Uint8Data(std::move(data))
Keith Davisd305e1a2020-01-22 11:57:54 +00003665, m_Int8Data(nullptr)
3666, m_Int32Data(nullptr)
3667{
3668}
3669
Kevin May7d96b162021-02-03 17:38:41 +00003670TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int8_t[]> && data)
Keith Davisd305e1a2020-01-22 11:57:54 +00003671: m_FloatData(nullptr)
3672, m_Uint8Data(nullptr)
3673, m_Int8Data(std::move(data))
telsoa01c577f2c2018-08-31 09:22:23 +01003674, m_Int32Data(nullptr)
3675{
3676}
3677
Kevin May7d96b162021-02-03 17:38:41 +00003678TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int32_t[]> && data)
telsoa01c577f2c2018-08-31 09:22:23 +01003679: m_FloatData(nullptr)
3680, m_Uint8Data(nullptr)
Keith Davisd305e1a2020-01-22 11:57:54 +00003681, m_Int8Data(nullptr)
telsoa01c577f2c2018-08-31 09:22:23 +01003682, m_Int32Data(std::move(data))
3683{
3684}
3685
3686} // armnnTfLiteParser