30 #include <schema_generated.h> 32 #include <flatbuffers/flexbuffers.h> 34 #include <fmt/format.h> 41 #define ARMNN_THROW_PARSE_EXCEPTION(msg) \ 43 throw armnn::ParseException( static_cast<const std::stringstream&>( std::stringstream() << msg \ 45 << CHECK_LOCATION().AsString()).str()); \ 48 using namespace armnn;
54 pTfLiteParserImpl(
new TfLiteParserImpl(options)) {}
56 ITfLiteParser::~ITfLiteParser() =
default;
78 armnn::INetworkPtr ITfLiteParser::CreateNetworkFromBinary(
const std::vector<uint8_t>& binaryContent)
80 return pTfLiteParserImpl->CreateNetworkFromBinary(binaryContent);
84 const std::string& name)
const 86 return pTfLiteParserImpl->GetNetworkInputBindingInfo(subgraphId, name);
90 const std::string& name)
const 92 return pTfLiteParserImpl->GetNetworkOutputBindingInfo(subgraphId, name);
95 size_t ITfLiteParser::GetSubgraphCount()
const 97 return pTfLiteParserImpl->GetSubgraphCount();
100 std::vector<std::string> ITfLiteParser::GetSubgraphInputTensorNames(
size_t subgraphId)
const 102 return pTfLiteParserImpl->GetSubgraphInputTensorNames(subgraphId);
105 std::vector<std::string> ITfLiteParser::GetSubgraphOutputTensorNames(
size_t subgraphId)
const 107 return pTfLiteParserImpl->GetSubgraphOutputTensorNames(subgraphId);
113 const uint32_t VIRTUAL_OPERATOR_ID = std::numeric_limits<uint32_t>::max();
116 size_t subgraphIndex,
119 if (model.get() ==
nullptr)
122 fmt::format(
"{} was called with invalid (null) model. " 123 "Possible reason is that the model is not yet loaded and Unpack(ed). " 129 else if (subgraphIndex >= model->subgraphs.size())
132 fmt::format(
"{} was called with an invalid subgraph index. " 140 #define CHECK_SUBGRAPH(MODEL, SUBGRAPH_INDEX) \ 141 CheckSubgraph(MODEL, SUBGRAPH_INDEX, CHECK_LOCATION()) 144 size_t subgraphIndex,
145 size_t operatorIndex,
148 if (model.get() ==
nullptr)
151 fmt::format(
"{} was called with invalid (null) model. " 152 "Possible reason is that the model is not yet loaded and Unpack(ed). " 153 "subgraph:{} operator:{} at {}",
159 else if (subgraphIndex >= model->subgraphs.size())
162 fmt::format(
"{} was called with an invalid subgraph index. " 163 "subgraph:{} operator:{} at {}",
169 else if (operatorIndex >= model->subgraphs[subgraphIndex]->operators.size() &&
170 operatorIndex != VIRTUAL_OPERATOR_ID)
173 fmt::format(
"{} was called with an invalid operator index. " 174 "subgraph:{} operator:{} at {}",
182 #define CHECK_MODEL(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX) \ 183 CheckModel(MODEL, SUBGRAPH_INDEX, OPERATOR_INDEX, CHECK_LOCATION()) 186 size_t subgraphIndex,
192 ARMNN_ASSERT_MSG(model.get() !=
nullptr,
"Expecting a valid model in this function");
196 ARMNN_ASSERT_MSG(subgraphIndex < model->subgraphs.size(),
"Expecting a valid subgraph index");
199 if (tensorIndex >= model->subgraphs[subgraphIndex]->tensors.size())
202 fmt::format(
"{} was called with an invalid tensor index. " 203 "subgraph:{} tensor:{} at {}",
211 #define CHECK_TENSOR(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX) \ 212 CheckTensor(MODEL, SUBGRAPH_INDEX, TENSOR_INDEX, CHECK_LOCATION()) 217 if (rawPtr ==
nullptr)
220 fmt::format(
"{} was called with a null tensor pointer at {}", location.
m_Function, location.
FileLine()));
224 #define CHECK_TENSOR_PTR(TENSOR_PTR) \ 225 CheckTensorPtr(TENSOR_PTR, CHECK_LOCATION()) 231 if (model.get() ==
nullptr)
234 fmt::format(
"{} was called with invalid (null) model. " 235 "Possible reason is that the model is not yet loaded and Unpack(ed). " 241 else if (bufferIndex >= model->buffers.size())
244 fmt::format(
"{} was called with an invalid buffer index. " 245 "buffer index:{} at {}",
250 else if (model->buffers[bufferIndex].get() ==
nullptr)
253 fmt::format(
"The buffer #{} is null. {}",
259 #define CHECK_BUFFER(MODEL, BUFFER_INDEX) \ 260 CheckBuffer(MODEL, BUFFER_INDEX, CHECK_LOCATION()) 262 void CheckBufferSize(TfLiteParserImpl::BufferRawPtr bufferPtr,
267 if (bufferPtr ==
nullptr)
270 fmt::format(
"BufferPtr is null for buffer:{}. {}",
277 std::stringstream ss;
278 ss <<
"Buffer #" << bufferId <<
" has " << bufferPtr->data.size() <<
" bytes. " 279 <<
"For tensor: " << tensorInfo.
GetShape()
280 <<
" expecting: " << tensorInfo.
GetNumBytes() <<
" bytes and " 289 const auto& operatorPtr = model->subgraphs[subgraphIndex]->operators[operatorIndex];
290 auto opcodeIndex = operatorPtr->opcode_index;
293 #if defined(ARMNN_POST_TFLITE_2_3) 294 auto opcode = std::max(model->operator_codes[opcodeIndex]->builtin_code,
295 static_cast<tflite::BuiltinOperator>(model->operator_codes[opcodeIndex]->deprecated_builtin_code));
297 auto opcode = model->operator_codes[opcodeIndex]->builtin_code;
306 TfLiteParserImpl::BufferRawPtr bufferPtr = TfLiteParserImpl::GetBuffer(model, bufferIndex);
311 ::memcpy(buffer.data(), bufferPtr->data.data(), bufferPtr->data.size());
316 ::memcpy(uint64Buffer.data(), bufferPtr->data.data(), bufferPtr->data.size());
317 buffer.assign(std::begin(uint64Buffer), std::end(uint64Buffer));
322 #define CHECK_BUFFER_SIZE(BUFFER_PTR, TENSOR_INFO, BUFFER_ID) \ 323 CheckBufferSize(BUFFER_PTR, TENSOR_INFO, BUFFER_ID, CHECK_LOCATION()) 327 switch(activationType)
329 case tflite::ActivationFunctionType_NONE:
330 case tflite::ActivationFunctionType_RELU:
331 case tflite::ActivationFunctionType_RELU6:
332 case tflite::ActivationFunctionType_TANH:
343 #define CHECK_SUPPORTED_FUSED_ACTIVATION(OPTION, SUBGRAPH_INDEX, OPERATOR_INDEX) \ 345 if (IsActivationSupported(OPTION->fused_activation_function) == false) \ 347 throw ParseException( \ 348 fmt::format("TfLite parser doesn't suppport fused activation: " \ 349 "{}/{} in {} subgraph:{} operator:{} at {}", \ 350 OPTION->fused_activation_function, \ 351 tflite::EnumNameActivationFunctionType(\ 352 OPTION->fused_activation_function), \ 356 CHECK_LOCATION().FileLine())); \ 361 std::vector<unsigned int> AsUnsignedVector(
const std::vector<int32_t>& in)
363 std::vector<unsigned int> result;
364 result.reserve(in.size());
377 bool IsOptionalOperandPresent(
int input)
382 void CalcPadding(uint32_t inputSize,
386 uint32_t& paddingFront,
387 uint32_t& paddingBack,
388 tflite::Padding padding)
392 if (padding == tflite::Padding_SAME)
394 uint32_t outputSize = (inputSize + stride - 1) / stride;
395 uint32_t dilatedSize = filterSize + (dilation - 1) * (filterSize - 1);
396 uint32_t temp = (outputSize - 1) * stride + dilatedSize;
397 if (temp > inputSize)
399 paddingFront = (temp - inputSize) / 2;
400 paddingBack = (temp - inputSize) - paddingFront;
406 const std::vector<unsigned int>& shape,
407 const bool outputTensor =
false)
412 switch (tensorPtr->type)
414 case tflite::TensorType_UINT8:
417 case tflite::TensorType_FLOAT32:
420 case tflite::TensorType_FLOAT16:
423 case tflite::TensorType_INT8:
424 if (tensorPtr->quantization->zero_point.size() == 1)
435 case tflite::TensorType_INT16:
438 case tflite::TensorType_INT32:
441 case tflite::TensorType_INT64:
444 case tflite::TensorType_BOOL:
451 fmt::format(
"Unsupported data type {} = {} for tensor: {}. {}",
453 tflite::EnumNameTensorType(tensorPtr->type),
460 std::vector<unsigned int> safeShape = shape;
461 if (shape.size() == 0)
463 safeShape.push_back(1);
468 tensorShape =
TensorShape(armnn::numeric_cast<unsigned int>(safeShape.size()), safeShape.data());
472 size_t shapeSignatureSize = tensorPtr->shape_signature.size();
475 if (shapeSignatureSize != 0)
478 if (shapeSignatureSize != shape.size())
482 for (
unsigned int i = 0; i < shapeSignatureSize; ++i)
484 unsigned int dim = tensorPtr->shape_signature[i] > -1 ?
485 static_cast<unsigned int>(tensorPtr->shape_signature[i]) : 0;
486 safeShape.push_back(dim);
490 std::unique_ptr<bool[]> dimMask = std::make_unique<bool[]>(tensorPtr->shape_signature.size());
491 for (
unsigned int i = 0; i < tensorPtr->shape_signature.size(); ++i)
493 dimMask[i] = tensorPtr->shape_signature[i] == -1 ? false :
true;
495 tensorShape =
TensorShape(static_cast<unsigned int>(safeShape.size()), safeShape.data(), dimMask.get());
498 else if (shape.size() == 0)
504 tensorShape =
TensorShape(armnn::numeric_cast<unsigned int>(shape.size()), shape.data());
508 float quantizationScale = 0.0f;
509 int32_t quantizationOffset = 0;
511 if (tensorPtr->quantization.get())
513 if (tensorPtr->quantization->scale.size() <= 1)
518 if (tensorPtr->quantization->scale.size() == 1)
520 quantizationScale = tensorPtr->quantization->scale[0];
522 if (tensorPtr->quantization->zero_point.size() == 1)
537 std::vector<float> quantizationScales;
538 std::vector<int32_t> quantizationOffsets;
541 std::copy(tensorPtr->quantization->scale.begin(),
542 tensorPtr->quantization->scale.end(),
543 std::back_inserter(quantizationScales));
549 armnn::numeric_cast<unsigned int>(tensorPtr->quantization->quantized_dimension));
565 auto const& dimensions = AsUnsignedVector(tensorPtr->shape);
570 const bool outputTensor)
572 auto const& dimensions = AsUnsignedVector(tensorPtr->shape);
573 return ToTensorInfo(tensorPtr, dimensions, outputTensor);
577 std::pair<armnn::ConstTensor, std::unique_ptr<T[]>>
586 fmt::format(
"Buffer for buffer:{} is null", tensorPtr->buffer).c_str());
594 reinterpret_cast<const T*
>(bufferPtr->data.data()), data.get(),
sizeof(T));
598 ::memcpy(data.get(), bufferPtr->data.data(), tensorInfo.
GetNumBytes());
604 return std::make_pair(
ConstTensor(tensorInfo, data.get()), std::move(data));
617 if (actualSize != expected.size())
622 for (
unsigned int i = 0u; i < actualSize; i++)
624 if (expected[i] < 0 ||
625 actual[i] != static_cast<unsigned int>(expected[i]))
634 void CheckMatchingQuantization(
const TensorInfo& first,
636 const std::string& descName,
637 std::string
const& firstName,
638 std::string
const& secondName)
650 if (firstDataType != secondDataType)
653 " must be of the same quantized type, " +
661 " must have the same quantization space, " +
673 , m_Network(nullptr, nullptr)
677 m_ParserFunctions[tflite::BuiltinOperator_ABS] = &TfLiteParserImpl::ParseAbs;
678 m_ParserFunctions[tflite::BuiltinOperator_ADD] = &TfLiteParserImpl::ParseAdd;
679 m_ParserFunctions[tflite::BuiltinOperator_ARG_MIN] = &TfLiteParserImpl::ParseArgMin;
680 m_ParserFunctions[tflite::BuiltinOperator_ARG_MAX] = &TfLiteParserImpl::ParseArgMax;
681 m_ParserFunctions[tflite::BuiltinOperator_AVERAGE_POOL_2D] = &TfLiteParserImpl::ParseAveragePool2D;
682 m_ParserFunctions[tflite::BuiltinOperator_BATCH_TO_SPACE_ND] = &TfLiteParserImpl::ParseBatchToSpaceND;
683 m_ParserFunctions[tflite::BuiltinOperator_CAST] = &TfLiteParserImpl::ParseCast;
684 m_ParserFunctions[tflite::BuiltinOperator_CONCATENATION] = &TfLiteParserImpl::ParseConcatenation;
685 m_ParserFunctions[tflite::BuiltinOperator_CONV_2D] = &TfLiteParserImpl::ParseConv2D;
687 #if defined(ARMNN_POST_TFLITE_2_3) 688 m_ParserFunctions[tflite::BuiltinOperator_CONV_3D] = &TfLiteParserImpl::ParseConv3D;
690 m_ParserFunctions[tflite::BuiltinOperator_CUSTOM] = &TfLiteParserImpl::ParseCustomOperator;
691 m_ParserFunctions[tflite::BuiltinOperator_DEPTH_TO_SPACE] = &TfLiteParserImpl::ParseDepthToSpace;
692 m_ParserFunctions[tflite::BuiltinOperator_DEPTHWISE_CONV_2D] = &TfLiteParserImpl::ParseDepthwiseConv2D;
693 m_ParserFunctions[tflite::BuiltinOperator_DEQUANTIZE] = &TfLiteParserImpl::ParseDequantize;
694 m_ParserFunctions[tflite::BuiltinOperator_DIV] = &TfLiteParserImpl::ParseDiv;
695 m_ParserFunctions[tflite::BuiltinOperator_ELU] = &TfLiteParserImpl::ParseElu;
696 m_ParserFunctions[tflite::BuiltinOperator_EQUAL] = &TfLiteParserImpl::ParseEqual;
697 m_ParserFunctions[tflite::BuiltinOperator_EXP] = &TfLiteParserImpl::ParseExp;
698 m_ParserFunctions[tflite::BuiltinOperator_EXPAND_DIMS] = &TfLiteParserImpl::ParseExpandDims;
699 m_ParserFunctions[tflite::BuiltinOperator_FLOOR_DIV] = &TfLiteParserImpl::ParseFloorDiv;
700 m_ParserFunctions[tflite::BuiltinOperator_FULLY_CONNECTED] = &TfLiteParserImpl::ParseFullyConnected;
701 m_ParserFunctions[tflite::BuiltinOperator_GATHER] = &TfLiteParserImpl::ParseGather;
702 m_ParserFunctions[tflite::BuiltinOperator_GATHER_ND] = &TfLiteParserImpl::ParseGatherNd;
703 m_ParserFunctions[tflite::BuiltinOperator_GREATER] = &TfLiteParserImpl::ParseGreater;
704 m_ParserFunctions[tflite::BuiltinOperator_GREATER_EQUAL] = &TfLiteParserImpl::ParseGreaterOrEqual;
705 m_ParserFunctions[tflite::BuiltinOperator_HARD_SWISH] = &TfLiteParserImpl::ParseHardSwish;
706 m_ParserFunctions[tflite::BuiltinOperator_LEAKY_RELU] = &TfLiteParserImpl::ParseLeakyRelu;
707 m_ParserFunctions[tflite::BuiltinOperator_LESS] = &TfLiteParserImpl::ParseLess;
708 m_ParserFunctions[tflite::BuiltinOperator_LESS_EQUAL] = &TfLiteParserImpl::ParseLessOrEqual;
709 m_ParserFunctions[tflite::BuiltinOperator_LOCAL_RESPONSE_NORMALIZATION]
710 = &TfLiteParserImpl::ParseLocalResponseNormalization;
711 m_ParserFunctions[tflite::BuiltinOperator_LOGICAL_NOT] = &TfLiteParserImpl::ParseLogicalNot;
712 m_ParserFunctions[tflite::BuiltinOperator_LOGISTIC] = &TfLiteParserImpl::ParseLogistic;
713 m_ParserFunctions[tflite::BuiltinOperator_L2_NORMALIZATION] = &TfLiteParserImpl::ParseL2Normalization;
714 m_ParserFunctions[tflite::BuiltinOperator_MAX_POOL_2D] = &TfLiteParserImpl::ParseMaxPool2D;
715 m_ParserFunctions[tflite::BuiltinOperator_MAXIMUM] = &TfLiteParserImpl::ParseMaximum;
716 m_ParserFunctions[tflite::BuiltinOperator_MEAN] = &TfLiteParserImpl::ParseMean;
717 m_ParserFunctions[tflite::BuiltinOperator_MINIMUM] = &TfLiteParserImpl::ParseMinimum;
718 m_ParserFunctions[tflite::BuiltinOperator_MIRROR_PAD] = &TfLiteParserImpl::ParseMirrorPad;
719 m_ParserFunctions[tflite::BuiltinOperator_MUL] = &TfLiteParserImpl::ParseMul;
720 m_ParserFunctions[tflite::BuiltinOperator_NEG] = &TfLiteParserImpl::ParseNeg;
721 m_ParserFunctions[tflite::BuiltinOperator_NOT_EQUAL] = &TfLiteParserImpl::ParseNotEqual;
722 m_ParserFunctions[tflite::BuiltinOperator_PACK] = &TfLiteParserImpl::ParsePack;
723 m_ParserFunctions[tflite::BuiltinOperator_PAD] = &TfLiteParserImpl::ParsePad;
724 m_ParserFunctions[tflite::BuiltinOperator_PADV2] = &TfLiteParserImpl::ParsePad;
725 m_ParserFunctions[tflite::BuiltinOperator_PRELU] = &TfLiteParserImpl::ParsePrelu;
726 m_ParserFunctions[tflite::BuiltinOperator_QUANTIZE] = &TfLiteParserImpl::ParseQuantize;
727 m_ParserFunctions[tflite::BuiltinOperator_RELU] = &TfLiteParserImpl::ParseRelu;
728 m_ParserFunctions[tflite::BuiltinOperator_RELU6] = &TfLiteParserImpl::ParseRelu6;
729 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MAX] = &TfLiteParserImpl::ParseReduceMax;
730 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_MIN] = &TfLiteParserImpl::ParseReduceMin;
731 m_ParserFunctions[tflite::BuiltinOperator_REDUCE_PROD] = &TfLiteParserImpl::ParseReduceProd;
732 m_ParserFunctions[tflite::BuiltinOperator_RESHAPE] = &TfLiteParserImpl::ParseReshape;
733 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_BILINEAR] = &TfLiteParserImpl::ParseResizeBilinear;
734 m_ParserFunctions[tflite::BuiltinOperator_RESIZE_NEAREST_NEIGHBOR] = &TfLiteParserImpl::ParseResizeNearestNeighbor;
735 m_ParserFunctions[tflite::BuiltinOperator_RSQRT] = &TfLiteParserImpl::ParseRsqrt;
736 m_ParserFunctions[tflite::BuiltinOperator_SQRT] = &TfLiteParserImpl::ParseSqrt;
737 m_ParserFunctions[tflite::BuiltinOperator_SHAPE] = &TfLiteParserImpl::ParseShape;
738 m_ParserFunctions[tflite::BuiltinOperator_SLICE] = &TfLiteParserImpl::ParseSlice;
739 m_ParserFunctions[tflite::BuiltinOperator_SOFTMAX] = &TfLiteParserImpl::ParseSoftmax;
740 m_ParserFunctions[tflite::BuiltinOperator_SPACE_TO_BATCH_ND] = &TfLiteParserImpl::ParseSpaceToBatchND;
741 m_ParserFunctions[tflite::BuiltinOperator_SPLIT] = &TfLiteParserImpl::ParseSplit;
742 m_ParserFunctions[tflite::BuiltinOperator_SPLIT_V] = &TfLiteParserImpl::ParseSplitV;
743 m_ParserFunctions[tflite::BuiltinOperator_SQUEEZE] = &TfLiteParserImpl::ParseSqueeze;
744 m_ParserFunctions[tflite::BuiltinOperator_STRIDED_SLICE] = &TfLiteParserImpl::ParseStridedSlice;
745 m_ParserFunctions[tflite::BuiltinOperator_SUB] = &TfLiteParserImpl::ParseSub;
746 m_ParserFunctions[tflite::BuiltinOperator_SUM] = &TfLiteParserImpl::ParseSum;
747 m_ParserFunctions[tflite::BuiltinOperator_TANH] = &TfLiteParserImpl::ParseTanH;
748 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE] = &TfLiteParserImpl::ParseTranspose;
749 m_ParserFunctions[tflite::BuiltinOperator_TRANSPOSE_CONV] = &TfLiteParserImpl::ParseTransposeConv;
750 m_ParserFunctions[tflite::BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_LSTM]
751 = &TfLiteParserImpl::ParseUnidirectionalSequenceLSTM;
752 m_ParserFunctions[tflite::BuiltinOperator_UNPACK] = &TfLiteParserImpl::ParseUnpack;
755 m_CustomParserFunctions[
"TFLite_Detection_PostProcess"] = &TfLiteParserImpl::ParseDetectionPostProcess;
758 void TfLiteParserImpl::ResetParser()
762 m_SubgraphConnections.clear();
763 m_OverridenOutputShapes.clear();
764 m_ConstantsToDequantize.clear();
765 m_ConstantsToBeCreated.clear();
772 return CreateNetworkFromModel();
779 return CreateNetworkFromModel();
786 m_Model = std::move(model);
788 return CreateNetworkFromModel();
791 INetworkPtr TfLiteParserImpl::CreateNetworkFromModel()
798 if (m_Options.value().m_InferAndValidate)
802 {
"InferAndValidate",
true }
805 networkOptions.push_back(shapeInferenceMethodOption);
807 if (m_Options.value().m_AllowExpandedDims)
811 {
"AllowExpandedDims",
true }
814 networkOptions.push_back(shapeInferenceMethodOption);
817 m_Network = INetwork::Create(networkOptions);
820 if (m_Model->subgraphs.size() != 1)
823 fmt::format(
"Current TfLite parser only supports 1 subgraph. Current one has: {} {}",
824 m_Model->subgraphs.size(),
828 size_t subgraphIndex = 0;
829 size_t operatorIndex = 0;
832 for (
SubgraphPtr const& subgraph : m_Model->subgraphs)
834 m_SubgraphConnections.emplace_back(subgraph->tensors.size());
837 auto const& opCodePtr = m_Model->operator_codes[op->opcode_index];
840 #if defined(ARMNN_POST_TFLITE_2_3) 841 auto builtinCode = std::max(opCodePtr->builtin_code,
842 static_cast<tflite::BuiltinOperator>(opCodePtr->deprecated_builtin_code));
844 auto builtinCode = opCodePtr->builtin_code;
847 if (builtinCode > tflite::BuiltinOperator_MAX)
849 throw ParseException(fmt::format(
"Operator code {} is out of range 0-{}. " 850 "subgraph:{} operator idx:{}. {}",
851 builtinCode, tflite::BuiltinOperator_MAX, subgraphIndex,
856 auto& parserFunction = m_ParserFunctions[builtinCode];
857 (this->*parserFunction)(subgraphIndex, operatorIndex);
861 SetupInputLayers(subgraphIndex);
862 SetupOutputLayers(subgraphIndex);
863 SetupConstantLayers(subgraphIndex);
871 std::stringstream errorString;
872 errorString <<
"Failed to parse operator #" << operatorIndex <<
" within subgraph #" 873 << subgraphIndex <<
" error: " << e.
what();
875 std::stringstream errors;
876 errors << errorString.str() <<
"\n";
881 for (subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
883 for (
size_t tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
885 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot !=
nullptr)
887 for (
size_t inputSlotIdx = 0;
888 inputSlotIdx < m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size();
891 m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot->Connect(
892 *(m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots[inputSlotIdx]));
897 return std::move(m_Network);
906 std::unique_ptr<float[]> buffer(
new float[tensorInfo.
GetNumElements()]);
911 auto axisDimensionality = tensorInfo.
GetShape()[axis];
916 unsigned int axisIndex = (i / axisFactor) % axisDimensionality;
932 fmt::format(
"Unsupported input/weights combination: Input {} not supported with Weights {}",
938 void TfLiteParserImpl::RegisterProducerOfTensor(
size_t subgraphIndex,
943 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
944 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
946 TensorSlots & tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
949 if (tensorSlots.outputSlot !=
nullptr)
951 throw ParseException(fmt::format(
"Another layer has already registered itself as the producer of " 952 "subgraph:{} tensor:{} {}",
958 tensorSlots.outputSlot = slot;
961 void TfLiteParserImpl::RegisterConsumerOfTensor(
size_t subgraphIndex,
966 ARMNN_ASSERT(m_SubgraphConnections.size() > subgraphIndex);
967 ARMNN_ASSERT(m_SubgraphConnections[subgraphIndex].size() > tensorIndex);
969 TensorSlots& tensorSlots = m_SubgraphConnections[subgraphIndex][tensorIndex];
970 tensorSlots.inputSlots.push_back(slot);
973 void TfLiteParserImpl::ParseCustomOperator(
size_t subgraphIndex,
size_t operatorIndex)
975 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
978 auto customParserFunction = &TfLiteParserImpl::ParseUnsupportedOperator;
981 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
982 const auto& customCode = m_Model->operator_codes[operatorPtr->opcode_index]->custom_code;
985 auto iterator = m_CustomParserFunctions.find(customCode);
986 if (iterator != m_CustomParserFunctions.end())
988 customParserFunction = iterator->second;
992 (this->*customParserFunction)(subgraphIndex, operatorIndex);
995 void TfLiteParserImpl::ParseUnsupportedOperator(
size_t subgraphIndex,
size_t operatorIndex)
997 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
999 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1001 auto opcodeIndex = operatorPtr->opcode_index;
1004 #if defined(ARMNN_POST_TFLITE_2_3) 1005 auto opcode = std::max(m_Model->operator_codes[opcodeIndex]->builtin_code,
1006 static_cast<tflite::BuiltinOperator>(m_Model->operator_codes[opcodeIndex]->deprecated_builtin_code));
1008 auto opcode = m_Model->operator_codes[opcodeIndex]->builtin_code;
1011 if (!m_Options || !m_Options.value().m_StandInLayerForUnsupported)
1015 fmt::format(
"Operator not supported. " 1016 "subgraph:{} operator:{} " 1017 "opcode_index:{} opcode:{} / {} {}",
1022 tflite::EnumNameBuiltinOperator(opcode),
1026 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1027 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1033 auto layerName = fmt::format(
"StandIn:{}:{}:{}", subgraphIndex, operatorIndex, opcode);
1036 IConnectableLayer* layer = m_Network->AddStandInLayer(descriptor, layerName.c_str());
1039 for (
unsigned int i = 0u; i < numOutputs; ++i)
1044 auto inputTensorIds = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1045 auto outputTensorIds = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1047 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIds);
1048 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIds);
1051 void TfLiteParserImpl::ParseCast(
size_t subgraphIndex,
size_t operatorIndex)
1053 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1055 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1057 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1060 auto layerName = fmt::format(
"Cast:{}:{}", subgraphIndex, operatorIndex);
1068 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1069 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1071 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1072 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1075 void TfLiteParserImpl::ParseConv2D(
size_t subgraphIndex,
size_t operatorIndex)
1077 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1079 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1080 const auto* options = operatorPtr->builtin_options.AsConv2DOptions();
1084 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1085 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1089 inputs.size() == 3 ?
1101 unsigned int inputHeight = inputTensorInfo.
GetShape()[1];
1102 unsigned int inputWidth = inputTensorInfo.
GetShape()[2];
1106 unsigned int filterHeight = filterTensorInfo.
GetShape()[1];
1107 unsigned int filterWidth = filterTensorInfo.
GetShape()[2];
1109 CalcPadding(inputHeight, filterHeight, desc.m_StrideY,
1110 desc.m_DilationY, desc.m_PadTop, desc.m_PadBottom, options->padding);
1111 CalcPadding(inputWidth, filterWidth, desc.m_StrideX,
1112 desc.m_DilationX, desc.m_PadLeft, desc.m_PadRight, options->padding);
1116 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1117 std::vector<unsigned int> tensorIndexesToRegister = { inputTensorIndexes[0], inputTensorIndexes[1] };
1119 auto layerName = fmt::format(
"Conv2D:{}:{}", subgraphIndex, operatorIndex);
1122 if (IsConstTensor(inputs[1]) && inputTensorInfo.
GetDataType() == DataType::Float32 &&
1123 (filterTensorInfo.
GetDataType() == DataType::QAsymmU8 ||
1124 filterTensorInfo.
GetDataType() == DataType::QAsymmS8))
1126 m_ConstantsToDequantize.emplace_back(inputs[1]->buffer);
1129 if (desc.m_BiasEnabled)
1134 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
1136 if (IsConstTensor(inputs[2]) && inputTensorInfo.
GetDataType() == DataType::Float32 &&
1137 (filterTensorInfo.
GetDataType() == DataType::QAsymmU8 ||
1138 filterTensorInfo.
GetDataType() == DataType::QAsymmS8))
1140 m_ConstantsToDequantize.emplace_back(inputs[2]->buffer);
1151 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
1153 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1155 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1156 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, { outputTensorIndexes[0] });
1160 #if defined(ARMNN_POST_TFLITE_2_3) 1161 void TfLiteParserImpl::ParseConv3D(
size_t subgraphIndex,
size_t operatorIndex)
1163 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1165 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1166 const auto* options = operatorPtr->builtin_options.AsConv3DOptions();
1180 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1183 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1190 unsigned int inputDepth = inputTensorInfo.GetShape()[1];
1191 unsigned int inputHeight = inputTensorInfo.GetShape()[2];
1192 unsigned int inputWidth = inputTensorInfo.GetShape()[3];
1195 unsigned int filterDepth = filterTensorInfo.
GetShape()[0];
1196 unsigned int filterHeight = filterTensorInfo.
GetShape()[1];
1197 unsigned int filterWidth = filterTensorInfo.
GetShape()[2];
1199 CalcPadding(inputDepth, filterDepth, desc.
m_StrideZ,
1201 CalcPadding(inputHeight, filterHeight, desc.
m_StrideY,
1203 CalcPadding(inputWidth, filterWidth, desc.
m_StrideX,
1206 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo, inputTensorInfo.
GetDataType());
1208 auto layerName = fmt::format(
"Conv3D:{}:{}", subgraphIndex, operatorIndex);
1210 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1213 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1215 if (inputs.size() == 3)
1220 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
1230 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
1232 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1234 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1235 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1239 void TfLiteParserImpl::ParseDepthwiseConv2D(
size_t subgraphIndex,
size_t operatorIndex)
1241 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1243 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1244 const auto* options = operatorPtr->builtin_options.AsDepthwiseConv2DOptions();
1254 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1256 if (inputs.size() == 3)
1261 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1270 unsigned int inputHeight = inputTensorInfo.
GetShape()[1];
1271 unsigned int inputWidth = inputTensorInfo.
GetShape()[2];
1274 unsigned int filterHeight = filterTensorInfo.
GetShape()[1];
1275 unsigned int filterWidth = filterTensorInfo.
GetShape()[2];
1277 CalcPadding(inputHeight, filterHeight, desc.
m_StrideY,
1279 CalcPadding(inputWidth, filterWidth, desc.
m_StrideX,
1283 auto layerName = fmt::format(
"DepthwiseConv2D:{}:{}", subgraphIndex, operatorIndex);
1285 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1288 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0], inputTensorIndexes[1]};
1298 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
1307 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister);
1309 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1311 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1312 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1315 void TfLiteParserImpl::ParseDequantize(
size_t subgraphIndex,
size_t operatorIndex)
1317 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1319 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1322 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1325 auto layerName = fmt::format(
"Dequantize:{}:{}", subgraphIndex, operatorIndex);
1333 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1334 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1336 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1337 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
1340 void TfLiteParserImpl::ParseExpandDims(
size_t subgraphIndex,
size_t operatorIndex)
1342 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1344 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1347 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1350 auto layerName = fmt::format(
"ExpandDims:{}:{}", subgraphIndex, operatorIndex);
1355 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1365 int32_t axis = inputs[1]->shape[0];
1369 if (axis > inputDimSize || axis < 0 - (inputDimSize + 1))
1371 throw ParseException(
"axis must be in range [0 - (inputDimSize + 1), inputDimSize] inclusive");
1376 axis = inputDimSize + axis + 1;
1379 std::vector<unsigned int> shape(static_cast<unsigned int>(inputDimSize) + 1);
1380 unsigned int inputShapeIndex = 0;
1381 for (
unsigned int i = 0; i < static_cast<unsigned int>(inputDimSize + 1); ++i)
1383 if (i == static_cast<unsigned int>(axis))
1389 shape[i] = inputTensorInfo.
GetShape()[inputShapeIndex];
1397 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
1399 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1401 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1402 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1404 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1405 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1408 void TfLiteParserImpl::ParseTranspose(
size_t subgraphIndex,
size_t operatorIndex)
1410 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1412 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1415 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1418 auto layerName = fmt::format(
"Transpose:{}:{}", subgraphIndex, operatorIndex);
1421 if (inputs.size() == 2)
1426 std::vector<unsigned int> permuteShape(numPermVecElements);
1427 ::memcpy(permuteShape.data(), permuteBufferPtr->data.data(), permuteTensorInfo.
GetNumBytes());
1435 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1437 IConnectableLayer* layer = m_Network->AddTransposeLayer(desc, layerName.c_str());
1441 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1442 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1444 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1445 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1448 void TfLiteParserImpl::ParseTransposeConv(
size_t subgraphIndex,
size_t operatorIndex)
1450 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1452 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1453 const auto* options = operatorPtr->builtin_options.AsTransposeConvOptions();
1461 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1462 if (inputs.size() == 4)
1471 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1478 if (tensorInfo.
GetDataType() == DataType::Signed32)
1480 ::memcpy(output_shape.data(),
GetBuffer(m_Model, inputs[0]->buffer)->data.data(), tensorInfo.
GetNumBytes());
1482 if (tensorInfo.
GetDataType() == DataType::QAsymmU8)
1486 output_shape[i] =
GetBuffer(m_Model, inputs[0]->buffer)->data.data()[i];
1490 for (
int dimension : output_shape)
1492 desc.
m_OutputShape.push_back(static_cast<unsigned int>(dimension));
1500 const unsigned int inputHeight = inputTensorInfo.
GetShape()[1];
1501 const unsigned int inputWidth = inputTensorInfo.
GetShape()[2];
1503 const unsigned int filterHeight = filterTensorInfo.
GetShape()[1];
1504 const unsigned int filterWidth = filterTensorInfo.
GetShape()[2];
1506 CalcPadding(inputHeight,
1514 CalcPadding(inputWidth,
1522 auto filterTensorAndData = CreateConstTensorNonPermuted(inputs[1], filterTensorInfo, inputTensorInfo.
GetDataType());
1525 auto layerName = fmt::format(
"TransposeConv:{}:{}", subgraphIndex, operatorIndex);
1530 auto biasConstTensor = CreateConstTensorNonPermuted(inputs[3], biasTensorInfo, inputTensorInfo.
GetDataType());
1531 layer = m_Network->AddTransposeConvolution2dLayer(desc,
1532 filterTensorAndData.first,
1533 biasConstTensor.first,
1538 layer = m_Network->AddTransposeConvolution2dLayer(desc,
1539 filterTensorAndData.first,
1547 layer->GetOutputSlot(0).SetTensorInfo(outputTensorInfo);
1550 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1551 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[2]});
1553 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1554 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1557 void TfLiteParserImpl::ParseAveragePool2D(
size_t subgraphIndex,
size_t operatorIndex)
1559 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Average);
1562 void TfLiteParserImpl::ParseBatchToSpaceND(
size_t subgraphIndex,
size_t operatorIndex)
1564 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1566 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1569 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1578 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1579 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1581 std::vector<unsigned int> cropsVector(cropsTensorInfo.
GetNumElements());
1582 ::memcpy(cropsVector.data(), cropsBufferPtr->data.data(), cropsTensorInfo.
GetNumBytes());
1585 std::vector<std::pair<unsigned int, unsigned int>> crops;
1586 for (
unsigned int i = 0; i < cropsTensorInfo.
GetNumElements() / step; ++i)
1588 crops.emplace_back(cropsVector[i * step], cropsVector[i * step + 1]);
1596 auto layerName = fmt::format(
"BatchToSpaceND:{}:{}", subgraphIndex, operatorIndex);
1600 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1602 IConnectableLayer* layer = m_Network->AddBatchToSpaceNdLayer(desc, layerName.c_str());
1606 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1607 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1609 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1610 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1613 void TfLiteParserImpl::ParseL2Normalization(
size_t subgraphIndex,
size_t operatorIndex)
1615 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1617 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1620 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1625 auto layerName = fmt::format(
"L2Normalization:{}:{}", subgraphIndex, operatorIndex);
1626 IConnectableLayer* layer = m_Network->AddL2NormalizationLayer(desc, layerName.c_str());
1633 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1634 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1636 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1637 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1640 void TfLiteParserImpl::ParseMaxPool2D(
size_t subgraphIndex,
size_t operatorIndex)
1642 ParsePool(subgraphIndex, operatorIndex, PoolingAlgorithm::Max);
1645 void TfLiteParserImpl::ParseMaximum(
size_t subgraphIndex,
size_t operatorIndex)
1647 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1649 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1652 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1655 auto layerName = fmt::format(
"Maximum:{}:{}", subgraphIndex, operatorIndex);
1659 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName,
"Input 0",
"Input 1");
1662 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1668 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1669 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1671 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1672 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1675 void TfLiteParserImpl::ParseMinimum(
size_t subgraphIndex,
size_t operatorIndex)
1677 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1679 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1682 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1685 auto layerName = fmt::format(
"Minimum:{}:{}", subgraphIndex, operatorIndex);
1689 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerName,
"Input 0",
"Input 1");
1692 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1698 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1699 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
1701 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1702 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1705 void TfLiteParserImpl::ParsePool(
size_t subgraphIndex,
1706 size_t operatorIndex,
1709 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1711 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1712 const auto* options = operatorPtr->builtin_options.AsPool2DOptions();
1716 std::string layerName;
1720 case PoolingAlgorithm::Average:
1722 fmt::format(
"AveragePool2D:{}:{}", subgraphIndex, operatorIndex);
1724 case PoolingAlgorithm::Max:
1726 fmt::format(
"MaxPool2D:{}:{}", subgraphIndex, operatorIndex);
1743 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1748 unsigned int inputHeight = inputTensorInfo.GetShape()[1];
1749 unsigned int inputWidth = inputTensorInfo.GetShape()[2];
1756 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1760 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1762 IConnectableLayer* layer = m_Network->AddPooling2dLayer(desc, layerName.c_str());
1768 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1769 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1771 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
1773 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1774 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1777 void TfLiteParserImpl::ParseSlice(
size_t subgraphIndex,
size_t operatorIndex)
1779 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1781 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1783 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1792 std::vector<unsigned int> begin(beginTensorInfo.
GetNumElements());
1793 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.
GetNumBytes());
1799 std::vector<int> signedSize(sizeTensorInfo.GetNumElements());
1800 ::memcpy(signedSize.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
1801 std::vector<unsigned int> size(sizeTensorInfo.GetNumElements());
1804 for (
unsigned int i = 0; i < signedSize.size(); ++i)
1806 int signedValue = signedSize[i];
1808 if (signedValue < -1 || signedValue > static_cast<int>(inputTensorInfo.GetShape()[i] - begin[i]))
1810 throw ParseException(fmt::format(
"Invalid value for size {} size must be in range " 1811 "[-1, inputDimSize - begin] [-1, {}] inclusive {}",
1813 inputTensorInfo.GetShape()[i] - begin[i],
1817 if (signedValue == -1)
1819 size[i] = inputTensorInfo.GetShape()[i] - begin[i];
1823 size[i] =
static_cast<unsigned int>(signedValue);
1829 auto layerName = fmt::format(
"Slice:{}:{}", subgraphIndex, operatorIndex);
1832 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1834 IConnectableLayer*
const layer = m_Network->AddSliceLayer(desc, layerName.c_str());
1839 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1840 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1843 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1844 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1847 void TfLiteParserImpl::ParseSoftmax(
size_t subgraphIndex,
size_t operatorIndex)
1849 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1850 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
1851 const auto* options = operatorPtr->builtin_options.AsSoftmaxOptions();
1854 desc.
m_Beta = options->beta;
1856 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1858 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1861 auto layerName = fmt::format(
"Softmax:{}:{}", subgraphIndex, operatorIndex);
1862 IConnectableLayer*
const layer = m_Network->AddSoftmaxLayer(desc, layerName.c_str());
1869 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1870 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1873 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1874 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1877 void TfLiteParserImpl::ParseSpaceToBatchND(
size_t subgraphIndex,
size_t operatorIndex)
1879 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1881 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1884 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1893 std::vector<unsigned int> blockShape(blockShapeTensorInfo.GetNumElements());
1894 ::memcpy(blockShape.data(), blockShapeBufferPtr->data.data(), blockShapeTensorInfo.GetNumBytes());
1896 std::vector<unsigned int> padListVector(padListTensorInfo.
GetNumElements());
1897 ::memcpy(padListVector.data(), padListBufferPtr->data.data(), padListTensorInfo.
GetNumBytes());
1900 std::vector<std::pair<unsigned int, unsigned int>> padList;
1901 for (
unsigned int i = 0; i < padListTensorInfo.
GetNumElements() / step; ++i)
1903 padList.emplace_back(padListVector[i * step], padListVector[i * step + 1]);
1911 auto layerName = fmt::format(
"SpaceToBatchND:{}:{}", subgraphIndex, operatorIndex);
1915 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
1917 IConnectableLayer* layer = m_Network->AddSpaceToBatchNdLayer(desc, layerName.c_str());
1921 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
1922 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
1924 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
1925 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
1932 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
1936 std::stringstream ss;
1937 ss <<
"Input tensor has unexpected number of dimensions:" << inputTensorInfo.
GetNumDimensions()
1938 <<
" shape:" << inputTensorInfo.
GetShape() <<
" " 1943 if (squeezeDims.empty())
1945 squeezeDims.assign(dimensionSequence,
1949 std::vector<uint32_t> outputDims;
1952 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
1953 auto currentDimension = inputTensorInfo.
GetShape()[i];
1954 if (skipSqueeze || currentDimension != 1)
1956 outputDims.push_back(currentDimension);
1960 if (outputDims.size() > 4)
1962 std::stringstream ss;
1963 ss <<
"Output tensor has unexpected number of dimensions:" << inputTensorInfo.
GetNumDimensions()
1964 <<
" shape:" << inputTensorInfo.
GetShape() <<
" " 1976 return outTensorInfo;
1979 void TfLiteParserImpl::ParseShape(
size_t subgraphIndex,
size_t operatorIndex)
1981 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
1983 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
1985 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
1988 auto layerName = fmt::format(
"Shape:{}:{}", subgraphIndex, operatorIndex);
2003 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
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);
2014 void TfLiteParserImpl::ParseSqueeze(
size_t subgraphIndex,
size_t operatorIndex)
2016 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2018 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2021 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2024 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2025 const auto * options = operatorPtr->builtin_options.AsSqueezeOptions();
2026 auto layerName = fmt::format(
"Squeeze:{}:{}", subgraphIndex, operatorIndex);
2030 std::vector<uint32_t> squeezeDim;
2033 if (options->squeeze_dims.size() == 1 && options->squeeze_dims[0] < 0)
2036 squeezeDim.push_back(static_cast<uint32_t>(dim));
2040 squeezeDim = AsUnsignedVector(options->squeeze_dims);
2045 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
2050 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
2054 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2055 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2057 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2058 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2061 void TfLiteParserImpl::ParseStridedSlice(
size_t subgraphIndex,
size_t operatorIndex)
2063 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2065 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2068 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2071 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2072 const auto* options = operatorPtr->builtin_options.AsStridedSliceOptions();
2086 ::memcpy(begin.data(), beginBufferPtr->data.data(), beginTensorInfo.
GetNumBytes());
2091 std::vector<int> end(endTensorInfo.GetNumElements());
2092 ::memcpy(end.data(), endBufferPtr->data.data(), endTensorInfo.GetNumBytes());
2097 std::vector<int> stride(strideTensorInfo.GetNumElements());
2098 ::memcpy(stride.data(), strideBufferPtr->data.data(), strideTensorInfo.GetNumBytes());
2104 auto layerName = fmt::format(
"StridedSlice:{}:{}", subgraphIndex, operatorIndex);
2105 IConnectableLayer* layer = m_Network->AddStridedSliceLayer(desc, layerName.c_str());
2111 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2112 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2114 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2115 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2118 void TfLiteParserImpl::ParseSub(
size_t subgraphIndex,
size_t operatorIndex)
2120 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2122 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2123 const auto* options = operatorPtr->builtin_options.AsSubOptions();
2125 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2128 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2134 auto layerName = fmt::format(
"Sub:{}:{}", subgraphIndex, operatorIndex);
2141 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2142 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2144 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2146 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2147 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2150 void TfLiteParserImpl::ParseDiv(
size_t subgraphIndex,
size_t operatorIndex)
2152 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2154 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2155 const auto* options = operatorPtr->builtin_options.AsDivOptions();
2157 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2160 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2166 auto layerName = fmt::format(
"Div:{}:{}", subgraphIndex, operatorIndex);
2173 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2174 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2175 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2177 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2178 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2181 void TfLiteParserImpl::ParseFloorDiv(
size_t subgraphIndex,
size_t operatorIndex)
2183 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2185 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2188 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2194 auto layerName = fmt::format(
"Div:{}:{}", subgraphIndex, operatorIndex);
2201 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2202 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2203 layer = AddFusedFloorLayer(layer, 0);
2205 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2206 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2209 void TfLiteParserImpl::ParseAdd(
size_t subgraphIndex,
size_t operatorIndex)
2211 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2213 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2214 const auto* options = operatorPtr->builtin_options.AsAddOptions();
2216 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2219 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2225 auto layerName = fmt::format(
"Add:{}:{}", subgraphIndex, operatorIndex);
2232 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2233 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2234 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2236 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2237 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2240 void TfLiteParserImpl::ParseMul(
size_t subgraphIndex,
size_t operatorIndex)
2242 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2244 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2245 const auto* options = operatorPtr->builtin_options.AsMulOptions();
2247 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2250 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2256 auto layerName = fmt::format(
"Mul:{}:{}", subgraphIndex, operatorIndex);
2257 IConnectableLayer* layer = m_Network->AddMultiplicationLayer(layerName.c_str());
2263 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2264 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
2265 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2267 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2268 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2271 void TfLiteParserImpl::ParseMean(
size_t subgraphIndex,
size_t operatorIndex)
2273 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2275 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2277 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2284 std::vector<unsigned int> axis(dimTensorInfo.GetNumElements());
2285 ::memcpy(axis.data(), bufferPtr->data.data(), dimTensorInfo.GetNumBytes());
2295 auto layerName = fmt::format(
"Mean:{}:{}", subgraphIndex, operatorIndex);
2301 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2302 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2304 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2305 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2308 void TfLiteParserImpl::ParsePad(
size_t subgraphIndex,
size_t operatorIndex)
2310 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2320 std::vector<unsigned int> padBuffer = GetUIntBuffer(padTensorInfo, m_Model, inputs[1]->buffer);
2324 auto opcode = GetOpCode(m_Model, subgraphIndex, operatorIndex);
2326 if (opcode == tflite::BuiltinOperator_PAD)
2330 if (inputTensorInfo.IsQuantized())
2332 desc.
m_PadValue =
static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2335 else if (opcode == tflite::BuiltinOperator_PADV2)
2341 if (padValueTensorInfo.GetNumElements() != 1)
2348 if (padValueBufferPtr->data.size() > 0)
2350 switch (padValueTensorInfo.GetDataType())
2354 std::vector<float> padValueBuffer(padValueTensorInfo.GetNumElements());
2355 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2361 std::vector<uint8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2362 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2363 desc.
m_PadValue = armnn::Dequantize<uint8_t>(padValueBuffer[0],
2364 padValueTensorInfo.GetQuantizationScale(),
2365 padValueTensorInfo.GetQuantizationOffset());
2371 std::vector<int8_t> padValueBuffer(padValueTensorInfo.GetNumElements());
2372 ::memcpy(padValueBuffer.data(), padValueBufferPtr->data.data(), padValueBufferPtr->data.size());
2373 desc.
m_PadValue = armnn::Dequantize<int8_t>(padValueBuffer[0],
2374 padValueTensorInfo.GetQuantizationScale(),
2375 padValueTensorInfo.GetQuantizationOffset());
2381 else if (inputTensorInfo.IsQuantized())
2383 desc.
m_PadValue =
static_cast<float>(inputTensorInfo.GetQuantizationOffset());
2387 for (
unsigned int i = 0; i < padTensorInfo.
GetNumElements() / step; ++i)
2389 desc.
m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2392 auto layerName = (opcode == tflite::BuiltinOperator_PAD) ? fmt::format(
"Pad:{}:{}", subgraphIndex, operatorIndex)
2393 : fmt::format(
"PadV2:{}:{}", subgraphIndex, operatorIndex);
2400 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2401 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2403 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2404 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2407 void TfLiteParserImpl::ParseMirrorPad(
size_t subgraphIndex,
size_t operatorIndex)
2409 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2422 std::vector<unsigned int> padBuffer(padTensorInfo.
GetNumElements());
2423 ::memcpy(padBuffer.data(), bufferPtr->data.data(), padTensorInfo.
GetNumBytes());
2427 for (
unsigned int i = 0; i < padTensorInfo.
GetNumElements() / step; ++i)
2429 desc.
m_PadList.emplace_back(padBuffer[i * step], padBuffer[i * step + 1]);
2432 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2433 const auto* options = operatorPtr->builtin_options.AsMirrorPadOptions();
2435 if (options->mode == tflite::MirrorPadMode_REFLECT)
2439 else if (options->mode == tflite::MirrorPadMode_SYMMETRIC)
2450 auto inputShape = inputTensorInfo.GetShape();
2453 const unsigned int isReflect =
static_cast<unsigned int>(desc.
m_PaddingMode == PaddingMode::Reflect);
2454 for(
unsigned int i = 0; i < padList.size(); ++i)
2456 if(padList.at(i).first > (inputShape[i] - isReflect) ||
2457 padList.at(i).second > (inputShape[i] - isReflect))
2460 "equal (Symmetric) to the dimension size.");
2464 auto layerName = fmt::format(
"MirrorPad:{}:{}", subgraphIndex, operatorIndex);
2471 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2472 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2474 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2475 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2478 void TfLiteParserImpl::ParsePrelu(
size_t subgraphIndex,
size_t operatorIndex)
2480 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2482 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2485 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2488 auto layerName = fmt::format(
"Prelu:{}:{}", subgraphIndex, operatorIndex);
2493 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
2499 if (IsConstTensor(inputs[1]))
2501 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2503 RegisterConsumerOfTensor(subgraphIndex, inputTensorIndexes[0], slot);
2505 auto alphaTensorAndData = CreateConstTensorNonPermuted(inputs[1], alphaTensorInfo,
2507 std::string constLayerName = fmt::format(
"Constant:{}", inputs[1]->name);
2509 m_Network->AddConstantLayer(alphaTensorAndData.first, constLayerName.c_str());
2514 RegisterOutputSlots(subgraphIndex,
2515 VIRTUAL_OPERATOR_ID,
2517 { inputTensorIndexes[1] });
2521 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2522 RegisterInputSlots(subgraphIndex, operatorIndex, layer, inputTensorIndexes);
2525 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2526 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2529 void TfLiteParserImpl::ParseQuantize(
size_t subgraphIndex,
size_t operatorIndex)
2531 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2533 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2536 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2539 auto layerName = fmt::format(
"Quantize:{}:{}", subgraphIndex, operatorIndex);
2547 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2548 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2550 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2551 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2554 void TfLiteParserImpl::ParseRelu(
size_t subgraphIndex,
size_t operatorIndex)
2556 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::ReLu);
2559 void TfLiteParserImpl::ParseRelu6(
size_t subgraphIndex,
size_t operatorIndex)
2561 ParseActivation(subgraphIndex,operatorIndex, ActivationFunction::BoundedReLu);
2564 void TfLiteParserImpl::ParseLeakyRelu(
size_t subgraphIndex,
size_t operatorIndex)
2566 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::LeakyReLu);
2569 void TfLiteParserImpl::ParseLogistic(
size_t subgraphIndex,
size_t operatorIndex)
2571 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::Sigmoid);
2574 void TfLiteParserImpl::ParseTanH(
size_t subgraphIndex,
size_t operatorIndex)
2576 ParseActivation(subgraphIndex,operatorIndex,ActivationFunction::TanH);
2579 void TfLiteParserImpl::ParseElu(
size_t subgraphIndex,
size_t operatorIndex)
2581 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::Elu);
2584 void TfLiteParserImpl::ParseHardSwish(
size_t subgraphIndex,
size_t operatorIndex)
2586 ParseActivation(subgraphIndex, operatorIndex, ActivationFunction::HardSwish);
2589 void TfLiteParserImpl::ParseActivation(
size_t subgraphIndex,
size_t operatorIndex,
ActivationFunction activationType)
2591 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2592 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2595 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2598 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2601 auto layerName = fmt::format(
"Activation:");
2605 switch (activationType)
2607 case ActivationFunction::ReLu:
2609 layerName += fmt::format(
"RELU:{}:{}", subgraphIndex, operatorIndex);
2612 case ActivationFunction::BoundedReLu:
2614 layerName += fmt::format(
"RELU6:{}:{}", subgraphIndex, operatorIndex);
2615 activationDesc.
m_A = 6.0f;
2616 activationDesc.
m_B = 0.0f;
2619 case ActivationFunction::Sigmoid:
2621 layerName += fmt::format(
"SIGMOID:{}:{}", subgraphIndex, operatorIndex);
2624 case ActivationFunction::TanH:
2626 layerName += fmt::format(
"TANH:{}:{}", subgraphIndex, operatorIndex);
2627 activationDesc.
m_A = 1.0f;
2628 activationDesc.
m_B = 1.0f;
2631 case ActivationFunction::LeakyReLu:
2633 layerName += fmt::format(
"LEAKYRELU:{}:{}", subgraphIndex, operatorIndex);
2634 const auto* options = operatorPtr->builtin_options.AsLeakyReluOptions();
2635 activationDesc.
m_A = options->alpha;
2638 case ActivationFunction::Elu:
2640 layerName += fmt::format(
"ELU:{}:{}", subgraphIndex, operatorIndex);
2641 activationDesc.
m_A = 1.0f;
2644 case ActivationFunction::HardSwish:
2646 layerName += fmt::format(
"HARDSWISH:{}:{}", subgraphIndex, operatorIndex);
2652 fmt::format(
"Unexpected ActivationFunction[{}] when creating layerName {} ",
2657 IConnectableLayer*
const layer = m_Network->AddActivationLayer(activationDesc, layerName.c_str());
2664 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2665 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2668 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2669 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2672 const std::vector<int32_t>& targetDimsIn)
2674 std::vector<unsigned int> outputDims(targetDimsIn.begin(), targetDimsIn.end());
2675 const auto stretchDim = std::find(targetDimsIn.begin(), targetDimsIn.end(), -1);
2677 if (stretchDim != targetDimsIn.end())
2679 if (std::find(std::next(stretchDim), targetDimsIn.end(), -1) != targetDimsIn.end())
2682 fmt::format(
"At most one component of shape can be -1 {}",
CHECK_LOCATION().AsString()));
2685 auto targetNumElements =
2687 std::accumulate(targetDimsIn.begin(), targetDimsIn.end(), -1, std::multiplies<int32_t>()));
2689 auto stretchIndex =
static_cast<size_t>(std::distance(targetDimsIn.begin(), stretchDim));
2690 outputDims[stretchIndex] = inputTensorInfo.
GetNumElements() / targetNumElements;
2701 void TfLiteParserImpl::ParseReshape(
size_t subgraphIndex,
size_t operatorIndex)
2703 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2705 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2707 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2710 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2711 const auto* options = operatorPtr->builtin_options.AsReshapeOptions();
2712 auto layerName = fmt::format(
"Reshape:{}:{}", subgraphIndex, operatorIndex);
2716 CheckMatchingQuantization(inputTensorInfo, actualOutputTensorInfo, layerName,
"Input 0",
"Output 0");
2722 std::vector<int32_t> targetShape;
2723 bool targetShapeFound =
false;
2725 if (options !=
nullptr)
2728 if (options->new_shape.empty() ==
false)
2730 targetShape = options->new_shape;
2731 targetShapeFound =
true;
2736 if (!targetShapeFound)
2739 if (inputs.size() > 1 && inputs[1] !=
nullptr)
2741 if (inputs[1]->is_variable)
2746 if (inputs[1]->shape.size() != 1)
2751 if (inputs[1]->type != tflite::TensorType_INT32)
2757 auto bufferPtr =
GetBuffer(m_Model, inputs[1]->buffer);
2758 auto values =
reinterpret_cast<const int32_t*
>(bufferPtr->data.data());
2761 for (
int i = 0; i < inputs[1]->shape[0]; ++i)
2763 targetShape.push_back(values[i]);
2773 if (reshapeShapes[0] > 2)
2775 throw ParseException(fmt::format(
"Invalid input shape '{}' in Reshape layer '{}' {}. " 2776 "When inferring during runtime, the parser only supports " 2777 "shape (batch, -1) or (-1) for target shape input.",
2783 const int32_t numInputElements = inputTensorInfo.
GetNumElements();
2784 const int32_t inputTensorShape = inputTensorInfo.
GetShape()[0];
2785 if (reshapeShapes[0] == 1)
2787 targetShape = {numInputElements};
2789 else if (reshapeShapes[0] == 2)
2791 targetShape = {inputTensorShape, numInputElements / inputTensorShape};
2794 catch (
const std::exception& exc)
2797 "Reshape operation. Reshape operator target shape input buffer data " 2798 "is null. " << exc.what());
2805 "At least one method required");
2814 if (inputs.size() > 1 && !
CheckShape(reshapeOutputTensorShape, outputs[0]->shape))
2816 std::stringstream ss;
2817 ss <<
"New shape defined in reshape parameters " 2818 << reshapeOutputTensorShape
2819 <<
" does not equal output shape " 2820 << actualOutputTensorInfo.
GetShape()
2829 IConnectableLayer* layer = m_Network->AddReshapeLayer(reshapeDesc, layerName.c_str());
2833 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2834 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2836 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2837 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2840 void TfLiteParserImpl::ParseResizeBilinear(
size_t subgraphIndex,
size_t operatorIndex)
2842 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::Bilinear);
2845 void TfLiteParserImpl::ParseResizeNearestNeighbor(
size_t subgraphIndex,
size_t operatorIndex)
2847 ParseResize(subgraphIndex, operatorIndex, ResizeMethod::NearestNeighbor);
2850 void TfLiteParserImpl::ParseResize(
size_t subgraphIndex,
size_t operatorIndex,
ResizeMethod resizeMethod)
2852 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2854 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2857 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2863 std::vector<int32_t> sizeTensorData(sizeTensorInfo.GetNumElements());
2866 ::memcpy(sizeTensorData.data(), sizeBufferPtr->data.data(), sizeTensorInfo.GetNumBytes());
2870 desc.m_TargetHeight =
static_cast<uint32_t
> (sizeTensorData[0]);
2871 desc.m_TargetWidth =
static_cast<uint32_t
> (sizeTensorData[1]);
2874 auto layerName = fmt::format(
"Resize:");
2876 switch (resizeMethod)
2878 case ResizeMethod::Bilinear:
2880 layerName += fmt::format(
"BILINEAR:{}:{}", subgraphIndex, operatorIndex);
2882 const auto & operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2883 const auto * options = operatorPtr->builtin_options.AsResizeBilinearOptions();
2885 desc.m_AlignCorners = options->align_corners;
2888 case ResizeMethod::NearestNeighbor:
2890 layerName += fmt::format(
"NEARESTNEIGHBOR:{}:{}", subgraphIndex, operatorIndex);
2896 fmt::format(
"Unexpected ResizeMethod[{}] when creating layerName {} ",
2903 CheckMatchingQuantization(inputTensorInfo, outputTensorInfo, layerName,
"Input 0",
"Output 0");
2909 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2910 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
2912 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2913 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
2916 void TfLiteParserImpl::ParseConcatenation(
size_t subgraphIndex,
size_t operatorIndex)
2918 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2920 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2921 const auto* options = operatorPtr->builtin_options.AsConcatenationOptions();
2925 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2926 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2929 unsigned int numConcatView =
static_cast<unsigned int>(inputs.size());
2932 const unsigned int concatDimInput =
static_cast<unsigned int>(
2933 (
static_cast<int>(inputRank) + options->axis) %
static_cast<int>(inputRank));
2935 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatView), inputRank);
2938 unsigned int mergeDimOrigin = 0;
2940 for (
unsigned int viewIndex = 0; viewIndex < numConcatView; ++viewIndex)
2946 inputTensorInfo, concatDescriptor, concatDimInput, viewIndex, mergeDimOrigin);
2949 auto layerName = fmt::format(
"Concatenation:{}:{}", subgraphIndex, operatorIndex);
2952 IConnectableLayer* layer = m_Network->AddConcatLayer(concatDescriptor, layerName.c_str());
2956 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
2957 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
2960 layer = AddFusedActivationLayer(layer, 0, options->fused_activation_function);
2962 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
2963 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
2966 void TfLiteParserImpl::ParseFullyConnected(
size_t subgraphIndex,
size_t operatorIndex)
2968 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
2970 const auto& operatorRfr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
2971 const auto options = operatorRfr->builtin_options.AsFullyConnectedOptions();
2979 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
2980 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
2986 int32_t weightsDimension =
static_cast<int32_t
>(filterTensorInfo.GetNumDimensions());
2987 if (weightsDimension != 2)
2990 fmt::format(
"Dimension {} for Fully Connected weights is not supported by Armnn. " 2997 auto layerName = fmt::format(
"FullyConnected:{}:{}", subgraphIndex, operatorIndex);
2999 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3001 std::vector<unsigned int> tensorIndexesToRegister = {inputTensorIndexes[0]};
3002 std::vector<unsigned int> ignoreInputWhenRegister = {};
3008 tensorIndexesToRegister.emplace_back(inputTensorIndexes[1]);
3011 (filterTensorInfo.GetDataType() == DataType::QAsymmU8 ||
3012 filterTensorInfo.GetDataType() == DataType::QAsymmS8))
3014 m_ConstantsToDequantize.emplace_back(inputs[1]->buffer);
3017 if (inputs.size() == 3)
3023 tensorIndexesToRegister.emplace_back(inputTensorIndexes[2]);
3026 (biasTensorInfo.
GetDataType() == DataType::QAsymmU8 ||
3027 biasTensorInfo.
GetDataType() == DataType::QAsymmS8))
3029 m_ConstantsToDequantize.emplace_back(inputs[2]->buffer);
3034 layer = m_Network->AddFullyConnectedLayer(desc, layerName.c_str());
3038 unsigned int startingSlotIndex = 0;
3045 std::vector<unsigned int> reshapedDimensions(2);
3046 reshapedDimensions[1] = filterTensorInfo.GetShape()[1];
3047 reshapedDimensions[0] = inputTensorInfo.
GetNumElements() / reshapedDimensions[1];
3049 if (inputTensorInfo.
GetNumElements() % reshapedDimensions[1] != 0)
3052 fmt::format(
"Failed to deduce input tensor shape from filter size {} {}",
3053 reshapedDimensions[1],
3060 std::string reshapeLayerName = fmt::format(
"Reshape_for:{}", layer->
GetName());
3068 RegisterInputSlots(subgraphIndex, operatorIndex, reshapeLayer, {inputTensorIndexes[0]});
3070 tensorIndexesToRegister.erase(tensorIndexesToRegister.begin());
3071 startingSlotIndex = 1;
3074 RegisterInputSlots(subgraphIndex, operatorIndex, layer, tensorIndexesToRegister, startingSlotIndex);
3081 options->fused_activation_function);
3084 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3085 RegisterOutputSlots(subgraphIndex, operatorIndex, fusedActivationLayer, {outputTensorIndexes[0]});
3088 void TfLiteParserImpl::ParseDetectionPostProcess(
size_t subgraphIndex,
size_t operatorIndex)
3090 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3092 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3094 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3095 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3099 auto custom_options = operatorPtr->custom_options;
3100 const flexbuffers::Map& m = flexbuffers::GetRoot(custom_options.data(), custom_options.size()).AsMap();
3109 desc.
m_ScaleH = m[
"h_scale"].AsFloat();
3110 desc.
m_ScaleW = m[
"w_scale"].AsFloat();
3111 desc.
m_ScaleX = m[
"x_scale"].AsFloat();
3112 desc.
m_ScaleY = m[
"y_scale"].AsFloat();
3114 if (!(m[
"use_regular_nms"].IsNull()))
3118 if (!(m[
"detections_per_class"].IsNull()))
3126 "must be positive and less than or equal to 1.");
3130 auto anchorTensorAndData = CreateConstTensorNonPermuted(inputs[2], anchorTensorInfo);
3132 auto layerName = fmt::format(
"DetectionPostProcess:{}:{}", subgraphIndex, operatorIndex);
3133 IConnectableLayer* layer = m_Network->AddDetectionPostProcessLayer(desc, anchorTensorAndData,
3141 m_OverridenOutputShapes.push_back({ 1, numDetectedBox, 4 });
3142 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
3143 m_OverridenOutputShapes.push_back({ 1, numDetectedBox });
3144 m_OverridenOutputShapes.push_back({ 1 });
3146 for (
unsigned int i = 0 ; i < outputs.size() ; ++i)
3154 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3155 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3158 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3159 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0],
3160 outputTensorIndexes[1],
3161 outputTensorIndexes[2],
3162 outputTensorIndexes[3]});
3166 void TfLiteParserImpl::ParsePack(
size_t subgraphIndex,
size_t operatorIndex)
3168 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3170 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3171 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3174 if (inputs.size() < 1)
3179 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3180 const auto* options = operatorPtr->builtin_options.AsPackOptions();
3183 desc.
m_Axis =
static_cast<uint32_t
>(options->axis);
3184 desc.
m_NumInputs =
static_cast<uint32_t
>(inputs.size());
3190 auto layerName = fmt::format(
"Pack:{}:{}", subgraphIndex, operatorIndex);
3198 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3199 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes});
3201 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3202 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3205 void TfLiteParserImpl::ParseUnidirectionalSequenceLSTM(
size_t subgraphIndex,
size_t operatorIndex)
3207 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3209 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3210 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3212 if (inputs.size() < 2)
3214 throw ParseException(
"UnidirectionalSequenceLSTM must have at least 2 input.");
3217 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3218 const auto& subgraphPtr = m_Model->subgraphs[subgraphIndex];
3219 const auto nodeParams = operatorPtr->builtin_options.AsUnidirectionalSequenceLSTMOptions();
3229 if (IsOptionalOperandPresent(operatorPtr->inputs[1]))
3231 params.
m_InputToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[1]].get(),
3232 inputTensorInfo).first;
3236 inputTensorInfo).first;
3237 params.
m_InputToCellWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[3]].get(),
3238 inputTensorInfo).first;
3240 inputTensorInfo).first;
3243 if (IsOptionalOperandPresent(operatorPtr->inputs[5]))
3246 inputTensorInfo).first;
3250 inputTensorInfo).first;
3252 inputTensorInfo).first;
3254 inputTensorInfo).first;
3257 if (IsOptionalOperandPresent(operatorPtr->inputs[9]))
3259 params.
m_CellToInputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[9]].get(),
3260 inputTensorInfo).first;
3263 if (IsOptionalOperandPresent(operatorPtr->inputs[10]))
3265 params.
m_CellToForgetWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[10]].get(),
3266 inputTensorInfo).first;
3269 if (IsOptionalOperandPresent(operatorPtr->inputs[11]))
3271 params.
m_CellToOutputWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[11]].get(),
3272 inputTensorInfo).first;
3276 if (IsOptionalOperandPresent(operatorPtr->inputs[12]))
3278 params.
m_InputGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[12]].get(),
3279 inputTensorInfo).first;
3282 params.
m_ForgetGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[13]].get(),
3283 inputTensorInfo).first;
3284 params.
m_CellBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[14]].get(),
3285 inputTensorInfo).first;
3286 params.
m_OutputGateBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[15]].get(),
3287 inputTensorInfo).first;
3290 if (IsOptionalOperandPresent(operatorPtr->inputs[16]))
3292 params.
m_ProjectionWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[16]].get(),
3293 inputTensorInfo).first;
3296 if (IsOptionalOperandPresent(operatorPtr->inputs[17]))
3298 params.
m_ProjectionBias = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[17]].get(),
3299 inputTensorInfo).first;
3304 m_ConstantsToBeCreated.push_back(operatorPtr->inputs[18]);
3306 m_ConstantsToBeCreated.push_back(operatorPtr->inputs[19]);
3309 if (inputs.size() >= 21 && IsOptionalOperandPresent(operatorPtr->inputs[20]))
3312 inputTensorInfo).first;
3315 if (inputs.size() >= 22 && IsOptionalOperandPresent(operatorPtr->inputs[21]))
3318 inputTensorInfo).first;
3321 if (inputs.size() >= 23 && IsOptionalOperandPresent(operatorPtr->inputs[22]))
3323 params.
m_CellLayerNormWeights = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->inputs[22]].get(),
3324 inputTensorInfo).first;
3327 if (inputs.size() >= 24 && IsOptionalOperandPresent(operatorPtr->inputs[23]))
3330 inputTensorInfo).first;
3336 desc.m_ClippingThresCell = nodeParams->cell_clip;
3337 desc.m_ClippingThresProj = nodeParams->proj_clip;
3347 desc.m_TimeMajor = nodeParams->time_major;
3349 if (desc.m_LayerNormEnabled)
3351 auto inputIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[0]].get(),
3352 inputTensorInfo).first;
3353 auto inputIntermediateTensorInfo = inputIntermediate->GetInfo();
3354 desc.m_InputIntermediateScale = inputIntermediateTensorInfo.GetQuantizationScale();
3356 auto forgetIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[1]].get(),
3357 inputTensorInfo).first;
3358 auto forgetIntermediateTensorInfo = forgetIntermediate->GetInfo();
3359 desc.m_ForgetIntermediateScale = forgetIntermediateTensorInfo.GetQuantizationScale();
3361 auto cellIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[2]].get(),
3362 inputTensorInfo).first;
3363 auto cellIntermediateTensorInfo = cellIntermediate->GetInfo();
3364 desc.m_CellIntermediateScale = cellIntermediateTensorInfo.GetQuantizationScale();
3366 auto outputIntermediate = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[3]].get(),
3367 inputTensorInfo).first;
3368 auto outputIntermediateTensorInfo = outputIntermediate->GetInfo();
3369 desc.m_OutputIntermediateScale = outputIntermediateTensorInfo.GetQuantizationScale();
3373 float defaultIntermediate = std::pow(2, -12);
3374 desc.m_InputIntermediateScale = defaultIntermediate;
3375 desc.m_ForgetIntermediateScale = defaultIntermediate;
3376 desc.m_CellIntermediateScale = defaultIntermediate;
3377 desc.m_OutputIntermediateScale = defaultIntermediate;
3380 auto hiddentensor = CreateConstTensorPtr(subgraphPtr->tensors[operatorPtr->intermediates[4]].get(),
3381 inputTensorInfo).first;
3383 desc.m_HiddenStateScale = hiddentensor->GetInfo().GetQuantizationScale();
3384 desc.m_HiddenStateZeroPoint = hiddentensor->GetInfo().GetQuantizationOffset();
3386 unsigned int batchSize = inputTensorInfo.GetShape()[0];
3387 unsigned int outputSize = outputTensorInfo.GetShape()[2];
3388 unsigned int numUnits = cellStateInInfo.
GetShape()[1];
3391 float qScale = inputTensorInfo.GetQuantizationScale();
3392 float qOffset = inputTensorInfo.GetQuantizationOffset();
3394 armnn::TensorInfo scratchBufferTensorInfo({batchSize, numUnits * 3}, dataType, qScale, qOffset);
3395 if (!desc.m_CifgEnabled)
3397 scratchBufferTensorInfo =
armnn::TensorInfo({batchSize, numUnits * 4}, dataType, qScale, qOffset);
3403 armnn::TensorInfo outputStateOutTensorInfo({batchSize, outputSize}, dataType, qScale, qOffset);
3416 if (!desc.m_CifgEnabled)
3427 if (desc.m_ProjectionEnabled)
3436 if (desc.m_PeepholeEnabled)
3442 if (desc.m_LayerNormEnabled)
3444 if(!desc.m_CifgEnabled)
3453 auto layerName = fmt::format(
"UnidirectionalSequenceLSTM:{}:{}", subgraphIndex, operatorIndex);
3459 auto inputTensorIndexes = AsUnsignedVector({operatorPtr->inputs[0],
3460 operatorPtr->inputs[18],
3461 operatorPtr->inputs[19]});
3462 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0],
3463 inputTensorIndexes[1],
3464 inputTensorIndexes[2]});
3466 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3472 unsigned int tensorIndex = outputTensorIndexes[0];
3474 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
3477 void TfLiteParserImpl::ParseUnpack(
size_t subgraphIndex,
size_t operatorIndex)
3479 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3481 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3482 const auto* options = operatorPtr->builtin_options.AsUnpackOptions();
3487 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3492 if (unpackAxis >= inputTensorInfo.GetNumDimensions())
3495 fmt::format(
"The unpack axis: {} cannot be greater than or equal to " 3496 "the number of input dimension {} {}",
3498 inputTensorInfo.GetNumDimensions(),
3506 unpackNum = inputTensorInfo.GetShape()[unpackAxis];
3512 throw ParseException(
"Number to unpack must greater than zero.");
3515 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3518 auto inputDimSize = inputTensorInfo.GetNumDimensions();
3519 std::vector<unsigned int> unpackDimSizes(inputDimSize);
3522 for (
unsigned int i = 0; i < inputDimSize; ++i)
3524 unpackDimSizes[i] = inputTensorInfo.GetShape()[i];
3527 if (unpackDimSizes[unpackAxis] != unpackNum)
3529 throw ParseException(
"Number to unpack must be the same as length of the dimension to " 3533 unpackDimSizes[unpackAxis] /= unpackNum;
3535 SplitterDescriptor splitDesc(unpackNum, static_cast<unsigned int>(unpackDimSizes.size()));
3536 for (
unsigned int j = 0; j < unpackNum; ++j)
3539 for (
unsigned int dimIdx = 0; dimIdx < unpackDimSizes.size(); ++dimIdx)
3541 splitDesc.
SetViewSize(j, dimIdx, unpackDimSizes[dimIdx]);
3546 auto layerName = fmt::format(
"Unpack:{}:{}", subgraphIndex, operatorIndex);
3547 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
3551 unpackDimSizes.data());
3553 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3554 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3556 std::vector<unsigned int> reshapeDims;
3557 for (
unsigned int axis = 0; axis < splitOutShape.
GetNumDimensions(); ++axis)
3559 if (axis != unpackAxis)
3561 reshapeDims.push_back(splitOutShape[axis]);
3571 std::string reshapeLayerName = fmt::format(
"Reshape_for:{}", layer->
GetName());
3586 RegisterProducerOfTensor(subgraphIndex, reshapedOutputId, slot);
3590 void TfLiteParserImpl::ParseSplit(
size_t subgraphIndex,
size_t operatorIndex)
3592 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3594 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3595 const auto* options = operatorPtr->builtin_options.AsSplitOptions();
3602 throw ParseException(
"Number to splits must greater than zero.");
3605 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3607 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3615 if (axisBufferPtr ==
nullptr)
3618 fmt::format(
"Operation has invalid inputs. Failed to read axis. {}",
3623 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.
GetNumBytes());
3624 int32_t axis = axisData[0];
3626 auto inputDimensions =
static_cast<int32_t
>(inputTensorInfo.GetNumDimensions());
3627 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3633 fmt::format(
"Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3640 auto inputDimSize = inputTensorInfo.GetNumDimensions();
3644 fmt::format(
"The number of dimensions: {} for input tensors of the split op cannot be greater than {} {}",
3645 inputTensorInfo.GetNumDimensions(),
3650 std::vector<unsigned int> splitterDimSizes(inputDimSize);
3653 for (
unsigned int i = 0; i < inputDimSize; ++i)
3655 splitterDimSizes[i] = inputTensorInfo.GetShape()[i];
3658 if (splitterDimSizes[splitDim] % numSplits != 0)
3660 throw ParseException(
"Number of splits must evenly divide the dimension");
3662 splitterDimSizes[splitDim] /= numSplits;
3665 for (
unsigned int j = 0; j < numSplits; ++j)
3668 for (
unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
3670 splitDesc.
SetViewSize(j, dimIdx, splitterDimSizes[dimIdx]);
3675 auto layerName = fmt::format(
"Split:{}:{}", subgraphIndex, operatorIndex);
3676 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
3679 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3680 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[1]});
3688 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3689 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3695 int v = idx < 0 ? numDims + idx : idx;
3699 return static_cast<unsigned int>(v);
3702 void TfLiteParserImpl::ParseSplitV(
size_t subgraphIndex,
size_t operatorIndex)
3704 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3706 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3707 const auto* options = operatorPtr->builtin_options.AsSplitVOptions();
3709 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3712 auto& inputTensor = inputs[0];
3713 auto& splitsTensor = inputs[1];
3714 auto& axisTensor = inputs[2];
3726 fmt::format(
"The number of dimensions: {} for input tensors of the " 3727 "SplitV op cannot be greater than {} {}",
3735 if (axisBufferPtr ==
nullptr)
3738 fmt::format(
"Operation has invalid inputs. Failed to read axis. {}",
3743 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.
GetNumBytes());
3744 int32_t axis = axisData[0];
3746 auto inputDimensions =
static_cast<int32_t
>(inputTensorInfo.
GetNumDimensions());
3747 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3753 fmt::format(
"Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3761 unsigned int numSplits{0};
3777 std::vector<int> splitsData(numSplits);
3779 ::memcpy(splitsData.data(), splitsBufferPtr->data.data(), splitsInfo.
GetNumBytes());
3781 unsigned int idx = 0;
3783 unsigned int inferIdx{0};
3785 for (
auto split : splitsData)
3799 if (numInferred == 0)
3801 if (splitSum != armnn::numeric_cast<int>(inputTensorInfo.
GetShape()[splitDim]))
3803 throw ParseException(
"SplitV split_sizes does not sum to the dimension of value along split_dim.");
3806 else if (numInferred == 1)
3812 throw ParseException(
"Cannot infer split size for more than one split");
3816 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3821 unsigned int accumSplit = 0;
3822 for (
unsigned int j = 0; j < numSplits; ++j)
3827 for (
unsigned int dimIdx = 0; dimIdx < inputTensorInfo.
GetNumDimensions(); ++dimIdx)
3829 unsigned int dimSize = inputTensorInfo.
GetShape()[dimIdx];
3830 if (dimIdx == splitDim)
3832 dimSize = splitSize;
3834 splitDesc.SetViewSize(j, dimIdx, dimSize);
3837 splitDesc.SetViewOriginCoord(j, splitDim, accumSplit);
3838 accumSplit += splitSize;
3841 auto layerName = fmt::format(
"SplitV:{}:{}", subgraphIndex, operatorIndex);
3842 IConnectableLayer* layer = m_Network->AddSplitterLayer(splitDesc, layerName.c_str());
3845 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3846 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3854 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3855 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3858 void TfLiteParserImpl::ParseArgMin(
size_t subgraphIndex,
size_t operatorIndex)
3863 void TfLiteParserImpl::ParseArgMax(
size_t subgraphIndex,
size_t operatorIndex)
3868 void TfLiteParserImpl::ParseArgMinMax(
size_t subgraphIndex,
size_t operatorIndex,
ArgMinMaxFunction argMinMaxFunction)
3870 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3871 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
3874 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
3888 "Output tensor data type is not supported. (Supported types: Signed32 & Signed64) {}",
3894 if (axisBufferPtr ==
nullptr)
3897 fmt::format(
"Operation has invalid inputs. Failed to read axis. {}",
3902 ::memcpy(axisData.data(), axisBufferPtr->data.data(), axisTensorInfo.
GetNumBytes());
3903 int32_t axis = axisData.front();
3905 auto inputDimensions =
static_cast<int32_t
>(inputTensorInfo.GetNumDimensions());
3906 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3912 fmt::format(
"Operation has invalid axis: {}. Axis must be in range [-n, n) {}",
3922 auto layerName = argMinMaxFunction == ArgMinMaxFunction::Max ?
"ArgMax:{}:{}" :
"ArgMin:{}:{}";
3923 auto layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
3924 IConnectableLayer *layer = m_Network->AddArgMinMaxLayer(desc, layerNameFormatted.c_str());
3929 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3930 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
3933 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3934 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
3937 void TfLiteParserImpl::ParseGather(
size_t subgraphIndex,
size_t operatorIndex)
3939 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
3952 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
3953 const auto* options = operatorPtr->builtin_options.AsGatherOptions();
3954 auto axis = options->axis;
3956 auto inputDimensions =
static_cast<int32_t
>(inputTensorInfo.GetNumDimensions());
3959 if (((axis < -inputDimensions) && (axis < 0)) || ((axis >= inputDimensions) && (axis > 0)))
3962 fmt::format(
"Operation has invalid axis: {} It is out of bounds [ -{}, {} ) {}",
3964 inputDimensions, inputDimensions,
3967 if (outputDimensions != static_cast<unsigned int>(inputDimensions) + indicesDimensions - 1)
3970 fmt::format(
"Operation has invalid output dimensions: {} Output must be an ({} + {} - 1) -D tensor {}",
3972 inputDimensions, indicesDimensions,
3976 gatherDescriptor.
m_Axis = axis;
3978 auto layerName = fmt::format(
"Gather:{}:{}", subgraphIndex, operatorIndex);
3979 IConnectableLayer* layer = m_Network->AddGatherLayer(gatherDescriptor, layerName.c_str());
3983 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
3984 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
3986 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
3987 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
3990 void TfLiteParserImpl::ParseGatherNd(
size_t subgraphIndex,
size_t operatorIndex)
3992 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4003 auto layerName = fmt::format(
"GatherNd:{}:{}", subgraphIndex, operatorIndex);
4008 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4009 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4011 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4012 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4015 void TfLiteParserImpl::ParseDepthToSpace(
size_t subgraphIndex,
size_t operatorIndex)
4017 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4026 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4027 const auto* options = operatorPtr->builtin_options.AsDepthToSpaceOptions();
4028 auto blockSize = options->block_size;
4032 fmt::format(
"Operation has invalid block size: {} Block size should be >= 2 {}",
4038 auto layerName = fmt::format(
"DepthToSpace:{}:{}", subgraphIndex, operatorIndex);
4039 IConnectableLayer* layer = m_Network->AddDepthToSpaceLayer(descriptor, layerName.c_str());
4044 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4045 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4047 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4048 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4051 void TfLiteParserImpl::ParseSum(
size_t subgraphIndex,
size_t operatorIndex)
4056 void TfLiteParserImpl::ParseReduceProd(
size_t subgraphIndex,
size_t operatorIndex)
4061 void TfLiteParserImpl::ParseReduceMax(
size_t subgraphIndex,
size_t operatorIndex)
4066 void TfLiteParserImpl::ParseReduceMin(
size_t subgraphIndex,
size_t operatorIndex)
4071 void TfLiteParserImpl::ParseReduce(
size_t subgraphIndex,
size_t operatorIndex,
ReduceOperation reduceOperation)
4073 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4075 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4076 const auto* options = operatorPtr->builtin_options.AsReducerOptions();
4078 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
4081 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
4084 auto layerName = fmt::format(
"Reduce:{}:{}", subgraphIndex, operatorIndex);
4092 if (axisBufferPtr !=
nullptr)
4094 std::vector<int32_t> axisData(inputTensorInfo1.
GetNumElements());
4095 ::memcpy(axisData.data(), axisBufferPtr->data.data(), inputTensorInfo1.
GetNumBytes());
4099 std::set<unsigned int> uniqueAxis;
4100 std::transform(axisData.begin(),
4102 std::inserter(uniqueAxis, uniqueAxis.begin()),
4103 [rank](
int i)->unsigned
int{
4104 return static_cast<uint32_t
>(((i + rank) % rank)); });
4105 desc.
m_vAxis.assign(uniqueAxis.begin(), uniqueAxis.end());
4125 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4126 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4129 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4130 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4133 void TfLiteParserImpl::ParseAbs(
size_t subgraphIndex,
size_t operatorIndex)
4138 void TfLiteParserImpl::ParseExp(
size_t subgraphIndex,
size_t operatorIndex)
4143 void TfLiteParserImpl::ParseLocalResponseNormalization(
size_t subgraphIndex,
size_t operatorIndex)
4145 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4147 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
4150 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
4153 auto layerName = fmt::format(
"LRN:{}:{}", subgraphIndex, operatorIndex);
4154 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4158 const auto& operatorPtr = m_Model->subgraphs[subgraphIndex]->operators[operatorIndex];
4159 const auto* options = operatorPtr->builtin_options.AsLocalResponseNormalizationOptions();
4165 descriptor.
m_NormSize =
static_cast<uint32_t
>(options->radius);
4166 descriptor.
m_K = options->bias;
4167 descriptor.
m_Alpha = options->alpha;
4168 descriptor.
m_Beta = options->beta;
4174 IConnectableLayer* layer = m_Network->AddNormalizationLayer(descriptor, layerNameFormatted.c_str());
4180 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4181 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4183 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4184 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4187 void TfLiteParserImpl::ParseLogicalNot(
size_t subgraphIndex,
size_t operatorIndex)
4192 void TfLiteParserImpl::ParseNeg(
size_t subgraphIndex,
size_t operatorIndex)
4197 void TfLiteParserImpl::ParseRsqrt(
size_t subgraphIndex,
size_t operatorIndex)
4202 void TfLiteParserImpl::ParseSqrt(
size_t subgraphIndex,
size_t operatorIndex)
4207 void TfLiteParserImpl::ParseElementwiseUnary(
size_t subgraphIndex,
size_t operatorIndex,
UnaryOperation unaryOperation)
4209 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4211 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
4214 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
4218 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4222 IConnectableLayer* layer = m_Network->AddElementwiseUnaryLayer(desc, layerNameFormatted.c_str());
4228 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4229 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0]});
4231 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4232 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, outputTensorIndexes);
4235 void TfLiteParserImpl::ParseEqual(
size_t subgraphIndex,
size_t operatorIndex)
4240 void TfLiteParserImpl::ParseNotEqual(
size_t subgraphIndex,
size_t operatorIndex)
4245 void TfLiteParserImpl::ParseGreater(
size_t subgraphIndex,
size_t operatorIndex)
4250 void TfLiteParserImpl::ParseGreaterOrEqual(
size_t subgraphIndex,
size_t operatorIndex)
4255 void TfLiteParserImpl::ParseLess(
size_t subgraphIndex,
size_t operatorIndex)
4260 void TfLiteParserImpl::ParseLessOrEqual(
size_t subgraphIndex,
size_t operatorIndex)
4265 void TfLiteParserImpl::ParseComparison(
size_t subgraphIndex,
size_t operatorIndex,
4268 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4270 auto inputs =
GetInputs(m_Model, subgraphIndex, operatorIndex);
4273 auto outputs =
GetOutputs(m_Model, subgraphIndex, operatorIndex);
4277 std::string layerNameFormatted = fmt::format(layerName, subgraphIndex, operatorIndex);
4281 CheckMatchingQuantization(inputTensorInfo, input1TensorInfo, layerNameFormatted,
"Input 0",
"Input 1");
4285 IConnectableLayer* layer = m_Network->AddComparisonLayer(desc, layerNameFormatted.c_str());
4291 auto inputTensorIndexes = AsUnsignedVector(
GetInputTensorIds(m_Model, subgraphIndex, operatorIndex));
4292 RegisterInputSlots(subgraphIndex, operatorIndex, layer, {inputTensorIndexes[0], inputTensorIndexes[1]});
4294 auto outputTensorIndexes = AsUnsignedVector(
GetOutputTensorIds(m_Model, subgraphIndex, operatorIndex));
4295 RegisterOutputSlots(subgraphIndex, operatorIndex, layer, {outputTensorIndexes[0]});
4299 unsigned int outputSlot,
4300 tflite::ActivationFunctionType activationType)
4303 std::string layerName = prevLayer->
GetName();
4305 switch(activationType)
4307 case tflite::ActivationFunctionType_NONE:
4312 case tflite::ActivationFunctionType_RELU:
4314 activationDesc.
m_Function = ActivationFunction::ReLu;
4315 layerName +=
":RELU";
4318 case tflite::ActivationFunctionType_RELU6:
4320 activationDesc.
m_Function = ActivationFunction::BoundedReLu;
4321 activationDesc.
m_A = 6.0f;
4322 activationDesc.
m_B = 0.0f;
4323 layerName +=
":RELU6";
4326 case tflite::ActivationFunctionType_TANH:
4328 activationDesc.
m_Function = ActivationFunction::TanH;
4329 activationDesc.
m_A = 1.0f;
4330 activationDesc.
m_B = 1.0f;
4331 layerName +=
":TANH";
4336 case tflite::ActivationFunctionType_RELU_N1_TO_1:
4337 case tflite::ActivationFunctionType_SIGN_BIT:
4341 fmt::format(
"TfLite parser doesn't suppport fused activation: " 4344 tflite::EnumNameActivationFunctionType(activationType),
4351 m_Network->AddActivationLayer(activationDesc, layerName.c_str());
4353 auto & prevOutputSlot = prevLayer->
GetOutputSlot(outputSlot);
4356 return activationLayer;
4360 unsigned int outputSlot)
4363 auto& prevOutputSlot = prevLayer->
GetOutputSlot(outputSlot);
4366 if (dataType == DataType::Signed32)
4371 std::string layerName = prevLayer->
GetName();
4382 if (fileName ==
nullptr)
4387 std::error_code errorCode;
4388 fs::path pathToFile(fileName);
4389 if (!fs::exists(pathToFile, errorCode))
4392 std::stringstream msg;
4393 msg <<
"Cannot find the file (" << fileName <<
") errorCode: " << errorCode
4398 std::ifstream file(fileName, std::ios::binary);
4399 std::string fileContent((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
4401 fileContent.size());
4406 if (binaryContent ==
nullptr)
4411 flatbuffers::Verifier verifier(binaryContent, len);
4412 if (verifier.VerifyBuffer<tflite::Model>() ==
false)
4415 fmt::format(
"Buffer doesn't conform to the expected Tensorflow Lite " 4416 "flatbuffers format. size:{} {}",
4420 return tflite::UnPackModel(binaryContent);
4424 size_t subgraphIndex,
4425 size_t operatorIndex)
4429 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4430 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
4432 size_t inputCount = operatorPtr->inputs.size();
4434 for (
size_t i = 0; i < inputCount; ++i)
4437 if (operatorPtr->inputs[i] == -1)
4444 result.push_back(subgraphPtr->tensors[inputId].get());
4451 size_t subgraphIndex,
4452 size_t operatorIndex)
4456 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4457 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
4459 size_t outputCount = operatorPtr->outputs.size();
4461 for (
size_t i = 0; i < outputCount; ++i)
4465 result[i] = subgraphPtr->tensors[outputId].get();
4471 size_t subgraphIndex)
4474 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4476 size_t inputCount = subgraphPtr->inputs.size();
4478 for (
size_t i = 0; i < inputCount; ++i)
4482 result[i] = std::make_pair(inputId, subgraphPtr->tensors[inputId].get());
4488 size_t subgraphIndex)
4491 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4493 size_t outputCount = subgraphPtr->outputs.size();
4495 for (
size_t i = 0; i < outputCount; ++i)
4498 result[i] = std::make_pair(outputId, subgraphPtr->tensors[outputId].get());
4504 size_t subgraphIndex,
4505 size_t operatorIndex)
4508 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4509 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
4510 return operatorPtr->inputs;
4514 size_t subgraphIndex,
4515 size_t operatorIndex)
4518 const auto& subgraphPtr = model->subgraphs[subgraphIndex];
4519 const auto& operatorPtr = subgraphPtr->operators[operatorIndex];
4520 return operatorPtr->outputs;
4523 void TfLiteParserImpl::RegisterInputSlots(
size_t subgraphIndex,
4524 size_t operatorIndex,
4526 const std::vector<unsigned int>& tensorIndexes,
4527 unsigned int startingSlotIndex)
4529 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4535 fmt::format(
"The number of tensor inputs ({}) does not match the number expected ({})" 4536 " for subgraph:{} operator index:{} {}",
4537 tensorIndexes.size(),
4544 for (
unsigned int index = 0; index < tensorIndexes.size() ; ++index)
4546 unsigned int tensorIndex = tensorIndexes[index];
4548 RegisterConsumerOfTensor(subgraphIndex, tensorIndex, slot);
4552 void TfLiteParserImpl::RegisterOutputSlots(
size_t subgraphIndex,
4553 size_t operatorIndex,
4555 const std::vector<unsigned int>& tensorIndexes)
4557 CHECK_MODEL(m_Model, subgraphIndex, operatorIndex);
4562 fmt::format(
"The number of tensor outputs ({}) does not match the number expected ({})" 4563 " for subgraph:{} operator index:{} {}",
4564 tensorIndexes.size(),
4571 for (
unsigned int slotIndex = 0; slotIndex < layer->
GetNumOutputSlots(); ++slotIndex)
4573 unsigned int tensorIndex = tensorIndexes[slotIndex];
4575 RegisterProducerOfTensor(subgraphIndex, tensorIndex, slot);
4579 void TfLiteParserImpl::SetupInputLayers(
size_t subgraphIndex)
4584 for (
auto const& tensorIdAndPtr : inputs)
4586 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
4588 m_Network->AddInputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
4593 RegisterOutputSlots(subgraphIndex,
4594 VIRTUAL_OPERATOR_ID,
4596 {
static_cast<uint32_t
>(tensorIdAndPtr.first) });
4600 void TfLiteParserImpl::SetupOutputLayers(
size_t subgraphIndex)
4605 for (
auto const& tensorIdAndPtr : outputs)
4607 auto bindingId = GenerateLayerBindingId(subgraphIndex, tensorIdAndPtr.first);
4609 m_Network->AddOutputLayer(bindingId, tensorIdAndPtr.second->name.c_str());
4611 RegisterInputSlots(subgraphIndex,
4612 VIRTUAL_OPERATOR_ID,
4614 {
static_cast<uint32_t
>(tensorIdAndPtr.first) });
4618 void TfLiteParserImpl::SetupConstantLayers(
size_t subgraph)
4622 const auto & subgraphPtr = m_Model->subgraphs[subgraph];
4623 for (
unsigned int subgraphIndex = 0; subgraphIndex < m_SubgraphConnections.size(); ++subgraphIndex)
4625 for (
unsigned int tensorIndex = 0; tensorIndex < m_SubgraphConnections[subgraphIndex].size(); ++tensorIndex)
4627 if (m_SubgraphConnections[subgraphIndex][tensorIndex].outputSlot ==
nullptr &&
4628 m_SubgraphConnections[subgraphIndex][tensorIndex].inputSlots.size() > 0)
4630 TensorRawPtr tensorPtr = subgraphPtr->tensors[tensorIndex].get();
4632 if (IsConstTensor(tensorPtr))
4637 if (std::find(m_ConstantsToDequantize.begin(), m_ConstantsToDequantize.end(), tensorPtr->buffer)
4638 != m_ConstantsToDequantize.end())
4640 dataType = DataType::Float32;
4642 auto tensorAndData = CreateConstTensorNonPermuted(tensorPtr, tensorInfo, dataType);
4644 std::string layerName = fmt::format(
"Constant:{}", tensorPtr->name);
4645 IConnectableLayer *layer = m_Network->AddConstantLayer(tensorAndData.first, layerName.c_str());
4648 RegisterOutputSlots(subgraphIndex,
4649 VIRTUAL_OPERATOR_ID,
4653 else if (ShouldConstantTensorBeCreated(tensorIndex))
4658 if (std::find(m_ConstantsToDequantize.begin(), m_ConstantsToDequantize.end(), tensorPtr->buffer)
4659 != m_ConstantsToDequantize.end())
4661 dataType = DataType::Float32;
4669 std::string layerName = fmt::format(
"Constant:{}", tensorPtr->name);
4670 IConnectableLayer* layer = m_Network->AddConstantLayer(tensorAndData, layerName.c_str());
4673 RegisterOutputSlots(subgraphIndex,
4674 VIRTUAL_OPERATOR_ID,
4681 fmt::format(
"Invalid Tensor: Tensor should be constant. {}",
4693 return model->buffers[bufferIndex].get();
4696 template<
typename T>
4697 std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
4706 auto constData = CreateConstTensorImpl<T>(bufferPtr,
4710 TfLiteParserImpl::SupportedDataStorage storage(std::move(constData.second));
4711 return std::make_pair(constData.first, std::move(storage));
4714 bool TfLiteParserImpl::ShouldConstantTensorBeCreated(
unsigned int tensorIndex)
4717 return (std::find(m_ConstantsToBeCreated.begin(), m_ConstantsToBeCreated.end(), tensorIndex)
4718 != m_ConstantsToBeCreated.end());
4721 bool TfLiteParserImpl::IsConstTensor(
TensorRawPtr tensorPtr)
4724 bool isConst =
true;
4726 auto buffer =
GetBuffer(m_Model, tensorPtr->buffer);
4727 if (buffer->data.size() == 0)
4735 std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
4736 TfLiteParserImpl::CreateConstTensorPermuted(
TensorRawPtr tensorPtr,
4741 auto bufferPtr =
GetBuffer(m_Model, tensorPtr->buffer);
4750 return CreateConstTensorAndStoreData<float>(bufferPtr,
4755 return CreateConstTensorAndStoreData<uint8_t>(bufferPtr,
4760 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
4765 return CreateConstTensorAndStoreData<int8_t>(bufferPtr,
4770 return CreateConstTensorAndStoreData<int32_t>(bufferPtr,
4776 std::stringstream errString;
4777 errString <<
"Unexpected datatype when creating const tensor: " 4779 <<
" shape:" << tensorInfo.GetShape()
4790 auto bufferPtr =
GetBuffer(m_Model, tensorPtr->buffer);
4796 return ConstTensor(tensorInfo, bufferPtr->data.data());
4799 std::pair<armnn::ConstTensor, std::unique_ptr<float[]>>
4800 TfLiteParserImpl::CreateConstTensorNonPermuted(
TensorRawPtr tensorPtr,
4805 auto bufferPtr =
GetBuffer(m_Model, tensorPtr->buffer);
4811 if (inputDataType == DataType::Float32 && tensorInfo.
GetDataType() != DataType::Float32)
4814 std::unique_ptr<float[]> data =
AsFloatArray(bufferPtr, tensorInfo);
4815 return std::make_pair(
ConstTensor(constTensorInfo, data.get()), std::move(data));
4819 return std::make_pair(
ConstTensor(tensorInfo, bufferPtr->data.data()), std::unique_ptr<
float[]>());
4823 std::pair<armnn::ConstTensor*, std::unique_ptr<float[]>>
4828 auto bufferPtr =
GetBuffer(m_Model, tensorPtr->buffer);
4837 std::unique_ptr<float[]> data =
AsFloatArray(bufferPtr, tensorInfo);
4838 return std::make_pair(
new ConstTensor(constTensorInfo, data.get()), std::move(data));
4842 return std::make_pair(
new ConstTensor(tensorInfo, bufferPtr->data.data()), std::unique_ptr<
float[]>());
4847 const std::string& name)
const 4851 for (
auto const& input : inputs)
4853 if (input.second->name == name)
4855 auto bindingId = GenerateLayerBindingId(subgraphId, input.first);
4859 return std::make_pair(bindingId, inputTensorInfo);
4863 std::stringstream bindings;
4864 for (
auto const& input : inputs)
4866 bindings <<
"'" << input.second->name <<
"' ";
4870 fmt::format(
"No input binding found for subgraph:{} and name:{}. " 4871 "Possible inputs are: [{}] {}",
4879 const std::string& name)
const 4883 for (
unsigned int i = 0; i < outputs.size(); ++i)
4885 auto const output = outputs[i];
4886 if (output.second->name == name)
4888 auto bindingId = GenerateLayerBindingId(subgraphId, output.first);
4889 std::vector<unsigned int> shape = m_OverridenOutputShapes.size() > 0 ?
4890 m_OverridenOutputShapes[i] : AsUnsignedVector(output.second->shape);
4891 return std::make_pair(bindingId,
ToTensorInfo(output.second, shape));
4895 std::stringstream bindings;
4896 for (
auto const& output : outputs)
4898 bindings <<
"'" << output.second->name <<
"' ";
4902 fmt::format(
"No output binding found for subgraph:{} and name:{}. " 4903 "Possible outputs are: [{}] {}",
4912 return m_Model->subgraphs.size();
4919 std::vector<std::string> result;
4920 result.reserve(inputs.size());
4921 for (
auto const& input : inputs)
4923 result.push_back(input.second->name);
4932 std::vector<std::string> result;
4933 result.reserve(outputs.size());
4934 for (
auto const& output : outputs)
4936 result.push_back(output.second->name);
4946 TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<
float[]>&& data)
4947 : m_FloatData(std::move(data))
4948 , m_Uint8Data(
nullptr)
4949 , m_Int8Data(
nullptr)
4950 , m_Int32Data(
nullptr)
4954 TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<uint8_t[]>&& data)
4955 : m_FloatData(
nullptr)
4956 , m_Uint8Data(std::move(data))
4957 , m_Int8Data(
nullptr)
4958 , m_Int32Data(
nullptr)
4962 TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int8_t[]>&& data)
4963 : m_FloatData(
nullptr)
4964 , m_Uint8Data(
nullptr)
4965 , m_Int8Data(std::move(data))
4966 , m_Int32Data(
nullptr)
4970 TfLiteParserImpl::SupportedDataStorage::SupportedDataStorage(std::unique_ptr<int32_t[]>&& data)
4971 : m_FloatData(
nullptr)
4972 , m_Uint8Data(
nullptr)
4973 , m_Int8Data(
nullptr)
4974 , m_Int32Data(std::move(data))
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.
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.
bool HasPerAxisQuantization() const
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
Optional< unsigned int > GetQuantizationDim() const
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)
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)
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}.
std::vector< float > GetQuantizationScales() const
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_MaxDetections
Maximum numbers of detections.
A PadDescriptor for the PadLayer.
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.
An LstmDescriptor for the LstmLayer.
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.
An ActivationDescriptor for the ActivationLayer.
const TensorInfo & GetInfo() const
void SetDataType(DataType type)
uint32_t m_NumInputs
Number of input tensors.
uint32_t m_PadLeft
Padding left value in the width dimension.
uint32_t m_ActivationFunc
The activation function to use.
A SliceDescriptor for the SliceLayer.
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)
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.
std::unique_ptr< float[]> AsFloatArray(TfLiteParserImpl::BufferRawPtr bufferPtr, const TensorInfo &tensorInfo)
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 TensorInfo & GetTensorInfo() const =0
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.
unsigned int GetNumElementsAfter(const armnn::TensorShape &shape, unsigned int axis)
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.
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.
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.
unsigned int GetNumElements() const
uint32_t m_PadRight
Padding right value in the width dimension.
bool m_ConstantWeights
Enable/disable constant weights and biases.