29 #include <schema_generated.h> 31 #include <flatbuffers/flexbuffers.h> 33 #include <fmt/format.h> 42 #define ARMNN_THROW_PARSE_EXCEPTION(msg) \ 44 throw armnn::ParseException( static_cast<const std::stringstream&>( std::stringstream() << msg \ 46 << CHECK_LOCATION().AsString()).str()); \ 49 using namespace armnn;
55 pTfLiteParserImpl(
new TfLiteParserImpl(options)) {}
57 ITfLiteParser::~ITfLiteParser() =
default;
79 armnn::INetworkPtr ITfLiteParser::CreateNetworkFromBinary(
const std::vector<uint8_t> & binaryContent)
81 return pTfLiteParserImpl->CreateNetworkFromBinary(binaryContent);
85 const std::string& name)
const 87 return pTfLiteParserImpl->GetNetworkInputBindingInfo(subgraphId, name);
91 const std::string& name)
const 93 return pTfLiteParserImpl->GetNetworkOutputBindingInfo(subgraphId, name);
96 size_t ITfLiteParser::GetSubgraphCount()
const 98 return pTfLiteParserImpl->GetSubgraphCount();
101 std::vector<std::string> ITfLiteParser::GetSubgraphInputTensorNames(
size_t subgraphId)
const 103 return pTfLiteParserImpl->GetSubgraphInputTensorNames(subgraphId);
106 std::vector<std::string> ITfLiteParser::GetSubgraphOutputTensorNames(
size_t subgraphId)
const 108 return pTfLiteParserImpl->GetSubgraphOutputTensorNames(subgraphId);
114 const uint32_t VIRTUAL_OPERATOR_ID = std::numeric_limits<uint32_t>::max();
117 size_t subgraphIndex,
120 if (model.get() ==
nullptr)
123 fmt::format(
"{} was called with invalid (null) model. " 124 "Possible reason is that the model is not yet loaded and Unpack(ed). " 130 else if (subgraphIndex >= model->subgraphs.size())
133 fmt::format(
"{} was called with an invalid subgraph index. " 141 #define CHECK_SUBGRAPH(MODEL, SUBGRAPH_INDEX) \ 142 CheckSubgraph(MODEL, SUBGRAPH_INDEX, CHECK_LOCATION()) 145 size_t subgraphIndex,
146 size_t operatorIndex,
149 if (model.get() ==
nullptr)
152 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 {}",
160 else if (subgraphIndex >= model->subgraphs.size())
163 fmt::format(
"{} was called with an invalid subgraph index. " 164 "subgraph:{} operator:{} at {}",
170 else if (operatorIndex >= model->subgraphs[subgraphIndex]->operators.size() &&
171 operatorIndex != VIRTUAL_OPERATOR_ID)
174 fmt::format(
"{} was called with an invalid operator index. " 175 "subgraph:{} operator:{} at {}",
183 #define CHECK_MODEL(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX) \ 184 CheckModel(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX, CHECK_LOCATION()) 187 size_t subgraphIndex,
193 ARMNN_ASSERT_MSG(model.get() !=
nullptr,
"Expecting a valid model in this function");
197 ARMNN_ASSERT_MSG(subgraphIndex < model->subgraphs.size(),
"Expecting a valid subgraph index");
200 if (tensorIndex >= model->subgraphs[subgraphIndex]->tensors.size())
203 fmt::format(
"{} was called with an invalid tensor index. " 204 "subgraph:{} tensor:{} at {}",
212 #define CHECK_TENSOR(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX) \ 213 CheckTensor(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX, CHECK_LOCATION()) 218 if (rawPtr ==
nullptr)
221 fmt::format(
"{} was called with a null tensor pointer at {}", location.
m_Function, location.
FileLine()));
225 #define CHECK_TENSOR_PTR(TENSOR_PTR) \ 226 CheckTensorPtr(TENSOR_PTR, CHECK_LOCATION()) 232 if (model.get() ==
nullptr)
235 fmt::format(
"{} was called with invalid (null) model. " 236 "Possible reason is that the model is not yet loaded and Unpack(ed). " 242 else if (bufferIndex >= model->buffers.size())
245 fmt::format(
"{} was called with an invalid buffer index. " 246 "buffer index:{} at {}",
251 else if (model->buffers[bufferIndex].get() ==
nullptr)
254 fmt::format(
"The buffer #{} is null. {}",
260 #define CHECK_BUFFER(MODEL, BUFFER_INDEX) \ 261 CheckBuffer(MODEL, BUFFER_INDEX, CHECK_LOCATION()) 263 void CheckBufferSize(TfLiteParserImpl::BufferRawPtr bufferPtr,
268 if (bufferPtr ==
nullptr)
271 fmt::format(
"BufferPtr is null for buffer:{}. {}",
278 std::stringstream ss;
279 ss <<
"Buffer #" << bufferId <<
" has " << bufferPtr->data.size() <<
" bytes. " 280 <<
"For tensor: " << tensorInfo.
GetShape()
281 <<
" expecting: " << tensorInfo.
GetNumBytes() <<
" bytes and " 287 #define CHECK_BUFFER_SIZE(BUFFER_PTR, TENSOR_INFO, BUFFER_ID) \ 288 CheckBufferSize(BUFFER_PTR, TENSOR_INFO, BUFFER_ID, CHECK_LOCATION()) 292 switch(activationType)
294 case tflite::ActivationFunctionType_NONE:
295 case tflite::ActivationFunctionType_RELU:
296 case tflite::ActivationFunctionType_RELU6:
297 case tflite::ActivationFunctionType_TANH:
308 #define CHECK_SUPPORTED_FUSED_ACTIVATION(OPTION, SUBGRAPH_INDEX, OPERATOR_INDEX) \ 310 if (IsActivationSupported(OPTION->fused_activation_function) == false) \ 312 throw ParseException( \ 313 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), \ 321 CHECK_LOCATION().FileLine())); \ 326 std::vector<unsigned int> AsUnsignedVector(
const std::vector<int32_t> & in)
328 std::vector<unsigned int> result;
329 result.reserve(in.size());
342 void CalcPadding(uint32_t inputSize,
346 uint32_t& paddingFront,
347 uint32_t& paddingBack,
348 tflite::Padding padding)
352 if (padding == tflite::Padding_SAME)
354 uint32_t outputSize = (inputSize + stride - 1) / stride;
355 uint32_t dilatedSize = filterSize + (dilation - 1) * (filterSize - 1);
356 uint32_t temp = (outputSize - 1) * stride + dilatedSize;
357 if (temp > inputSize)
359 paddingFront = (temp - inputSize) / 2;
360 paddingBack = (temp - inputSize) - paddingFront;
366 const std::vector<unsigned int>& shape,
367 const bool outputTensor =
false)
372 switch (tensorPtr->type)
374 case tflite::TensorType_UINT8:
377 case tflite::TensorType_FLOAT32:
380 case tflite::TensorType_INT8:
381 if (tensorPtr->quantization->zero_point.size() == 1)
392 case tflite::TensorType_INT16:
395 case tflite::TensorType_INT32:
398 case tflite::TensorType_INT64:
401 case tflite::TensorType_BOOL:
408 fmt::format(
"Unsupported data type {} = {} for tensor: {}. {}",
410 tflite::EnumNameTensorType(tensorPtr->type),
417 std::vector<unsigned int> safeShape = shape;
418 if (shape.size() == 0)
420 safeShape.push_back(1);
425 tensorShape =
TensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()), safeShape.data());
429 size_t shapeSignatureSize = tensorPtr->shape_signature.size();
432 if (shapeSignatureSize != 0)
435 if (shapeSignatureSize != shape.size())
439 for (
unsigned int i = 0; i < shapeSignatureSize; ++i)
441 unsigned int dim = tensorPtr->shape_signature[i] > -1 ?
442 static_cast<unsigned int>(tensorPtr->shape_signature[i]) : 0;
443 safeShape.push_back(dim);
447 std::unique_ptr<bool[]> dimMask = std::make_unique<bool[]>(tensorPtr->shape_signature.size());
448 for (
unsigned int i = 0; i < tensorPtr->shape_signature.size(); ++i)
450 dimMask[i] = tensorPtr->shape_signature[i] == -1 ? false :
true;
452 tensorShape =
TensorShape(static_cast<unsigned int>(safeShape.size()), safeShape.data(), dimMask.get());
455 else if (shape.size() == 0)
461 tensorShape =
TensorShape(armnn::numeric_cast<unsigned int>(shape.size()), shape.data());
465 float quantizationScale = 0.0f;
466 int32_t quantizationOffset = 0;
468 if (tensorPtr->quantization.get())
470 if (tensorPtr->quantization->scale.size() <= 1)
475 if (tensorPtr->quantization->scale.size() == 1)
477 quantizationScale = tensorPtr->quantization->scale[0];
479 if (tensorPtr->quantization->zero_point.size() == 1)
494 std::vector<float> quantizationScales;
495 std::vector<int32_t> quantizationOffsets;
498 std::copy(tensorPtr->quantization->scale.begin(),
499 tensorPtr->quantization->scale.end(),
500 std::back_inserter(quantizationScales));
506 armnn::numeric_cast<unsigned int>(tensorPtr->quantization->quantized_dimension));
522 auto const & dimensions = AsUnsignedVector(tensorPtr->shape);
527 const bool outputTensor)
529 auto const & dimensions = AsUnsignedVector(tensorPtr->shape);
530 return ToTensorInfo(tensorPtr, dimensions, outputTensor);
534 std::pair<armnn::ConstTensor, std::unique_ptr<T[]>>
543 fmt::format(
"Buffer for buffer:{} is null", tensorPtr->buffer).c_str());
551 reinterpret_cast<const T*
>(bufferPtr->data.data()), data.get(),
sizeof(T));
555 ::memcpy(data.get(), bufferPtr->data.data(), tensorInfo.
GetNumBytes());
561 return std::make_pair(
ConstTensor(tensorInfo, data.get()), std::move(data));
574 if (actualSize != expected.size())
579 for (
unsigned int i = 0u; i < actualSize; i++)
581 if (expected[i] < 0 ||
582 actual[i] != static_cast<unsigned int>(expected[i]))
591 void CheckMatchingQuantization(
const TensorInfo& first,
593 const std::string& descName,
594 std::string
const& firstName,
595 std::string
const& secondName)
607 if (firstDataType != secondDataType)
610 " must be of the same quantized type, " +
618 " must have the same quantization space, " +
630 , m_Network(nullptr, nullptr)
634 m_ParserFunctions[tflite::BuiltinOperator_ABS] = &TfLiteParserImpl::ParseAbs;
635 m_ParserFunctions[tflite::BuiltinOperator_ADD] = &TfLiteParserImpl::ParseAdd;
636 m_ParserFunctions[tflite::BuiltinOperator_ARG_MIN] = &TfLiteParserImpl::ParseArgMin;
637 m_ParserFunctions[tflite::BuiltinOperator_ARG_MAX] = &TfLiteParserImpl::ParseArgMax;
638 m_ParserFunctions[tflite::BuiltinOperator_AVERAGE_POOL_2D] = &TfLiteParserImpl::ParseAveragePool2D;
639 m_ParserFunctions[tflite::BuiltinOperator_BATCH_TO_SPACE_ND] = &TfLiteParserImpl::ParseBatchToSpaceND;
640 m_ParserFunctions[tflite::BuiltinOperator_CAST] = &TfLiteParserImpl::ParseCast;
641 m_ParserFunctions[tflite::BuiltinOperator_CONCATENATION] = &TfLiteParserImpl::ParseConcatenation;
642 m_ParserFunctions[tflite::BuiltinOperator_CONV_2D] = &TfLiteParserImpl::ParseConv2D;
644 #if defined(ARMNN_POST_TFLITE_2_3) 645 m_ParserFunctions[tflite::BuiltinOperator_CONV_3D] = &TfLiteParserImpl::ParseConv3D;
647 m_ParserFunctions[tflite::BuiltinOperator_CUSTOM] = &TfLiteParserImpl::ParseCustomOperator;
648 m_ParserFunctions[tflite::BuiltinOperator_DEPTH_TO_SPACE] = &TfLiteParserImpl::ParseDepthToSpace;
649 m_ParserFunctions[tflite::BuiltinOperator_DEPTHWISE_CONV_2D] = &TfLiteParserImpl::ParseDepthwiseConv2D;
650 m_ParserFunctions[tflite::BuiltinOperator_DEQUANTIZE] = &TfLiteParserImpl::ParseDequantize;
651 m_ParserFunctions[tflite::BuiltinOperator_DIV] = &TfLiteParserImpl::ParseDiv;
652 m_ParserFunctions[tflite::BuiltinOperator_ELU] = &TfLiteParserImpl::ParseElu;
653 m_ParserFunctions[tflite::BuiltinOperator_EQUAL] = &TfLiteParserImpl::ParseEqual;
654 m_ParserFunctions[tflite::BuiltinOperator_EXP] = &TfLiteParserImpl::ParseExp;
655 m_ParserFunctions[tflite::BuiltinOperator_EXPAND_DIMS] = &TfLiteParserImpl::ParseExpandDims;
656 m_ParserFunctions[tflite::BuiltinOperator_FULLY_CONNECTED] = &TfLiteParserImpl::ParseFullyConnected;
657 m_ParserFunctions[tflite::BuiltinOperator_GATHER] = &TfLiteParserImpl::ParseGather;
658 m_ParserFunctions[tflite::BuiltinOperator_GREATER] = &TfLiteParserImpl::ParseGreater;
659 m_ParserFunctions[tflite::BuiltinOperator_GREATER_EQUAL] = &TfLiteParserImpl::ParseGreaterOrEqual;
660 m_ParserFunctions[tflite::BuiltinOperator_HARD_SWISH] = &TfLiteParserImpl::ParseHardSwish;
661 m_ParserFunctions[tflite::BuiltinOperator_LEAKY_RELU] = &TfLiteParserImpl::ParseLeakyRelu;
662 m_ParserFunctions[tflite::BuiltinOperator_LESS] = &TfLiteParserImpl::ParseLess;
663 m_ParserFunctions[tflite::BuiltinOperator_LESS_EQUAL] = &TfLiteParserImpl::ParseLessOrEqual;
664 m_ParserFunctions[tflite::BuiltinOperator_LOCAL_RESPONSE_NORMALIZATION]
665 = &TfLiteParserImpl::ParseLocalResponseNormalization;
666 m_ParserFunctions[tflite::BuiltinOperator_LOGICAL_NOT] = &TfLiteParserImpl::ParseLogicalNot;
667 m_ParserFunctions[tflite::BuiltinOperator_LOGISTIC] = &TfLiteParserImpl::ParseLogistic;
668 m_ParserFunctions[tflite::BuiltinOperator_L2_NORMALIZATION] = &TfLiteParserImpl::ParseL2Normalization;
669 m_ParserFunctions[tflite::BuiltinOperator_MAX_POOL_2D] = &TfLiteParserImpl::ParseMaxPool2D;
670 m_ParserFunctions[tflite::BuiltinOperator_MAXIMUM] = &TfLiteParserImpl::ParseMaximum;
671 m_ParserFunctions[tflite::BuiltinOperator_MEAN] = &TfLiteParserImpl::ParseMean;
672 m_ParserFunctions[tflite::BuiltinOperator_MINIMUM] = &TfLiteParserImpl::ParseMinimum;
673 m_ParserFunctions[tflite::BuiltinOperator_MIRROR_PAD] = &TfLiteParserImpl::ParseMirrorPad;
674 m_ParserFunctions[tflite::BuiltinOperator_MUL] = &TfLiteParserImpl::ParseMul;
675 m_ParserFunctions[tflite::BuiltinOperator_NEG] = &TfLiteParserImpl::ParseNeg;
676 m_ParserFunctions[tflite::BuiltinOperator_NOT_EQUAL] = &TfLiteParserImpl::ParseNotEqual;
677 m_ParserFunctions[tflite::BuiltinOperator_PACK] = &TfLiteParserImpl::ParsePack;
678 m_ParserFunctions[tflite::BuiltinOperator_PAD] = &TfLiteParserImpl::ParsePad;
679 m_ParserFunctions[tflite::BuiltinOperator_PRELU] = &TfLiteParserImpl::ParsePrelu;
680 m_ParserFunctions[tflite::BuiltinOperator_QUANTIZE] = &TfLiteParserImpl::ParseQuantize;
681 m_ParserFunctions[tflite::BuiltinOperator_RELU] = &TfLiteParserImpl::ParseRelu;
682 m_ParserFunctions[tflite::BuiltinOperator_RELU6] = &TfLiteParserImpl::ParseRelu6;
683 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MAX] = &TfLiteParserImpl::ParseReduceMax;
684 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MIN] = &TfLiteParserImpl::ParseReduceMin;
685 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_PROD] = &TfLiteParserImpl::ParseReduceProd;
686 m_ParserFunctions[tflite::BuiltinOperator_RESHAPE] = &TfLiteParserImpl::ParseReshape;
687 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_BILINEAR] = &TfLiteParserImpl::ParseResizeBilinear;
688 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_NEAREST_NEIGHBOR] = &TfLiteParserImpl::ParseResizeNearestNeighbor;
689 m_ParserFunctions[tflite::BuiltinOperator_RSQRT] = &TfLiteParserImpl::ParseRsqrt;
690 m_ParserFunctions[tflite::BuiltinOperator_SHAPE] = &TfLiteParserImpl::ParseShape;
691 m_ParserFunctions[tflite::BuiltinOperator_SLICE] = &TfLiteParserImpl::ParseSlice;
692 m_ParserFunctions[tflite::BuiltinOperator_SOFTMAX] = &TfLiteParserImpl::ParseSoftmax;
693 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_BATCH_ND] = &TfLiteParserImpl::ParseSpaceToBatchND;
694 m_ParserFunctions[tflite::BuiltinOperator_SPLIT] = &TfLiteParserImpl::ParseSplit;
695 m_ParserFunctions[tflite::BuiltinOperator_SPLIT_V] = &TfLiteParserImpl::ParseSplitV;
696 m_ParserFunctions[tflite::BuiltinOperator_SQUEEZE] = &TfLiteParserImpl::ParseSqueeze;
697 m_ParserFunctions[tflite::BuiltinOperator_STRIDED_SLICE] = &TfLiteParserImpl::ParseStridedSlice;
698 m_ParserFunctions[tflite::BuiltinOperator_SUB] = &TfLiteParserImpl::ParseSub;
699 m_ParserFunctions[tflite::BuiltinOperator_SUM] = &TfLiteParserImpl::ParseSum;
700 m_ParserFunctions[tflite::BuiltinOperator_TANH] = &TfLiteParserImpl::ParseTanH;
701 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE] = &TfLiteParserImpl::ParseTranspose;
702 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE_CONV] = &TfLiteParserImpl::ParseTransposeConv;
703 m_ParserFunctions[tflite::BuiltinOperator_UNPACK] = &TfLiteParserImpl::ParseUnpack;
706 m_CustomParserFunctions[
"TFLite_Detection_PostProcess"] = &TfLiteParserImpl::ParseDetectionPostProcess;
709 void TfLiteParserImpl::ResetParser()
713 m_SubgraphConnections.clear();
720 return CreateNetworkFromModel();
727 return CreateNetworkFromModel();
734 m_Model = std::move(model);
736 return CreateNetworkFromModel();
739 INetworkPtr TfLiteParserImpl::CreateNetworkFromModel()
744 if (m_Options && m_Options.value().m_InferAndValidate)
748 {
"InferAndValidate",
true }
751 networkOptions.push_back(shapeInferenceMethodOption);
754 m_Network = INetwork::Create(networkOptions);
757 if (m_Model->subgraphs.size() != 1)
760 fmt::format(
"Current TfLite parser only supports 1 subgraph. Current one has: {} {}",
761 m_Model->subgraphs.size(),
765 size_t subgraphIndex = 0;
766 size_t operatorIndex = 0;
769 for (
SubgraphPtr const& subgraph : m_Model->subgraphs)
771 m_SubgraphConnections.emplace_back(subgraph->tensors.size());
774 auto const& opCodePtr = m_Model->operator_codes[op->opcode_index];
777 #if defined(ARMNN_POST_TFLITE_2_3) 778 auto builtinCode = std::max(opCodePtr->builtin_code,
779 static_cast<tflite::BuiltinOperator>(opCodePtr->deprecated_builtin_code));
781 auto builtinCode = opCodePtr->builtin_code;
784 if (builtinCode > tflite::BuiltinOperator_MAX)
786 throw ParseException(fmt::format(
"Operator code {} is out of range 0-{}. " 787 "subgraph:{} operator idx:{}. {}",
788 builtinCode, tflite::BuiltinOperator_MAX, subgraphIndex,
793 auto& parserFunction = m_ParserFunctions[builtinCode];
794 (this->*parserFunction)(subgraphIndex, operatorIndex);
798 SetupInputLayers(subgraphIndex);
799 SetupOutputLayers(subgraphIndex);
800 SetupConstantLayers(subgraphIndex);
808 std::stringstream errorString;
809 errorString <<
"Failed to parse operator #" << operatorIndex <<
" within subgraph #" 810 << subgraphIndex <<
" error: " << e.
what();
812 std::stringstream errors;
813 errors << errorString.str() <<
"\n";
818 for (subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
820 for (
size_t tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
822 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot !=
nullptr)
824 for (
size_t inputSlotIdx = 0;
825 inputSlotIdx < m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size();
828 m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot->Connect(
829 *(m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots[inputSlotIdx]));
835 return std::move(m_Network);
838 void TfLiteParserImpl::RegisterProducerOfTensor(
size_t subgraphIndex,
843 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
844 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
846 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
849 if (tensorSlots.outputSlot !=
nullptr)
851 throw ParseException(fmt::format(
"Another layer has already registered itself as the producer of " 852 "subgraph:{} tensor:{} {}",
858 tensorSlots.outputSlot = slot;
861 void TfLiteParserImpl::RegisterConsumerOfTensor(
size_t subgraphIndex,
866 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
867 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
869 TensorSlots& tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
870 tensorSlots.inputSlots.push_back(slot);
873 void TfLiteParserImpl::ParseCustomOperator(
size_t subgraphIndex,
size_t operatorIndex)
875 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
878 auto customParserFunction = &TfLiteParserImpl::ParseUnsupportedOperator;
881 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
882 const auto& customCode = m_Model->operator_codes[operatorPtr->opcode_index]->custom_code;
885 auto iterator = m_CustomParserFunctions.find(customCode);
886 if (iterator != m_CustomParserFunctions.end())
888 customParserFunction = iterator->second;
892 (this->*customParserFunction)(subgraphIndex, operatorIndex);
895 void TfLiteParserImpl::ParseUnsupportedOperator(
size_t subgraphIndex,
size_t operatorIndex)
897 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
899 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
901 auto opcodeIndex = operatorPtr->opcode_index;
904 #if defined(ARMNN_POST_TFLITE_2_3) 905 auto opcode = std::max(m_Model->operator_codes[opcodeIndex]->builtin_code,
906 static_cast<tflite::BuiltinOperator>(m_Model->operator_codes[opcodeIndex]->deprecated_builtin_code));
908 auto opcode = m_Model->operator_codes[opcodeIndex]->builtin_code;
911 if (!m_Options || !m_Options.value().m_StandInLayerForUnsupported)
915 fmt::format(
"Operator not supported. " 916 "subgraph:{} operator:{} " 917 "opcode_index:{} opcode:{} / {} {}",
922 tflite::EnumNameBuiltinOperator(opcode),
926 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
927 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
933 auto layerName = fmt::format(
"StandIn:{}:{}:{}", subgraphIndex, operatorIndex, opcode);
936 IConnectableLayer* layer = m_Network->AddStandInLayer(descriptor, layerName.c_str());
939 for (
unsigned int i = 0u; i < numOutputs; ++i)
944 auto inputTensorIds = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
945 auto outputTensorIds = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
947 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIds);
948 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIds);
951 void TfLiteParserImpl::ParseCast(
size_t subgraphIndex,
size_t operatorIndex)
953 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
955 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
957 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
960 auto layerName = fmt::format(
"Cast:{}:{}", subgraphIndex, operatorIndex);
968 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
969 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
971 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
972 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
975 void TfLiteParserImpl::ParseConv2D(
size_t subgraphIndex,
size_t operatorIndex)
977 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
979 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
980 const auto * options = operatorPtr->builtin_options.AsConv2DOptions();
992 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
995 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1002 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1003 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1007 unsigned int filterHeight = filterTensorInfo.
GetShape()[1];
1008 unsigned int filterWidth = filterTensorInfo.
GetShape()[2];
1010 CalcPadding(inputHeight, filterHeight, desc.
m_StrideY,
1012 CalcPadding(inputWidth, filterWidth, desc.
m_StrideX,
1015 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
1018 auto layerName = fmt::format(
"Conv2D:{}:{}", subgraphIndex, operatorIndex);
1020 if (inputs.size() == 3)
1024 auto biasTensorAndData = CreateConstTensorNonPermuted(inputs[2], biasTensorInfo);
1025 layer = m_Network->AddConvolution2dLayer(desc,
1026 filterTensorAndData,
1032 layer = m_Network->AddConvolution2dLayer(desc,
1033 filterTensorAndData,
1045 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1046 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1048 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1050 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1051 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1055 #if defined(ARMNN_POST_TFLITE_2_3) 1056 void TfLiteParserImpl::ParseConv3D(
size_t subgraphIndex,
size_t operatorIndex)
1058 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1060 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1061 const auto* options = operatorPtr->builtin_options.AsConv3DOptions();
1075 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1078 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1085 unsigned int inputDepth = inputTensorInfo.GetShape()[1];
1086 unsigned int inputHeight = inputTensorInfo.GetShape()[2];
1087 unsigned int inputWidth = inputTensorInfo.GetShape()[3];
1090 unsigned int filterDepth = filterTensorInfo.
GetShape()[0];
1091 unsigned int filterHeight = filterTensorInfo.
GetShape()[1];
1092 unsigned int filterWidth = filterTensorInfo.
GetShape()[2];
1094 CalcPadding(inputDepth, filterDepth, desc.
m_StrideZ,
1096 CalcPadding(inputHeight, filterHeight, desc.
m_StrideY,
1098 CalcPadding(inputWidth, filterWidth, desc.
m_StrideX,
1101 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
1103 auto layerName = fmt::format(
"Conv3D:{}:{}", subgraphIndex, operatorIndex);
1105 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1108 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1110 if (inputs.size() == 3)
1115 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
1125 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
1127 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1129 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1130 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1134 void TfLiteParserImpl::ParseDepthwiseConv2D(
size_t subgraphIndex,
size_t operatorIndex)
1136 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1138 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1139 const auto * options = operatorPtr->builtin_options.AsDepthwiseConv2DOptions();
1150 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1152 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1161 unsigned int inputHeight = inputTensorInfo.
GetShape()[1];
1162 unsigned int inputWidth = inputTensorInfo.
GetShape()[2];
1165 unsigned int filterHeight = filterTensorInfo.
GetShape()[1];
1166 unsigned int filterWidth = filterTensorInfo.
GetShape()[2];
1168 CalcPadding(inputHeight, filterHeight, desc.
m_StrideY,
1170 CalcPadding(inputWidth, filterWidth, desc.
m_StrideX,
1174 auto filterTensor = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
1176 auto layerName = fmt::format(
"DepthwiseConv2D:{}:{}", subgraphIndex, operatorIndex);
1178 if (inputs.size() == 3)
1182 auto biasTensorAndData = CreateConstTensorNonPermuted(inputs[2], biasTensorInfo);
1183 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
1190 layer = m_Network->AddDepthwiseConvolution2dLayer(desc,
1202 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1203 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1205 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1207 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1208 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1211 void TfLiteParserImpl::ParseDequantize(
size_t subgraphIndex,
size_t operatorIndex)
1213 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1215 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1218 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1221 auto layerName = fmt::format(
"Dequantize:{}:{}", subgraphIndex, operatorIndex);
1229 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1230 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1232 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1233 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1236 void TfLiteParserImpl::ParseExpandDims(
size_t subgraphIndex,
size_t operatorIndex)
1238 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1240 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1243 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1246 auto layerName = fmt::format(
"ExpandDims:{}:{}", subgraphIndex, operatorIndex);
1251 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1261 int32_t axis = inputs[1]->shape[0];
1265 if (axis > inputDimSize || axis < 0 - (inputDimSize + 1))
1267 throw ParseException(
"axis must be in range [0 - (inputDimSize + 1), inputDimSize] inclusive");
1272 axis = inputDimSize + axis + 1;
1275 std::vector<unsigned int> shape(static_cast<unsigned int>(inputDimSize) + 1);
1276 unsigned int inputShapeIndex = 0;
1277 for (
unsigned int i = 0; i < static_cast<unsigned int>(inputDimSize + 1); ++i)
1279 if (i == static_cast<unsigned int>(axis))
1285 shape[i] = inputTensorInfo.
GetShape()[inputShapeIndex];
1293 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
1295 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1297 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1298 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1300 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1301 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1304 void TfLiteParserImpl::ParseTranspose(
size_t subgraphIndex,
size_t operatorIndex)
1306 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1308 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1311 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1314 auto layerName = fmt::format(
"Transpose:{}:{}", subgraphIndex, operatorIndex);
1317 if (inputs.size() == 2)
1322 std::vector<unsigned int> permuteShape(numPermVecElements);
1323 ::memcpy(permuteShape.data(), permuteBufferPtr->data.data(), permuteTensorInfo.
GetNumBytes());
1331 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1333 IConnectableLayer* layer = m_Network->AddTransposeLayer(desc, layerName.c_str());
1337 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1338 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1340 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1341 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1344 void TfLiteParserImpl::ParseTransposeConv(
size_t subgraphIndex,
size_t operatorIndex)
1346 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1348 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1349 const auto * options = operatorPtr->builtin_options.AsTransposeConvOptions();
1357 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1358 if (inputs.size() == 4)
1367 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1374 if (tensorInfo.
GetDataType() == DataType::Signed32)
1376 ::memcpy(output_shape.data(),
GetBuffer(m_Model, inputs[0]->buffer)->data.data(), tensorInfo.
GetNumBytes());
1378 if (tensorInfo.
GetDataType() == DataType::QAsymmU8)
1382 output_shape[i] =
GetBuffer(m_Model, inputs[0]->buffer)->data.data()[i];
1386 for (
int dimension : output_shape)
1388 desc.
m_OutputShape.push_back(static_cast<unsigned int>(dimension));
1396 const unsigned int inputHeight = inputTensorInfo.
GetShape()[1];
1397 const unsigned int inputWidth = inputTensorInfo.
GetShape()[2];
1399 const unsigned int filterHeight = filterTensorInfo.
GetShape()[1];
1400 const unsigned int filterWidth = filterTensorInfo.
GetShape()[2];
1402 CalcPadding(inputHeight,
1410 CalcPadding(inputWidth,
1418 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo);
1421 auto layerName = fmt::format(
"TransposeConv:{}:{}", subgraphIndex, operatorIndex);
1426 auto biasConstTensor = CreateConstTensorNonPermuted(inputs[3], biasTensorInfo);
1427 layer = m_Network->AddTransposeConvolution2dLayer(desc,
1428 filterTensorAndData,
1434 layer = m_Network->AddTransposeConvolution2dLayer(desc,
1435 filterTensorAndData,
1446 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1447 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[2]});
1449 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1450 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1453 void TfLiteParserImpl::ParseAveragePool2D(
size_t subgraphIndex,
size_t operatorIndex)
1455 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Average);
1458 void TfLiteParserImpl::ParseBatchToSpaceND(
size_t subgraphIndex,
size_t operatorIndex)
1460 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1462 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1465 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1474 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1475 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1477 std::vector<unsigned int> cropsVector(cropsTensorInfo.
GetNumElements());
1478 ::memcpy(cropsVector.data(), cropsBufferPtr->data.data(), cropsTensorInfo.
GetNumBytes());
1481 std::vector<std::pair<unsigned int, unsigned int>> crops;
1482 for (
unsigned int i = 0; i < cropsTensorInfo.
GetNumElements() / step; ++i)
1484 crops.emplace_back(cropsVector[i * step], cropsVector[i * step + 1]);
1492 auto layerName = fmt::format(
"BatchToSpaceND:{}:{}", subgraphIndex, operatorIndex);
1496 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1498 IConnectableLayer* layer = m_Network->AddBatchToSpaceNdLayer(desc, layerName.c_str());
1502 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1503 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1505 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1506 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1509 void TfLiteParserImpl::ParseL2Normalization(
size_t subgraphIndex,
size_t operatorIndex)
1511 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1513 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1516 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1521 auto layerName = fmt::format(
"L2Normalization:{}:{}", subgraphIndex, operatorIndex);
1522 IConnectableLayer* layer = m_Network->AddL2NormalizationLayer(desc, layerName.c_str());
1529 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1530 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1532 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1533 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1536 void TfLiteParserImpl::ParseMaxPool2D(
size_t subgraphIndex,
size_t operatorIndex)
1538 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Max);
1541 void TfLiteParserImpl::ParseMaximum(
size_t subgraphIndex,
size_t operatorIndex)
1543 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1545 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1548 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1551 auto layerName = fmt::format(
"Maximum:{}:{}", subgraphIndex, operatorIndex);
1555 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName,
"Input 0",
"Input 1");
1558 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1564 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1565 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1567 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1568 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1571 void TfLiteParserImpl::ParseMinimum(
size_t subgraphIndex,
size_t operatorIndex)
1573 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1575 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1578 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1581 auto layerName = fmt::format(
"Minimum:{}:{}", subgraphIndex, operatorIndex);
1585 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName,
"Input 0",
"Input 1");
1588 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1594 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1595 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1597 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1598 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1601 void TfLiteParserImpl::ParsePool(
size_t subgraphIndex,
1602 size_t operatorIndex,
1605 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1607 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1608 const auto * options = operatorPtr->builtin_options.AsPool2DOptions();
1612 std::string layerName;
1616 case PoolingAlgorithm::Average:
1618 fmt::format(
"AveragePool2D:{}:{}", subgraphIndex, operatorIndex);
1620 case PoolingAlgorithm::Max:
1622 fmt::format(
"MaxPool2D:{}:{}", subgraphIndex, operatorIndex);
1639 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1644 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1645 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1652 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1656 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1658 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, layerName.c_str());
1664 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1665 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1667 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1669 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1670 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1673 void TfLiteParserImpl::ParseSlice(
size_t subgraphIndex,
size_t operatorIndex)
1675 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1677 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1679 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1688 std::vector<unsigned int> begin(beginTensorInfo.
GetNumElements());
1689 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.
GetNumBytes());
1695 std::vector<int> signedSize(sizeTensorInfo.GetNumElements());
1696 ::memcpy(signedSize.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
1697 std::vector<unsigned int> size(sizeTensorInfo.GetNumElements());
1700 for (
unsigned int i = 0; i < signedSize.size(); ++i)
1702 int signedValue = signedSize[i];
1704 if (signedValue < -1 || signedValue > static_cast<int>(inputTensorInfo.GetShape()[i] - begin[i]))
1706 throw ParseException(fmt::format(
"Invalid value for size {} size must be in range " 1707 "[-1, inputDimSize - begin] [-1, {}] inclusive {}",
1709 inputTensorInfo.GetShape()[i] - begin[i],
1713 if (signedValue == -1)
1715 size[i] = inputTensorInfo.GetShape()[i] - begin[i];
1719 size[i] =
static_cast<unsigned int>(signedValue);
1725 auto layerName = fmt::format(
"Slice:{}:{}", subgraphIndex, operatorIndex);
1728 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1730 IConnectableLayer*
const layer = m_Network->AddSliceLayer(desc, layerName.c_str());
1735 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1736 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1739 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1740 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1743 void TfLiteParserImpl::ParseSoftmax(
size_t subgraphIndex,
size_t operatorIndex)
1745 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1746 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1747 const auto * options = operatorPtr->builtin_options.AsSoftmaxOptions();
1750 desc.
m_Beta = options->beta;
1752 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1754 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1757 auto layerName = fmt::format(
"Softmax:{}:{}", subgraphIndex, operatorIndex);
1758 IConnectableLayer*
const layer = m_Network->AddSoftmaxLayer(desc, layerName.c_str());
1765 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1766 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1769 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1770 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1773 void TfLiteParserImpl::ParseSpaceToBatchND(
size_t subgraphIndex,
size_t operatorIndex)
1775 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1777 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1780 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1789 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1790 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1792 std::vector<unsigned int> padListVector(padListTensorInfo.
GetNumElements());
1793 ::memcpy(padListVector.data(), padListBufferPtr->data.data(), padListTensorInfo.
GetNumBytes());
1796 std::vector<std::pair<unsigned int, unsigned int>> padList;
1797 for (
unsigned int i = 0; i < padListTensorInfo.
GetNumElements() / step; ++i)
1799 padList.emplace_back(padListVector[i * step], padListVector[i * step + 1]);
1807 auto layerName = fmt::format(
"SpaceToBatchND:{}:{}", subgraphIndex, operatorIndex);
1811 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1813 IConnectableLayer* layer = m_Network->AddSpaceToBatchNdLayer(desc, layerName.c_str());
1817 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1818 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1820 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1821 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1828 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
1832 std::stringstream ss;
1833 ss <<
"Input tensor has unexpected number of dimensions:" << inputTensorInfo.
GetNumDimensions()
1834 <<
" shape:" << inputTensorInfo.
GetShape() <<
" " 1839 if (squeezeDims.empty())
1841 squeezeDims.assign(dimensionSequence,
1845 std::vector<uint32_t> outputDims;
1848 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
1849 auto currentDimension = inputTensorInfo.
GetShape()[i];
1850 if (skipSqueeze || currentDimension != 1)
1852 outputDims.push_back(currentDimension);
1856 if (outputDims.size() > 4)
1858 std::stringstream ss;
1859 ss <<
"Output tensor has unexpected number of dimensions:" << inputTensorInfo.
GetNumDimensions()
1860 <<
" shape:" << inputTensorInfo.
GetShape() <<
" " 1872 return outTensorInfo;
1875 void TfLiteParserImpl::ParseShape(
size_t subgraphIndex,
size_t operatorIndex)
1877 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1879 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1881 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1884 auto layerName = fmt::format(
"Shape:{}:{}", subgraphIndex, operatorIndex);
1899 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
1903 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1904 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1906 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1907 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1910 void TfLiteParserImpl::ParseSqueeze(
size_t subgraphIndex,
size_t operatorIndex)
1912 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1914 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1917 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1920 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1921 const auto * options = operatorPtr->builtin_options.AsSqueezeOptions();
1922 auto layerName = fmt::format(
"Squeeze:{}:{}", subgraphIndex, operatorIndex);
1926 std::vector<uint32_t> squeezeDim;
1929 if (options->squeeze_dims.size() == 1 && options->squeeze_dims[0] < 0)
1932 squeezeDim.push_back(static_cast<uint32_t>(dim));
1936 squeezeDim = AsUnsignedVector(options->squeeze_dims);
1941 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1946 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
1950 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1951 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1953 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1954 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1957 void TfLiteParserImpl::ParseStridedSlice(
size_t subgraphIndex,
size_t operatorIndex)
1959 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1961 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1964 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1967 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1968 const auto * options = operatorPtr->builtin_options.AsStridedSliceOptions();
1982 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.
GetNumBytes());
1987 std::vector<int> end(endTensorInfo.GetNumElements());
1988 ::memcpy(end.data(), endBufferPtr->data.data(), endTensorInfo.GetNumBytes());
1993 std::vector<int> stride(strideTensorInfo.GetNumElements());
1994 ::memcpy(stride.data(), strideBufferPtr->data.data(), strideTensorInfo.GetNumBytes());
2000 auto layerName = fmt::format(
"StridedSlice:{}:{}", subgraphIndex, operatorIndex);
2001 IConnectableLayer* layer = m_Network->AddStridedSliceLayer(desc, layerName.c_str());
2007 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2008 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2010 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2011 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2014 void TfLiteParserImpl::ParseSub(
size_t subgraphIndex,
size_t operatorIndex)
2016 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2018 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2019 const auto * options = operatorPtr->builtin_options.AsSubOptions();
2021 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2024 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2030 auto layerName = fmt::format(
"Sub:{}:{}", subgraphIndex, operatorIndex);
2037 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2038 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2040 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2042 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2043 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2046 void TfLiteParserImpl::ParseDiv(
size_t subgraphIndex,
size_t operatorIndex)
2048 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2050 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2051 const auto * options = operatorPtr->builtin_options.AsDivOptions();
2053 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2056 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2062 auto layerName = fmt::format(
"Div:{}:{}", subgraphIndex, operatorIndex);
2069 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2070 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2071 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2073 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2074 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2077 void TfLiteParserImpl::ParseAdd(
size_t subgraphIndex,
size_t operatorIndex)
2079 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2081 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2082 const auto * options = operatorPtr->builtin_options.AsAddOptions();
2084 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2087 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2093 auto layerName = fmt::format(
"Add:{}:{}", subgraphIndex, operatorIndex);
2100 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2101 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2102 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2104 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2105 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2108 void TfLiteParserImpl::ParseMul(
size_t subgraphIndex,
size_t operatorIndex)
2110 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2112 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2113 const auto * options = operatorPtr->builtin_options.AsMulOptions();
2115 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2118 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2124 auto layerName = fmt::format(
"Mul:{}:{}", subgraphIndex, operatorIndex);
2125 IConnectableLayer* layer = m_Network->AddMultiplicationLayer(layerName.c_str());
2131 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2132 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2133 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2135 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2136 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2139 void TfLiteParserImpl::ParseMean(
size_t subgraphIndex,
size_t operatorIndex)
2141 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2143 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2145 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2152 std::vector<unsigned int> axis(dimTensorInfo.GetNumElements());
2153 ::memcpy(axis.data(), bufferPtr->data.data(), dimTensorInfo.GetNumBytes());
2163 auto layerName = fmt::format(
"Mean:{}:{}", subgraphIndex, operatorIndex);
2169 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2170 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2172 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2173 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2176 void TfLiteParserImpl::ParsePad(
size_t subgraphIndex,
size_t operatorIndex)
2178 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2190 std::vector<unsigned int> padBuffer(padTensorInfo.
GetNumElements());
2191 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.
GetNumBytes());
2195 if (inputTensorInfo.IsQuantized())
2197 desc.
m_PadValue =
static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2199 for (
unsigned int i = 0; i < padTensorInfo.
GetNumElements() / step; ++i)
2201 desc.
m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2204 auto layerName = fmt::format(
"Pad:{}:{}", subgraphIndex, operatorIndex);
2211 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2212 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2214 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2215 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2218 void TfLiteParserImpl::ParseMirrorPad(
size_t subgraphIndex,
size_t operatorIndex)
2220 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2233 std::vector<unsigned int> padBuffer(padTensorInfo.
GetNumElements());
2234 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.
GetNumBytes());
2238 for (
unsigned int i = 0; i < padTensorInfo.
GetNumElements() / step; ++i)
2240 desc.
m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2243 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2244 const auto* options = operatorPtr->builtin_options.AsMirrorPadOptions();
2246 if (options->mode == tflite::MirrorPadMode_REFLECT)
2250 else if (options->mode == tflite::MirrorPadMode_SYMMETRIC)
2261 auto inputShape = inputTensorInfo.GetShape();
2264 const unsigned int isReflect =
static_cast<unsigned int>(desc.
m_PaddingMode == PaddingMode::Reflect);
2265 for(
unsigned int i = 0; i < padList.size(); ++i)
2267 if(padList.at(i).first > (inputShape[i] - isReflect) ||
2268 padList.at(i).second > (inputShape[i] - isReflect))
2271 "equal (Symmetric) to the dimension size.");
2275 auto layerName = fmt::format(
"MirrorPad:{}:{}", subgraphIndex, operatorIndex);
2282 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2283 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2285 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2286 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2289 void TfLiteParserImpl::ParsePrelu(
size_t subgraphIndex,
size_t operatorIndex)
2291 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2293 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2296 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2299 auto layerName = fmt::format(
"Prelu:{}:{}", subgraphIndex, operatorIndex);
2304 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
2310 if (IsConstTensor(inputs[1]))
2312 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2314 RegisterConsumerOfTensor(subgraphIndex, inputTensorIndexes[0], slot);
2316 auto alphaTensorAndData = CreateConstTensorNonPermuted(inputs[1], alphaTensorInfo);
2317 std::string constLayerName = fmt::format(
"Constant:{}", inputs[1]->name);
2319 m_Network->AddConstantLayer(alphaTensorAndData, constLayerName.c_str());
2324 RegisterOutputSlots(subgraphIndex,
2325 VIRTUAL_OPERATOR_ID,
2327 { inputTensorIndexes[1] });
2331 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2332 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIndexes);
2335 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2336 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2339 void TfLiteParserImpl::ParseQuantize(
size_t subgraphIndex,
size_t operatorIndex)
2341 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2343 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2346 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2349 auto layerName = fmt::format(
"Quantize:{}:{}", subgraphIndex, operatorIndex);
2357 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2358 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2360 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2361 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2364 void TfLiteParserImpl::ParseRelu(
size_t subgraphIndex,
size_t operatorIndex)
2366 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::ReLu);
2369 void TfLiteParserImpl::ParseRelu6(
size_t subgraphIndex,
size_t operatorIndex)
2371 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::BoundedReLu);
2374 void TfLiteParserImpl::ParseLeakyRelu(
size_t subgraphIndex,
size_t operatorIndex)
2376 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::LeakyReLu);
2379 void TfLiteParserImpl::ParseLogistic(
size_t subgraphIndex,
size_t operatorIndex)
2381 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Sigmoid);
2384 void TfLiteParserImpl::ParseTanH(
size_t subgraphIndex,
size_t operatorIndex)
2386 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::TanH);
2389 void TfLiteParserImpl::ParseElu(
size_t subgraphIndex,
size_t operatorIndex)
2391 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::Elu);
2394 void TfLiteParserImpl::ParseHardSwish(
size_t subgraphIndex,
size_t operatorIndex)
2396 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::HardSwish);
2399 void TfLiteParserImpl::ParseActivation(
size_t subgraphIndex,
size_t operatorIndex,
ActivationFunction activationType)
2401 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2402 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2405 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2408 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2411 auto layerName = fmt::format(
"Activation:");
2415 switch (activationType)
2417 case ActivationFunction::ReLu:
2419 layerName += fmt::format(
"RELU:{}:{}", subgraphIndex, operatorIndex);
2422 case ActivationFunction::BoundedReLu:
2424 layerName += fmt::format(
"RELU6:{}:{}", subgraphIndex, operatorIndex);
2425 activationDesc.
m_A = 6.0f;
2426 activationDesc.
m_B = 0.0f;
2429 case ActivationFunction::Sigmoid:
2431 layerName += fmt::format(
"SIGMOID:{}:{}", subgraphIndex, operatorIndex);
2434 case ActivationFunction::TanH:
2436 layerName += fmt::format(
"TANH:{}:{}", subgraphIndex, operatorIndex);
2437 activationDesc.
m_A = 1.0f;
2438 activationDesc.
m_B = 1.0f;
2441 case ActivationFunction::LeakyReLu:
2443 layerName += fmt::format(
"LEAKYRELU:{}:{}", subgraphIndex, operatorIndex);
2444 const auto * options = operatorPtr->builtin_options.AsLeakyReluOptions();
2445 activationDesc.
m_A = options->alpha;
2448 case ActivationFunction::Elu:
2450 layerName += fmt::format(
"ELU:{}:{}", subgraphIndex, operatorIndex);
2451 activationDesc.
m_A = 1.0f;
2454 case ActivationFunction::HardSwish:
2456 layerName += fmt::format(
"HARDSWISH:{}:{}", subgraphIndex, operatorIndex);
2462 fmt::format(
"Unexpected ActivationFunction[{}] when creating layerName {} ",
2467 IConnectableLayer*
const layer = m_Network->AddActivationLayer(activationDesc, layerName.c_str());
2474 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2475 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2478 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2479 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2482 const std::vector<int32_t> & targetDimsIn)
2484 std::vector<unsigned int> outputDims(targetDimsIn.begin(), targetDimsIn.end());
2485 const auto stretchDim = std::find(targetDimsIn.begin(), targetDimsIn.end(), -1);
2487 if (stretchDim != targetDimsIn.end())
2489 if (std::find(std::next(stretchDim), targetDimsIn.end(), -1) != targetDimsIn.end())
2492 fmt::format(
"At most one component of shape can be -1 {}",
CHECK_LOCATION().AsString()));
2495 auto targetNumElements =
2497 std::accumulate(targetDimsIn.begin(), targetDimsIn.end(), -1, std::multiplies<int32_t>()));
2499 auto stretchIndex =
static_cast<size_t>(std::distance(targetDimsIn.begin(), stretchDim));
2500 outputDims[stretchIndex] = inputTensorInfo.
GetNumElements() / targetNumElements;
2511 void TfLiteParserImpl::ParseReshape(
size_t subgraphIndex,
size_t operatorIndex)
2513 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2515 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2517 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2520 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2521 const auto * options = operatorPtr->builtin_options.AsReshapeOptions();
2522 auto layerName = fmt::format(
"Reshape:{}:{}", subgraphIndex, operatorIndex);
2526 CheckMatchingQuantization(inputTensorInfo, actualOutputTensorInfo, layerName,
"Input 0",
"Output 0");
2532 std::vector<int32_t> targetShape;
2533 bool targetShapeFound =
false;
2535 if (options !=
nullptr)
2538 if (options->new_shape.empty() ==
false)
2540 targetShape = options->new_shape;
2541 targetShapeFound =
true;
2546 if (!targetShapeFound)
2549 if (inputs.size() > 1 && inputs[1] !=
nullptr)
2551 if (inputs[1]->is_variable)
2556 if (inputs[1]->shape.size() != 1)
2561 if (inputs[1]->type != tflite::TensorType_INT32)
2567 auto bufferPtr =
GetBuffer(m_Model, inputs[1]->buffer);
2568 auto values =
reinterpret_cast<const int32_t*
>(bufferPtr->data.data());
2573 for (
int i=0; i < inputs[1]->shape[0]; ++i)
2575 targetShape.push_back(values[i]);
2581 "At least one method required");
2590 if (inputs.size() > 1 && !
CheckShape(reshapeOutputTensorShape, outputs[0]->shape))
2592 std::stringstream ss;
2593 ss <<
"New shape defined in reshape parameters " 2594 << reshapeOutputTensorShape
2595 <<
" does not equal output shape " 2596 << actualOutputTensorInfo.
GetShape()
2605 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
2609 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2610 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2612 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2613 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2616 void TfLiteParserImpl::ParseResizeBilinear(
size_t subgraphIndex,
size_t operatorIndex)
2618 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::Bilinear);
2621 void TfLiteParserImpl::ParseResizeNearestNeighbor(
size_t subgraphIndex,
size_t operatorIndex)
2623 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::NearestNeighbor);
2626 void TfLiteParserImpl::ParseResize(
size_t subgraphIndex,
size_t operatorIndex,
ResizeMethod resizeMethod)
2628 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2630 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2633 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2639 std::vector<int32_t> sizeTensorData(sizeTensorInfo.GetNumElements());
2642 ::memcpy(sizeTensorData.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
2646 desc.m_TargetHeight =
static_cast<uint32_t
> (sizeTensorData[0]);
2647 desc.m_TargetWidth =
static_cast<uint32_t
> (sizeTensorData[1]);
2650 auto layerName = fmt::format(
"Resize:");
2652 switch (resizeMethod)
2654 case ResizeMethod::Bilinear:
2656 layerName += fmt::format(
"BILINEAR:{}:{}", subgraphIndex, operatorIndex);
2658 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2659 const auto * options = operatorPtr->builtin_options.AsResizeBilinearOptions();
2661 desc.m_AlignCorners = options->align_corners;
2664 case ResizeMethod::NearestNeighbor:
2666 layerName += fmt::format(
"NEARESTNEIGHBOR:{}:{}", subgraphIndex, operatorIndex);
2672 fmt::format(
"Unexpected ResizeMethod[{}] when creating layerName {} ",
2679 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
2685 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2686 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2688 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2689 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2692 void TfLiteParserImpl::ParseConcatenation(
size_t subgraphIndex,
size_t operatorIndex)
2694 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2696 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2697 const auto * options = operatorPtr->builtin_options.AsConcatenationOptions();
2701 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2702 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2705 unsigned int numConcatView =
static_cast<unsigned int>(inputs.size());
2708 const unsigned int concatDimInput =
static_cast<unsigned int>(
2709 (
static_cast<int>(inputRank) + options->axis) %
static_cast<int>(inputRank));
2711 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatView), inputRank);
2714 unsigned int mergeDimOrigin = 0;
2716 for (
unsigned int viewIndex = 0; viewIndex < numConcatView; ++viewIndex)
2722 inputTensorInfo, concatDescriptor, concatDimInput, viewIndex, mergeDimOrigin);
2725 auto layerName = fmt::format(
"Concatenation:{}:{}", subgraphIndex, operatorIndex);
2728 IConnectableLayer* layer = m_Network->AddConcatLayer(concatDescriptor, layerName.c_str());
2732 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2733 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
2736 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2738 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2739 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2742 void TfLiteParserImpl::ParseFullyConnected(
size_t subgraphIndex,
size_t operatorIndex)
2744 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2746 const auto & operatorRfr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2747 const auto options = operatorRfr->builtin_options.AsFullyConnectedOptions();
2755 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2756 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2762 int32_t weightsDimension =
static_cast<int32_t
>(filterTensorInfo.GetNumDimensions());
2763 if (weightsDimension != 2)
2766 fmt::format(
"Dimension {} for Fully Connected weights is not supported by Armnn. " 2773 auto layerName = fmt::format(
"FullyConnected:{}:{}", subgraphIndex, operatorIndex);
2775 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2777 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0]};
2778 std::vector<unsigned int> ignoreInputWhenRegister = {};
2783 tensorIndexesToRegister.emplace_back(inputTensorIndexes[1]);
2785 if (inputs.size() == 3)
2790 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
2794 layer = m_Network->AddFullyConnectedLayer(desc, layerName.c_str());
2799 unsigned int startingSlotIndex = 0;
2806 std::vector<unsigned int> reshapedDimensions(2);
2807 reshapedDimensions[1] = filterTensorInfo.GetShape()[1];
2808 reshapedDimensions[0] = inputTensorInfo.
GetNumElements() / reshapedDimensions[1];
2810 if (inputTensorInfo.
GetNumElements() % reshapedDimensions[1] != 0)
2813 fmt::format(
"Failed to deduce input tensor shape from filter size {} {}",
2814 reshapedDimensions[1],
2821 std::string reshapeLayerName = fmt::format(
"Reshape_for:{}", layer->
GetName());
2829 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {inputTensorIndexes[0]});
2831 tensorIndexesToRegister.erase(tensorIndexesToRegister.begin());
2832 startingSlotIndex = 1;
2835 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister, startingSlotIndex);
2842 options->fused_activation_function);
2845 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2846 RegisterOutputSlots(subgraphIndex, operatorIndex, fusedActivationLayer, {outputTensorIndexes[0]});
2849 void TfLiteParserImpl::ParseDetectionPostProcess(
size_t subgraphIndex,
size_t operatorIndex)
2851 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2853 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2855 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2856 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2860 auto custom_options = operatorPtr->custom_options;
2861 const flexbuffers::Map& m = flexbuffers::GetRoot(custom_options.data(), custom_options.size()).AsMap();
2870 desc.
m_ScaleH = m[
"h_scale"].AsFloat();
2871 desc.
m_ScaleW = m[
"w_scale"].AsFloat();
2872 desc.
m_ScaleX = m[
"x_scale"].AsFloat();
2873 desc.
m_ScaleY = m[
"y_scale"].AsFloat();
2875 if (!(m[
"use_regular_nms"].IsNull()))
2879 if (!(m[
"detections_per_class"].IsNull()))
2887 "must be positive and less than or equal to 1.");
2891 auto anchorTensorAndData = CreateConstTensorNonPermuted(inputs[2], anchorTensorInfo);
2893 auto layerName = fmt::format(
"DetectionPostProcess:{}:{}", subgraphIndex, operatorIndex);
2894 IConnectableLayer* layer = m_Network->AddDetectionPostProcessLayer(desc, anchorTensorAndData,
2902 m_OverridenOutputShapes.push_back({ 1, numDetectedBox, 4 });
2903 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
2904 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
2905 m_OverridenOutputShapes.push_back({ 1 });
2907 for (
unsigned int i = 0 ; i < outputs.size() ; ++i)
2915 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2916 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2919 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2920 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0],
2921 outputTensorIndexes[1],
2922 outputTensorIndexes[2],
2923 outputTensorIndexes[3]});
2927 void TfLiteParserImpl::ParsePack(
size_t subgraphIndex,
size_t operatorIndex)
2929 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2931 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2932 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2935 if (inputs.size() < 1)
2940 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2941 const auto* options = operatorPtr->builtin_options.AsPackOptions();
2944 desc.
m_Axis =
static_cast<uint32_t
>(options->axis);
2945 desc.
m_NumInputs =
static_cast<uint32_t
>(inputs.size());
2951 auto layerName = fmt::format(
"Pack:{}:{}", subgraphIndex, operatorIndex);
2959 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2960 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
2962 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2963 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2966 void TfLiteParserImpl::ParseUnpack(
size_t subgraphIndex,
size_t operatorIndex)
2968 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2970 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2971 const auto * options = operatorPtr->builtin_options.AsUnpackOptions();
2976 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2981 if (unpackAxis >= inputTensorInfo.GetNumDimensions())
2984 fmt::format(
"The unpack axis: {} cannot be greater than or equal to " 2985 "the number of input dimension {} {}",
2987 inputTensorInfo.GetNumDimensions(),
2995 unpackNum = inputTensorInfo.GetShape()[unpackAxis];
3001 throw ParseException(
"Number to unpack must greater than zero.");
3004 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3007 auto inputDimSize = inputTensorInfo.GetNumDimensions();
3008 std::vector<unsigned int> unpackDimSizes(inputDimSize);
3011 for (
unsigned int i = 0; i < inputDimSize; ++i)
3013 unpackDimSizes[i] = inputTensorInfo.GetShape()[i];
3016 if (unpackDimSizes[unpackAxis] != unpackNum)
3018 throw ParseException(
"Number to unpack must be the same as length of the dimension to " 3022 unpackDimSizes[unpackAxis] /= unpackNum;
3024 SplitterDescriptor splitDesc(unpackNum, static_cast<unsigned int>(unpackDimSizes.size()));
3025 for (
unsigned int j = 0; j < unpackNum; ++j)
3028 for (
unsigned int dimIdx = 0; dimIdx < unpackDimSizes.size(); ++dimIdx)
3030 splitDesc.
SetViewSize(j, dimIdx, unpackDimSizes[dimIdx]);
3035 auto layerName = fmt::format(
"Unpack:{}:{}", subgraphIndex, operatorIndex);
3036 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
3040 unpackDimSizes.data());
3042 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3043 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3045 std::vector<unsigned int> reshapeDims;
3046 for (
unsigned int axis = 0; axis < splitOutShape.
GetNumDimensions(); ++axis)
3048 if (axis != unpackAxis)
3050 reshapeDims.push_back(splitOutShape[axis]);
3060 std::string reshapeLayerName = fmt::format(
"Reshape_for:{}", layer->
GetName());
3075 RegisterProducerOfTensor(subgraphIndex, reshapedOutputId, slot);
3079 void TfLiteParserImpl::ParseSplit(
size_t subgraphIndex,
size_t operatorIndex)
3081 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3083 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3084 const auto * options = operatorPtr->builtin_options.AsSplitOptions();
3091 throw ParseException(
"Number to splits must greater than zero.");
3094 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3096 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3104 if (axisBufferPtr ==
nullptr)
3107 fmt::format(
"Operation has invalid inputs. Failed to read axis. {}",
3112 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.
GetNumBytes());
3113 int32_t axis = axisData[0];
3115 auto inputDimensions =
static_cast<int32_t
>(inputTensorInfo.GetNumDimensions());
3116 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3122 fmt::format(
"Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3129 auto inputDimSize = inputTensorInfo.GetNumDimensions();
3133 fmt::format(
"The number of dimensions: {} for input tensors of the split op cannot be greater than {} {}",
3134 inputTensorInfo.GetNumDimensions(),
3139 std::vector<unsigned int> splitterDimSizes(inputDimSize);
3142 for (
unsigned int i = 0; i < inputDimSize; ++i)
3144 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
3147 if (splitterDimSizes[splitDim] % numSplits != 0)
3149 throw ParseException(
"Number of splits must evenly divide the dimension");
3151 splitterDimSizes[splitDim] /= numSplits;
3154 for (
unsigned int j = 0; j < numSplits; ++j)
3157 for (
unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
3159 splitDesc.
SetViewSize(j, dimIdx, splitterDimSizes[dimIdx]);
3164 auto layerName = fmt::format(
"Split:{}:{}", subgraphIndex, operatorIndex);
3165 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
3168 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3169 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[1]});
3177 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3178 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3184 int v = idx < 0 ? numDims + idx : idx;
3188 return static_cast<unsigned int>(v);
3191 void TfLiteParserImpl::ParseSplitV(
size_t subgraphIndex,
size_t operatorIndex)
3193 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3195 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3196 const auto * options = operatorPtr->builtin_options.AsSplitVOptions();
3198 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3201 auto& inputTensor = inputs[0];
3202 auto& splitsTensor = inputs[1];
3203 auto& axisTensor = inputs[2];
3215 fmt::format(
"The number of dimensions: {} for input tensors of the " 3216 "SplitV op cannot be greater than {} {}",
3224 if (axisBufferPtr ==
nullptr)
3227 fmt::format(
"Operation has invalid inputs. Failed to read axis. {}",
3232 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.
GetNumBytes());
3233 int32_t axis = axisData[0];
3235 auto inputDimensions =
static_cast<int32_t
>(inputTensorInfo.
GetNumDimensions());
3236 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3242 fmt::format(
"Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3250 unsigned int numSplits{0};
3266 std::vector<int> splitsData(numSplits);
3268 ::memcpy(splitsData.data(), splitsBufferPtr->data.data(), splitsInfo.
GetNumBytes());
3270 unsigned int idx = 0;
3272 unsigned int inferIdx{0};
3274 for (
auto split : splitsData)
3288 if (numInferred == 0)
3290 if (splitSum != armnn::numeric_cast<int>(inputTensorInfo.
GetShape()[splitDim]))
3292 throw ParseException(
"SplitV split_sizes does not sum to the dimension of value along split_dim.");
3295 else if (numInferred == 1)
3301 throw ParseException(
"Cannot infer split size for more than one split");
3305 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3310 unsigned int accumSplit = 0;
3311 for (
unsigned int j = 0; j < numSplits; ++j)
3316 for (
unsigned int dimIdx = 0; dimIdx < inputTensorInfo.
GetNumDimensions(); ++dimIdx)
3318 unsigned int dimSize = inputTensorInfo.
GetShape()[dimIdx];
3319 if (dimIdx == splitDim)
3321 dimSize = splitSize;
3323 splitDesc.SetViewSize(j, dimIdx, dimSize);
3326 splitDesc.SetViewOriginCoord(j, splitDim, accumSplit);
3327 accumSplit += splitSize;
3330 auto layerName = fmt::format(
"SplitV:{}:{}", subgraphIndex, operatorIndex);
3331 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
3334 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3335 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3343 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3344 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3347 void TfLiteParserImpl::ParseArgMin(
size_t subgraphIndex,
size_t operatorIndex)
3352 void TfLiteParserImpl::ParseArgMax(
size_t subgraphIndex,
size_t operatorIndex)
3357 void TfLiteParserImpl::ParseArgMinMax(
size_t subgraphIndex,
size_t operatorIndex,
ArgMinMaxFunction argMinMaxFunction)
3359 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3360 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3363 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3377 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
3383 if (axisBufferPtr ==
nullptr)
3386 fmt::format(
"Operation has invalid inputs. Failed to read axis. {}",
3391 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.
GetNumBytes());
3392 int32_t axis = axisData.front();
3394 auto inputDimensions =
static_cast<int32_t
>(inputTensorInfo.GetNumDimensions());
3395 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3401 fmt::format(
"Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3411 auto layerName = argMinMaxFunction == ArgMinMaxFunction::Max ?
"ArgMax:{}:{}" :
"ArgMin:{}:{}";
3412 auto layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3413 IConnectableLayer *layer = m_Network->AddArgMinMaxLayer(desc, layerNameFormatted.c_str());
3418 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3419 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3422 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3423 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3426 void TfLiteParserImpl::ParseGather(
size_t subgraphIndex,
size_t operatorIndex)
3428 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3441 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3442 const auto * options = operatorPtr->builtin_options.AsGatherOptions();
3443 auto axis = options->axis;
3445 auto inputDimensions =
static_cast<int32_t
>(inputTensorInfo.GetNumDimensions());
3448 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3451 fmt::format(
"Operation has invalid axis: {} It is out of bounds [ -{}, {} ) {}",
3453 inputDimensions, inputDimensions,
3456 if (outputDimensions != static_cast<unsigned int>(inputDimensions) + indicesDimensions - 1)
3459 fmt::format(
"Operation has invalid output dimensions: {} Output must be an ({} + {} - 1) -D tensor {}",
3461 inputDimensions, indicesDimensions,
3465 gatherDescriptor.
m_Axis = axis;
3467 auto layerName = fmt::format(
"Gather:{}:{}", subgraphIndex, operatorIndex);
3468 IConnectableLayer* layer = m_Network->AddGatherLayer(gatherDescriptor, layerName.c_str());
3472 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3473 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3475 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3476 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3479 void TfLiteParserImpl::ParseDepthToSpace(
size_t subgraphIndex,
size_t operatorIndex)
3481 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3490 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3491 const auto * options = operatorPtr->builtin_options.AsDepthToSpaceOptions();
3492 auto blockSize = options->block_size;
3496 fmt::format(
"Operation has invalid block size: {} Block size should be >= 2 {}",
3502 auto layerName = fmt::format(
"DepthToSpace:{}:{}", subgraphIndex, operatorIndex);
3503 IConnectableLayer* layer = m_Network->AddDepthToSpaceLayer(descriptor, layerName.c_str());
3508 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3509 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3511 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3512 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3515 void TfLiteParserImpl::ParseSum(
size_t subgraphIndex,
size_t operatorIndex)
3520 void TfLiteParserImpl::ParseReduceProd(
size_t subgraphIndex,
size_t operatorIndex)
3525 void TfLiteParserImpl::ParseReduceMax(
size_t subgraphIndex,
size_t operatorIndex)
3530 void TfLiteParserImpl::ParseReduceMin(
size_t subgraphIndex,
size_t operatorIndex)
3535 void TfLiteParserImpl::ParseReduce(
size_t subgraphIndex,
size_t operatorIndex,
ReduceOperation reduceOperation)
3537 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3539 const auto &operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3540 const auto *options = operatorPtr->builtin_options.AsReducerOptions();
3542 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3545 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3548 auto layerName = fmt::format(
"Reduce:{}:{}", subgraphIndex, operatorIndex);
3556 if (axisBufferPtr !=
nullptr)
3558 std::vector<int32_t> axisData(inputTensorInfo1.
GetNumElements());
3559 ::memcpy(axisData.data(), axisBufferPtr->data.data(), inputTensorInfo1.
GetNumBytes());
3563 std::set<unsigned int> uniqueAxis;
3564 std::transform(axisData.begin(),
3566 std::inserter(uniqueAxis, uniqueAxis.begin()),
3567 [rank](
int i)->unsigned
int{
3568 return static_cast<uint32_t
>(((i + rank) % rank)); });
3569 desc.
m_vAxis.assign(uniqueAxis.begin(), uniqueAxis.end());
3589 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3590 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3593 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3594 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3597 void TfLiteParserImpl::ParseAbs(
size_t subgraphIndex,
size_t operatorIndex)
3602 void TfLiteParserImpl::ParseExp(
size_t subgraphIndex,
size_t operatorIndex)
3607 void TfLiteParserImpl::ParseLocalResponseNormalization(
size_t subgraphIndex,
size_t operatorIndex)
3609 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3611 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3614 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3617 auto layerName = fmt::format(
"LRN:{}:{}", subgraphIndex, operatorIndex);
3618 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3622 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3623 const auto* options = operatorPtr->builtin_options.AsLocalResponseNormalizationOptions();
3629 descriptor.
m_NormSize =
static_cast<uint32_t
>(options->radius);
3630 descriptor.
m_K = options->bias;
3631 descriptor.
m_Alpha = options->alpha;
3632 descriptor.
m_Beta = options->beta;
3638 IConnectableLayer* layer = m_Network->AddNormalizationLayer(descriptor, layerNameFormatted.c_str());
3644 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3645 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3647 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3648 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3651 void TfLiteParserImpl::ParseLogicalNot(
size_t subgraphIndex,
size_t operatorIndex)
3656 void TfLiteParserImpl::ParseNeg(
size_t subgraphIndex,
size_t operatorIndex)
3661 void TfLiteParserImpl::ParseRsqrt(
size_t subgraphIndex,
size_t operatorIndex)
3666 void TfLiteParserImpl::ParseElementwiseUnary(
size_t subgraphIndex,
size_t operatorIndex,
UnaryOperation unaryOperation)
3668 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3670 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3673 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3677 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3681 IConnectableLayer* layer = m_Network->AddElementwiseUnaryLayer(desc, layerNameFormatted.c_str());
3687 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3688 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3690 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3691 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3694 void TfLiteParserImpl::ParseEqual(
size_t subgraphIndex,
size_t operatorIndex)
3699 void TfLiteParserImpl::ParseNotEqual(
size_t subgraphIndex,
size_t operatorIndex)
3704 void TfLiteParserImpl::ParseGreater(
size_t subgraphIndex,
size_t operatorIndex)
3709 void TfLiteParserImpl::ParseGreaterOrEqual(
size_t subgraphIndex,
size_t operatorIndex)
3714 void TfLiteParserImpl::ParseLess(
size_t subgraphIndex,
size_t operatorIndex)
3719 void TfLiteParserImpl::ParseLessOrEqual(
size_t subgraphIndex,
size_t operatorIndex)
3724 void TfLiteParserImpl::ParseComparison(
size_t subgraphIndex,
size_t operatorIndex,
3727 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3729 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3732 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3736 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3740 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerNameFormatted,
"Input 0",
"Input 1");
3744 IConnectableLayer* layer = m_Network->AddComparisonLayer(desc, layerNameFormatted.c_str());
3750 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3751 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3753 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3754 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3758 unsigned int outputSlot,
3759 tflite::ActivationFunctionType activationType)
3762 std::string layerName = prevLayer->
GetName();
3764 switch(activationType)
3766 case tflite::ActivationFunctionType_NONE:
3771 case tflite::ActivationFunctionType_RELU:
3773 activationDesc.
m_Function = ActivationFunction::ReLu;
3774 layerName +=
":RELU";
3777 case tflite::ActivationFunctionType_RELU6:
3779 activationDesc.
m_Function = ActivationFunction::BoundedReLu;
3780 activationDesc.
m_A = 6.0f;
3781 activationDesc.
m_B = 0.0f;
3782 layerName +=
":RELU6";
3785 case tflite::ActivationFunctionType_TANH:
3787 activationDesc.
m_Function = ActivationFunction::TanH;
3788 activationDesc.
m_A = 1.0f;
3789 activationDesc.
m_B = 1.0f;
3790 layerName +=
":TANH";
3795 case tflite::ActivationFunctionType_RELU_N1_TO_1:
3796 case tflite::ActivationFunctionType_SIGN_BIT:
3800 fmt::format(
"TfLite parser doesn't suppport fused activation: " 3803 tflite::EnumNameActivationFunctionType(activationType),
3810 m_Network->AddActivationLayer(activationDesc, layerName.c_str());
3812 auto & prevOutputSlot = prevLayer->
GetOutputSlot(outputSlot);
3815 return activationLayer;
3820 if (fileName ==
nullptr)
3825 std::error_code errorCode;
3826 fs::path pathToFile(fileName);
3827 if (!fs::exists(pathToFile, errorCode))
3830 std::stringstream msg;
3831 msg <<
"Cannot find the file (" << fileName <<
") errorCode: " << errorCode
3836 std::ifstream file(fileName, std::ios::binary);
3837 std::string fileContent((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
3839 fileContent.size());
3844 if (binaryContent ==
nullptr)
3849 flatbuffers::Verifier verifier(binaryContent, len);
3850 if (verifier.VerifyBuffer<tflite::Model>() ==
false)
3853 fmt::format(
"Buffer doesn't conform to the expected Tensorflow Lite " 3854 "flatbuffers format. size:{} {}",
3858 return tflite::UnPackModel(binaryContent);
3862 size_t subgraphIndex,
3863 size_t operatorIndex)
3867 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3868 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
3870 size_t inputCount = operatorPtr->inputs.size();
3872 for (
size_t i=0; i<inputCount; ++i)
3875 if (operatorPtr->inputs[i] == -1)
3882 result.push_back(subgraphPtr->tensors[inputId].get());
3889 size_t subgraphIndex,
3890 size_t operatorIndex)
3894 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3895 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
3897 size_t outputCount = operatorPtr->outputs.size();
3899 for (
size_t i=0; i<outputCount; ++i)
3903 result[i] = subgraphPtr->tensors[outputId].get();
3909 size_t subgraphIndex)
3912 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3914 size_t inputCount = subgraphPtr->inputs.size();
3916 for (
size_t i=0; i<inputCount; ++i)
3920 result[i] = std::make_pair(inputId, subgraphPtr->tensors[inputId].get());
3926 size_t subgraphIndex)
3929 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3931 size_t outputCount = subgraphPtr->outputs.size();
3933 for (
size_t i=0; i<outputCount; ++i)
3936 result[i] = std::make_pair(outputId, subgraphPtr->tensors[outputId].get());
3942 size_t subgraphIndex,
3943 size_t operatorIndex)
3946 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3947 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
3948 return operatorPtr->inputs;
3952 size_t subgraphIndex,
3953 size_t operatorIndex)
3956 const auto & subgraphPtr = model->subgraphs[subgraphIndex];
3957 const auto & operatorPtr = subgraphPtr->operators[operatorIndex];
3958 return operatorPtr->outputs;
3961 void TfLiteParserImpl::RegisterInputSlots(
size_t subgraphIndex,
3962 size_t operatorIndex,
3964 const std::vector<unsigned int>& tensorIndexes,
3965 unsigned int startingSlotIndex)
3967 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3973 fmt::format(
"The number of tensor inputs ({}) does not match the number expected ({})" 3974 " for subgraph:{} operator index:{} {}",
3975 tensorIndexes.size(),
3982 for (
unsigned int index = 0; index < tensorIndexes.size() ; ++index)
3984 unsigned int tensorIndex = tensorIndexes[index];
3986 RegisterConsumerOfTensor(subgraphIndex, tensorIndex, slot);
3990 void TfLiteParserImpl::RegisterOutputSlots(
size_t subgraphIndex,
3991 size_t operatorIndex,
3993 const std::vector<unsigned int>& tensorIndexes)
3995 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4000 fmt::format(
"The number of tensor outputs ({}) does not match the number expected ({})" 4001 " for subgraph:{} operator index:{} {}",
4002 tensorIndexes.size(),
4009 for (
unsigned int slotIndex = 0; slotIndex < layer->
GetNumOutputSlots(); ++slotIndex)
4011 unsigned int tensorIndex = tensorIndexes[slotIndex];
4013 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
4017 void TfLiteParserImpl::SetupInputLayers(
size_t subgraphIndex)
4022 for (
auto const & tensorIdAndPtr : inputs)
4024 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
4026 m_Network->AddInputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
4031 RegisterOutputSlots(subgraphIndex,
4032 VIRTUAL_OPERATOR_ID,
4034 {
static_cast<uint32_t
>(tensorIdAndPtr.first) });
4038 void TfLiteParserImpl::SetupOutputLayers(
size_t subgraphIndex)
4043 for (
auto const & tensorIdAndPtr : outputs)
4045 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
4047 m_Network->AddOutputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
4049 RegisterInputSlots(subgraphIndex,
4050 VIRTUAL_OPERATOR_ID,
4052 {
static_cast<uint32_t
>(tensorIdAndPtr.first) });
4056 void TfLiteParserImpl::SetupConstantLayers(
size_t subgraphIndex)
4060 const auto & subgraphPtr = m_Model->subgraphs[subgraphIndex];
4061 for (
unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
4063 for (
unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
4065 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot ==
nullptr &&
4066 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
4068 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
4070 if(IsConstTensor(tensorPtr))
4073 auto tensorAndData = CreateConstTensorNonPermuted(tensorPtr, tensorInfo);
4075 std::string layerName = fmt::format(
"Constant:{}", tensorPtr->name);
4076 IConnectableLayer *layer = m_Network->AddConstantLayer(tensorAndData, layerName.c_str());
4079 RegisterOutputSlots(subgraphIndex,
4080 VIRTUAL_OPERATOR_ID,
4087 fmt::format(
"Invalid Tensor: Tensor should be constant. {}",
4099 return model->buffers[bufferIndex].get();
4102 template<
typename T>
4103 std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
4112 auto constData = CreateConstTensorImpl<T>(bufferPtr,
4116 TfLiteParserImpl::SupportedDataStorage storage(std::move(constData.second));
4117 return std::make_pair(constData.first, std::move(storage));
4120 bool TfLiteParserImpl::IsConstTensor(
TensorRawPtr tensorPtr)
4123 bool isConst =
true;
4125 auto buffer =
GetBuffer(m_Model, tensorPtr->buffer);
4126 if (buffer->data.size() == 0)
4134 std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
4135 TfLiteParserImpl::CreateConstTensorPermuted(
TensorRawPtr tensorPtr,
4140 auto bufferPtr =
GetBuffer(m_Model, tensorPtr->buffer);
4149 return CreateConstTensorAndStoreData<float>(bufferPtr,
4154 return CreateConstTensorAndStoreData<uint8_t>(bufferPtr,
4159 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
4164 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
4169 return CreateConstTensorAndStoreData<int32_t>(bufferPtr,
4175 std::stringstream errString;
4176 errString <<
"Unexpected datatype when creating const tensor: " 4178 <<
" shape:" << tensorInfo.GetShape()
4189 auto bufferPtr =
GetBuffer(m_Model, tensorPtr->buffer);
4195 return ConstTensor(tensorInfo, bufferPtr->data.data());
4199 const std::string& name)
const 4203 for (
auto const & input : inputs)
4205 if (input.second->name == name)
4207 auto bindingId = GenerateLayerBindingId(subgraphId, input.first);
4210 inputTensorInfo.SetConstant(
true);
4211 return std::make_pair(bindingId, inputTensorInfo);
4215 std::stringstream bindings;
4216 for (
auto const & input : inputs)
4218 bindings <<
"'" << input.second->name <<
"' ";
4222 fmt::format(
"No input binding found for subgraph:{} and name:{}. " 4223 "Possible inputs are: [{}] {}",
4231 const std::string& name)
const 4235 for (
unsigned int i = 0; i < outputs.size(); ++i)
4237 auto const output = outputs[i];
4238 if (output.second->name == name)
4240 auto bindingId = GenerateLayerBindingId(subgraphId, output.first);
4241 std::vector<unsigned int> shape = m_OverridenOutputShapes.size() > 0 ?
4242 m_OverridenOutputShapes[i] : AsUnsignedVector(output.second->shape);
4243 return std::make_pair(bindingId,
ToTensorInfo(output.second, shape));
4247 std::stringstream bindings;
4248 for (
auto const & output : outputs)
4250 bindings <<
"'" << output.second->name <<
"' ";
4254 fmt::format(
"No output binding found for subgraph:{} and name:{}. " 4255 "Possible outputs are: [{}] {}",
4264 return m_Model->subgraphs.size();
4271 std::vector<std::string> result;
4272 result.reserve(inputs.size());
4273 for (
auto const & input : inputs)
4275 result.push_back(input.second->name);
4284 std::vector<std::string> result;
4285 result.reserve(outputs.size());
4286 for (
auto const & output : outputs)
4288 result.push_back(output.second->name);
4298 TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<
float[]> && data)
4299 : m_FloatData(std::move(data))
4300 , m_Uint8Data(
nullptr)
4301 , m_Int8Data(
nullptr)
4302 , m_Int32Data(
nullptr)
4306 TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<uint8_t[]> && data)
4307 : m_FloatData(
nullptr)
4308 , m_Uint8Data(std::move(data))
4309 , m_Int8Data(
nullptr)
4310 , m_Int32Data(
nullptr)
4314 TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int8_t[]> && data)
4315 : m_FloatData(
nullptr)
4316 , m_Uint8Data(
nullptr)
4317 , m_Int8Data(std::move(data))
4318 , m_Int32Data(
nullptr)
4322 TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int32_t[]> && data)
4323 : m_FloatData(
nullptr)
4324 , m_Uint8Data(
nullptr)
4325 , m_Int8Data(
nullptr)
4326 , m_Int32Data(std::move(data))
uint32_t m_PadBottom
Padding bottom value in the height dimension.
bool m_BiasEnabled
Enable/disable bias.
#define CHECK_MODEL(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX)
std::unique_ptr< tflite::ModelT > ModelPtr
static TensorIdRawPtrVector GetSubgraphOutputs(const ModelPtr &model, size_t subgraphIndex)
virtual unsigned int GetNumOutputSlots() const =0
Returns the number of connectable output slots.
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
UnaryOperation m_Operation
Specifies the elementwiseUnary operation to execute.
uint32_t m_Axis
0-based axis along which to stack the input tensors.
A ViewsDescriptor for the SplitterLayer.
Interface for a layer that is connectable to other layers via InputSlots and OutputSlots.
float m_ScaleW
Center size encoding scale weight.
bool IsTypeSpaceMatch(const TensorInfo &other) const
Check that the types are the same and, if quantize, that the quantization parameters are the same...
uint32_t m_PadBottom
Padding bottom value in the height dimension.
bool m_BiasEnabled
Enable/disable bias.
virtual unsigned int GetNumInputSlots() const =0
Returns the number of connectable input slots.
float m_K
Kappa value used for the across channel normalization equation.
A TransposeConvolution2dDescriptor for the TransposeConvolution2dLayer.
#define ARMNN_THROW_PARSE_EXCEPTION(msg)
const TensorShape & GetShape() const
uint32_t m_PadBottom
Padding bottom value in the height dimension.
uint32_t m_PadLeft
Padding left value in the width dimension.
const tflite::TensorT * TensorRawPtr
std::string AsString() const
int32_t m_ShrinkAxisMask
Shrink axis mask value. If set, the nth specification shrinks the dimensionality by 1...
A ReshapeDescriptor for the ReshapeLayer.
bool AreAllDimensionsSpecified() const
Checks if there is at least one dimension not specified.
std::vector< int > m_Begin
Begin values for the input that will be sliced.
const tflite::BufferT * BufferRawPtr
uint32_t m_PadBack
Padding back value in the depth dimension.
float m_PadValue
Optional value to use for padding, defaults to 0.
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
A ComparisonDescriptor for the ComparisonLayer.
float m_ScaleX
Center size encoding scale x.
TensorShape m_InputShape
Required shape of all input tensors.
bool m_TransposeWeightMatrix
Enable/disable transpose weight matrix.
uint32_t m_PoolWidth
Pooling width value.
uint32_t m_StrideX
Stride value when proceeding through input for the width dimension.
A Convolution2dDescriptor for the Convolution2dLayer.
float m_Alpha
Alpha value for the normalization equation.
uint32_t m_PadLeft
Padding left value in the width dimension.
bool m_KeepDims
if true then output shape has no change.
bool m_BiasEnabled
Enable/disable bias.
std::vector< unsigned int > m_OutputShape
unsigned int GetNumBytes() const
ResizeMethod m_Method
The Interpolation method to use (Bilinear, NearestNeighbor).
float m_Beta
Exponentiation value.
armnn::INetworkPtr CreateNetworkFromBinaryFile(const char *graphFile)
Create the network from a flatbuffers binary file on disk.
PaddingMethod m_PaddingMethod
The padding method to be used. (Exclude, IgnoreValue).
BindingPointInfo GetNetworkOutputBindingInfo(size_t subgraphId, const std::string &name) const
Retrieve binding info (layer id and tensor info) for the network output identified by the given layer...
ArgMinMaxFunction m_Function
Specify if the function is to find Min or Max.
uint32_t m_DetectionsPerClass
Detections per classes, used in Regular NMS.
bool m_OutputShapeEnabled
Output shape if it has been specified.
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
#define CHECK_BUFFER(MODEL, BUFFER_INDEX)
virtual const char * what() const noexcept override
#define ARMNN_LOG(severity)
uint32_t m_PadTop
Padding top value in the height dimension.
std::vector< BackendOptions > NetworkOptions
uint32_t m_PadBottom
Padding bottom value in the height dimension.
std::vector< std::string > GetSubgraphOutputTensorNames(size_t subgraphId) const
Return the output tensor names for a given subgraph.
bool m_BiasEnabled
Enable/disable bias.
void ProcessConcatInputTensorInfo(armnn::TensorInfo &inputTensorInfo, armnn::OriginsDescriptor &concatDescriptor, const unsigned int &concatAxis, unsigned int inputIndex, unsigned int &mergeDimOrigin)
uint32_t m_PadRight
Padding right value in the width dimension.
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
std::vector< std::pair< unsigned int, unsigned int > > m_PadList
Specifies the padding for input dimension.
ReduceOperation m_ReduceOperation
Specifies the reduction operation to execute.
std::unique_ptr< ITfLiteParser, void(*)(ITfLiteParser *parser)> ITfLiteParserPtr
std::unique_ptr< tflite::OperatorT > OperatorPtr
unsigned int ComputeWrappedIndex(int idx, unsigned int numDimsIn)
Copyright (c) 2021 ARM Limited and Contributors.
void IgnoreUnused(Ts &&...)
uint32_t m_PadBottom
Padding bottom value in the height dimension.
int32_t m_BeginMask
Begin mask value.
static armnn::TensorInfo OutputShapeOfReshape(const armnn::TensorInfo &inputTensorInfo, const std::vector< int32_t > &targetDimsIn)
uint32_t m_DilationY
Dilation along y axis.
int32_t m_EndMask
End mask value.
A SpaceToDepthDescriptor for the SpaceToDepthLayer.
std::vector< std::pair< unsigned int, unsigned int > > m_PadList
Specifies the padding values for the input dimension: heightPad{top, bottom} widthPad{left, right}.
uint32_t m_DilationX
Dilation along x axis.
uint32_t m_DilationY
Dilation factor value for height dimension.
A BatchToSpaceNdDescriptor for the BatchToSpaceNdLayer.
uint32_t m_StrideX
Stride value when proceeding through input for the width dimension.
int LayerBindingId
Type of identifiers for bindable layers (inputs, outputs).
#define TFLITE_PARSER_VERSION
TFLITE_PARSER_VERSION: "X.Y.Z" where: X = Major version number Y = Minor version number Z = Patch ver...
virtual void SetTensorInfo(const TensorInfo &tensorInfo)=0
uint32_t m_StrideY
Stride value when proceeding through input for the height dimension.
NormalizationAlgorithmMethod m_NormMethodType
Normalization method algorithm to use (LocalBrightness, LocalContrast).
#define CHECK_TENSOR(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX)
constexpr const char * GetDataTypeName(DataType dataType)
void SetShape(const TensorShape &newShape)
armnn::INetworkPtr CreateNetworkFromBinary(const std::vector< uint8_t > &binaryContent)
Create the network from a flatbuffers binary.
A ResizeBilinearDescriptor for the ResizeBilinearLayer.
static BufferRawPtr GetBuffer(const ModelPtr &model, size_t bufferIndex)
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
uint32_t m_MaxClassesPerDetection
Maximum numbers of classes per detection, used in Fast NMS.
std::vector< unsigned int > m_Axis
Values for the dimensions to reduce.
A StackDescriptor for the StackLayer.
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
constexpr char const * GetUnaryOperationAsCString(UnaryOperation operation)
TensorShape m_TargetShape
Target shape value.
armnn::INetworkPtr CreateNetworkFromBinaryFile(const char *graphFile)
Create the network from a flatbuffers binary file on disk.
uint32_t m_PoolHeight
Pooling height value.
uint32_t m_PadTop
Padding top value in the height dimension.
uint32_t m_MaxDetections
Maximum numbers of detections.
A PadDescriptor for the PadLayer.
uint32_t m_StrideX
Stride value when proceeding through input for the width dimension.
std::unique_ptr< onnx::ModelProto > ModelPtr
#define CHECK_SUBGRAPH(MODEL, SUBGRAPH_INDEX)
uint32_t m_StrideX
Stride value when proceeding through input for the width dimension.
BindingPointInfo GetNetworkInputBindingInfo(size_t subgraphId, const std::string &name) const
Retrieve binding info (layer id and tensor info) for the network input identified by the given layer ...
bool CheckShape(const armnn::TensorShape &actual, const std::vector< uint32_t > &expected)
static ModelPtr LoadModelFromBinary(const uint8_t *binaryContent, size_t len)
float m_NmsIouThreshold
Intersection over union threshold.
uint32_t m_PadRight
Padding right value in the width dimension.
std::vector< TensorIdRawPtr > TensorIdRawPtrVector
uint32_t m_DilationX
Dilation factor value for width dimension.
uint32_t m_PadTop
Padding top value in the height dimension.
std::string FileLine() const
Status SetViewSize(uint32_t view, uint32_t coord, uint32_t value)
Set the size of the views.
#define ARMNN_ASSERT_MSG(COND, MSG)
int32_t m_NewAxisMask
New axis mask value.
bool m_KeepDims
Enable/disable keep dimensions. If true, then the reduced dimensions that are of length 1 are kept...
static std::vector< int32_t > & GetInputTensorIds(const ModelPtr &model, size_t subgraphIndex, size_t operatorIndex)
std::vector< unsigned int > m_BlockShape
Block shape values.
An output connection slot for a layer.
A L2NormalizationDescriptor for the L2NormalizationLayer.
int32_t GetQuantizationOffset() const
An ArgMinMaxDescriptor for ArgMinMaxLayer.
static const std::string GetVersion()
Retrieve version in X.Y.Z form.
float GetQuantizationScale() const
DataType GetDataType() const
An OriginsDescriptor for the ConcatLayer.
A ReduceDescriptor for the REDUCE operators.
bool has_value() const noexcept
A FullyConnectedDescriptor for the FullyConnectedLayer.
int32_t m_EllipsisMask
Ellipsis mask value.
bool m_BiasEnabled
Enable/disable bias.
static ModelPtr LoadModelFromFile(const char *fileName)
A tensor defined by a TensorInfo (shape and data type) and an immutable backing store.
unsigned int GetUnsignedAxis(const unsigned int inputDimension, const int axis)
A GatherDescriptor for the GatherLayer.
#define CHECK_VALID_SIZE(ACTUAL,...)
uint32_t m_NumClasses
Number of classes.
#define CHECKED_NON_NEGATIVE(VALUE)
std::vector< TensorRawPtr > TensorRawPtrVector
size_t GetSubgraphCount() const
Return the number of subgraphs in the parsed model.
uint32_t m_PadTop
Padding top value in the height dimension.
#define ARMNN_ASSERT(COND)
A StandInDescriptor for the StandIn layer.
bool m_UseRegularNms
Use Regular NMS.
uint32_t m_PadFront
Padding front value in the depth dimension.
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
std::vector< unsigned int > m_BlockShape
Block shape value.
std::vector< int > m_Stride
Stride values for the input that will be sliced.
bool IsActivationSupported(const BackendId &backend, const TensorInfo &input, const TensorInfo &output, const ActivationDescriptor &descriptor, char *reasonIfUnsupported=nullptr, size_t reasonIfUnsupportedMaxLength=1024)
Deprecated in favor of IBackend and ILayerSupport interfaces.
An ActivationDescriptor for the ActivationLayer.
uint32_t m_NumInputs
Number of input tensors.
uint32_t m_PadLeft
Padding left value in the width dimension.
A SliceDescriptor for the SliceLayer.
uint32_t m_StrideY
Stride value when proceeding through input for the height dimension.
armnn::INetworkPtr LoadModel(std::unique_ptr< tflite::ModelT > model)
A Convolution3dDescriptor for the Convolution3dLayer.
std::unique_ptr< tflite::SubGraphT > SubgraphPtr
uint32_t m_PadRight
Padding right value in the width dimension.
PaddingMode m_PaddingMode
Specifies the Padding mode (Constant, Reflect or Symmetric)
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
#define CHECK_TENSOR_PTR(TENSOR_PTR)
std::vector< uint32_t > m_vAxis
The indices of the dimensions to reduce.
float m_ScaleH
Center size encoding scale height.
ComparisonOperation m_Operation
Specifies the comparison operation to execute.
std::vector< int > m_End
End values for the input that will be sliced.
A SpaceToBatchNdDescriptor for the SpaceToBatchNdLayer.
static TensorIdRawPtrVector GetSubgraphInputs(const ModelPtr &model, size_t subgraphIndex)
DataLayout m_DataLayout
The data layout to be used (NDHWC, NCDHW).
Struct for the users to pass backend specific options.
NormalizationAlgorithmChannel m_NormChannelType
Normalization channel algorithm to use (Across, Within).
float m_A
Alpha upper bound value used by the activation functions. (BoundedReLu, Linear, TanH, Elu).
static TensorRawPtrVector GetInputs(const ModelPtr &model, size_t subgraphIndex, size_t operatorIndex)
uint32_t m_DilationX
Dilation along x axis.
const armnnSerializer::TensorInfo * TensorRawPtr
static TensorRawPtrVector GetOutputs(const ModelPtr &model, size_t subgraphIndex, size_t operatorIndex)
std::pair< armnn::ConstTensor, std::unique_ptr< T[]> > CreateConstTensorImpl(const T *bufferPtr, armnn::TensorInfo &tensorInfo, const armnn::Optional< armnn::PermutationVector &> permutationVector)
uint32_t m_PadLeft
Padding left value in the width dimension.
EmptyOptional is used to initialize the Optional class in case we want to have default value for an O...
uint32_t m_StrideX
Stride value when proceeding through input for the width dimension.
static std::vector< int32_t > & GetOutputTensorIds(const ModelPtr &model, size_t subgraphIndex, size_t operatorIndex)
#define CHECK_SUPPORTED_FUSED_ACTIVATION(OPTION, SUBGRAPH_INDEX, OPERATOR_INDEX)
int32_t m_Axis
The axis in params to gather indices from.
A ElementwiseUnaryDescriptor for the ElementwiseUnaryLayer.
PoolingAlgorithm m_PoolType
The pooling algorithm to use (Max. Average, L2).
uint32_t m_StrideY
Stride value when proceeding through input for the height dimension.
uint32_t m_StrideY
Stride value when proceeding through input for the height dimension.
std::vector< std::pair< unsigned int, unsigned int > > m_Crops
The values to crop from the input dimension.
uint32_t m_PadTop
Padding top value in the height dimension.
unsigned int GetNumDimensions() const
Function that returns the tensor rank.
OutputShapeRounding m_OutputShapeRounding
The rounding method for the output shape. (Floor, Ceiling).
constexpr char const * GetComparisonOperationAsCString(ComparisonOperation operation)
void SetConcatAxis(unsigned int concatAxis)
Set the concatenation axis value.
virtual const IInputSlot & GetInputSlot(unsigned int index) const =0
Get a const input slot handle by slot index.
A MeanDescriptor for the MeanLayer.
void SetConstant(const bool IsConstant=true)
Marks the data corresponding to this tensor info as constant.
armnn::BindingPointInfo BindingPointInfo
std::enable_if_t< std::is_unsigned< Source >::value &&std::is_unsigned< Dest >::value, Dest > numeric_cast(Source source)
armnn::TensorInfo ToTensorInfo(TensorRawPtr tensorPtr)
uint32_t m_PadRight
Padding right value in the width dimension.
A TransposeDescriptor for the TransposeLayer.
A StridedSliceDescriptor for the StridedSliceLayer.
virtual const IOutputSlot & GetOutputSlot(unsigned int index) const =0
Get the const output slot handle by slot index.
int m_Axis
Axis to reduce across the input tensor.
virtual const char * GetName() const =0
Returns the name of the layer.
float m_ScaleY
Center size encoding scale y.
float m_NmsScoreThreshold
NMS score threshold.
std::unique_ptr< INetwork, void(*)(INetwork *network)> INetworkPtr
virtual int Connect(IInputSlot &destination)=0
Krichevsky 2012: Local Brightness Normalization.
A Pooling2dDescriptor for the Pooling2dLayer.
A NormalizationDescriptor for the NormalizationLayer.
static armnn::TensorInfo OutputShapeOfSqueeze(std::vector< uint32_t > squeezeDims, const armnn::TensorInfo &inputTensorInfo)
std::vector< std::string > GetSubgraphInputTensorNames(size_t subgraphId) const
Return the input tensor names for a given subgraph.
unsigned int GetNumDimensions() const
#define CHECK_BUFFER_SIZE(BUFFER_PTR, TENSOR_INFO, BUFFER_ID)
uint32_t m_DilationZ
Dilation along z axis.
float m_B
Beta lower bound value used by the activation functions. (BoundedReLu, Linear, TanH).
armnn::TensorShape Permuted(const armnn::TensorShape &srcShape, const armnn::PermutationVector &mappings)
A SoftmaxDescriptor for the SoftmaxLayer.
float m_Beta
Beta value for the normalization equation.
uint32_t m_StrideZ
Stride value when proceeding through input for the depth dimension.
uint32_t m_NormSize
Depth radius value.
Status SetViewOriginCoord(uint32_t view, uint32_t coord, uint32_t value)
Set the view origin coordinates.
ActivationFunction m_Function
The activation function to use (Sigmoid, TanH, Linear, ReLu, BoundedReLu, SoftReLu, LeakyReLu, Abs, Sqrt, Square, Elu).
uint32_t m_StrideY
Stride value when proceeding through input for the height dimension.
A DepthwiseConvolution2dDescriptor for the DepthwiseConvolution2dLayer.
constexpr unsigned int MaxNumOfTensorDimensions
uint32_t m_DilationY
Dilation along y axis.
uint32_t m_PadLeft
Padding left value in the width dimension.
unsigned int GetNumElements() const
uint32_t m_PadRight
Padding right value in the width dimension.
bool m_ConstantWeights
Enable/disable constant weights and biases.