20 #include <google/protobuf/io/zero_copy_stream_impl.h> 21 #include <google/protobuf/text_format.h> 23 #include <tensorflow/core/framework/graph.pb.h> 25 #include <boost/format.hpp> 26 #include <boost/numeric/conversion/cast.hpp> 31 using namespace armnn;
42 template <
typename Callable>
43 void ReadMandatoryNodeAttributeImpl(
const tensorflow::NodeDef& nodeDef,
44 const std::string& attribName,
45 tensorflow::AttrValue::ValueCase expectedValueCase,
48 auto iter = nodeDef.attr().find(attribName);
49 if (iter != nodeDef.attr().end())
51 const auto& attrValue = iter->second;
52 if (attrValue.value_case() == expectedValueCase)
61 "Attribute %1% of node %2% expected to have %3% as tensorflow::AttrValue::ValueCase, " 62 "but found %4% instead %5%")
65 %
static_cast<int>(expectedValueCase)
66 % static_cast<int>(attrValue.value_case())
75 "Could not find required attribute %1% in node %2% %3%")
82 template <
typename Callable>
83 void ReadOptionalNodeAttributeImpl(
const tensorflow::NodeDef& nodeDef,
84 const std::string& attribName,
85 tensorflow::AttrValue::ValueCase expectedValueCase,
88 auto iter = nodeDef.attr().find(attribName);
89 if (iter != nodeDef.attr().end())
91 const auto& attrValue = iter->second;
92 if (attrValue.value_case() == expectedValueCase)
101 "Attribute %1% of node %2% expected to have %3% as tensorflow::AttrValue::ValueCase, " 102 "but found %4% instead %5%")
105 %
static_cast<int>(expectedValueCase)
106 % static_cast<int>(attrValue.value_case())
112 float ReadMandatoryNodeFloatAttribute(
const tensorflow::NodeDef& nodeDef,
const std::string& name)
114 float attribValue = 0.0f;
115 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kF,
116 [&attribValue](
const tensorflow::AttrValue& attrValue)
118 attribValue = attrValue.f();
123 int32_t ReadMandatoryNodeInt32Attribute(
const tensorflow::NodeDef& nodeDef,
const std::string& name)
125 int32_t attribValue = 0u;
126 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kI,
127 [&attribValue](
const tensorflow::AttrValue& attrValue)
129 attribValue =
static_cast<int32_t
>(attrValue.i());
134 bool ReadMandatoryNodeBoolAttribute(
const tensorflow::NodeDef& nodeDef,
const std::string& name)
136 bool attribValue =
false;
137 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kB,
138 [&attribValue](
const tensorflow::AttrValue& attrValue)
140 attribValue =
static_cast<bool>(attrValue.b());
145 uint32_t ReadMandatoryNodeUint32Attribute(
const tensorflow::NodeDef& nodeDef,
const std::string& name)
147 uint32_t attribValue = 0u;
148 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kI,
149 [&attribValue](
const tensorflow::AttrValue& attrValue)
151 attribValue =
static_cast<uint32_t
>(attrValue.i());
156 std::string ReadMandatoryNodeStringAttribute(
const tensorflow::NodeDef& nodeDef,
const std::string& name)
158 std::string attribValue =
"";
159 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kS,
160 [&attribValue](
const tensorflow::AttrValue& attrValue)
162 attribValue = attrValue.s();
167 std::vector<uint32_t> ReadMandatoryNodeUint32ListAttribute(
const tensorflow::NodeDef& nodeDef,
168 const std::string& name)
170 std::vector<uint32_t> attriList;
171 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kList,
172 [&attriList](
const tensorflow::AttrValue& attrValue)
174 for (
int attriNum = 0; attriNum < attrValue.list().i_size(); ++attriNum)
176 attriList.push_back(static_cast<uint32_t>(attrValue.list().i(attriNum)));
183 std::vector<uint32_t> ReadOptionalNodeUint32ListAttribute(
const tensorflow::NodeDef& nodeDef,
184 const std::string& name)
186 std::vector<uint32_t> attriList;
187 ReadOptionalNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kList,
188 [&attriList](
const tensorflow::AttrValue& attrValue)
190 for (
int attriNum = 0; attriNum < attrValue.list().i_size(); ++attriNum)
192 attriList.push_back(static_cast<uint32_t>(attrValue.list().i(attriNum)));
199 std::string ReadOptionalNodeStringAttribute(
const tensorflow::NodeDef& nodeDef,
200 const std::string& name,
201 const std::string& defaultValue =
"")
203 std::string attribValue = defaultValue;
204 ReadOptionalNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kS,
205 [&attribValue](
const tensorflow::AttrValue& attrValue)
207 attribValue = attrValue.s();
212 bool ReadOptionalNodeBoolAttribute(
const tensorflow::NodeDef& nodeDef,
213 const std::string& name,
214 bool defaultValue =
false)
216 bool attribValue = defaultValue;
217 ReadOptionalNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kB,
218 [&attribValue](
const tensorflow::AttrValue& attrValue)
220 attribValue = attrValue.b();
225 tensorflow::DataType ReadMandatoryNodeTypeAttribute(
const tensorflow::NodeDef& nodeDef,
const std::string& name)
228 ReadMandatoryNodeAttributeImpl(nodeDef, name, tensorflow::AttrValue::kType,
229 [&attribValue](
const tensorflow::AttrValue& attrValue)
231 attribValue = attrValue.type();
238 std::vector<unsigned int> outDims(targetDims.begin(), targetDims.end());
239 const auto stretchDim = std::find(targetDims.begin(), targetDims.end(), -1);
241 if (stretchDim != targetDims.end())
243 if (std::find(std::next(stretchDim), targetDims.end(), -1) != targetDims.end())
248 "At most one component of shape can be -1 %1%")
252 auto targetNumElements =
254 std::accumulate(targetDims.begin(), targetDims.end(), -1, std::multiplies<int32_t>()));
255 auto stretchIndex =
static_cast<size_t>(std::distance(targetDims.begin(), stretchDim));
256 outDims[stretchIndex] = input.
GetNumElements() / targetNumElements;
260 reshapeInfo.
SetShape(
TensorShape{
static_cast<unsigned int>(outDims.size()), outDims.data() });
267 INetwork& m_Network,
const tensorflow::NodeDef& nodeDef)
271 const unsigned int matchDim = inputTensorInfo.
GetNumDimensions() - (isNHWC ? 1 : 3);
272 std::array<unsigned int, MaxNumOfTensorDimensions> reshapedDimensions;
273 std::fill_n(reshapedDimensions.begin(), inputTensorInfo.
GetNumDimensions(), 1);
274 reshapedDimensions[matchDim] = input1Info.
GetShape()[0];
279 const std::string reshapeLayerName =
"reshape_for-" + nodeDef.name();
292 OutputId ParseOutputId(
const std::string & name)
294 unsigned int outputNum = 0;
295 size_t colonPos = name.find_last_of(
":");
296 if (colonPos != std::string::npos)
298 int n = std::stoi(name.substr(colonPos+1));
304 "Output tensor id is out of range for %1% %2%")
308 outputNum =
static_cast<unsigned int>(n);
310 return OutputId(name.substr(0,colonPos),outputNum);
313 #define CHECK_DATA_FORMAT(NODE_DEF, FORMAT, NODE_TYPE) \ 314 if( FORMAT != "NHWC" && FORMAT != "NCHW" ) \ 316 throw ParseException( \ 319 "Unsupported data format %1% passed for %2% node %3%. " \ 320 "Only NHWC and NCHW supported %4%") \ 324 % CHECK_LOCATION().AsString())); \ 327 #define CHECK_PADDING_TYPE(NODE_DEF, PADDING) \ 328 if(PADDING != "SAME" && PADDING != "VALID" ) \ 330 throw ParseException( \ 333 "Only 'SAME' and 'VALID' padding supported. Got %1% for %2% %3%") \ 336 % CHECK_LOCATION().AsString())); \ 341 const std::map<std::string, TfParser::OperationParsingFunction> TfParser::ms_OperationNameToParsingFunctions = {
342 {
"Const", &TfParser::ParseConst },
343 {
"Add", &TfParser::ParseAdd },
344 {
"AddN", &TfParser::ParseAddN },
345 {
"BiasAdd", &TfParser::ParseBiasAdd },
346 {
"Identity", &TfParser::ParseIdentity },
347 {
"Conv2D", &TfParser::ParseConv2D },
348 {
"DepthwiseConv2dNative", &TfParser::ParseDepthwiseConv2D },
349 {
"ExpandDims", &TfParser::ParseExpandDims },
350 {
"FusedBatchNorm", &TfParser::ParseFusedBatchNorm },
351 {
"Gather", &TfParser::ParseGather},
352 {
"Greater", &TfParser::ParseGreater},
353 {
"ConcatV2", &TfParser::ParseConcat },
354 {
"LRN", &TfParser::ParseLrn },
355 {
"MatMul", &TfParser::ParseMatMul },
356 {
"Mean", &TfParser::ParseMean },
357 {
"Mul", &TfParser::ParseMul },
358 {
"Placeholder", &TfParser::ParsePlaceholder },
359 {
"RealDiv", &TfParser::ParseRealDiv },
360 {
"Relu", &TfParser::ParseRelu },
361 {
"Relu6", &TfParser::ParseRelu6 },
362 {
"Reshape", &TfParser::ParseReshape },
363 {
"ResizeBilinear", &TfParser::ParseResizeBilinear },
364 {
"Rsqrt", &TfParser::ParseRsqrt },
365 {
"Shape", &TfParser::ParseShape },
366 {
"Squeeze", &TfParser::ParseSqueeze },
367 {
"Sigmoid", &TfParser::ParseSigmoid },
368 {
"Softmax", &TfParser::ParseSoftmax },
369 {
"Softplus", &TfParser::ParseSoftplus },
370 {
"Split", &TfParser::ParseSplit },
371 {
"StridedSlice", &TfParser::ParseStridedSlice },
372 {
"Tanh", &TfParser::ParseTanh },
373 {
"MaxPool", &TfParser::ParseMaxPool },
374 {
"AvgPool", &TfParser::ParseAvgPool },
375 {
"Maximum", &TfParser::ParseMaximum },
376 {
"Minimum", &TfParser::ParseMinimum },
377 {
"Equal", &TfParser::ParseEqual },
378 {
"Pad", &TfParser::ParsePad },
379 {
"Sub", &TfParser::ParseSub },
380 {
"Pack" , &TfParser::ParseStack },
381 {
"Stack", &TfParser::ParseStack },
382 {
"Transpose", &TfParser::ParseTranspose },
385 const std::list<std::string> TfParser::m_ControlInputs = {
405 uint32_t filterSize,
bool samePadding,
406 uint32_t* paddingFront, uint32_t* paddingBack) {
411 uint32_t outputSize = (inputSize + stride - 1) / stride;
412 uint32_t temp = (outputSize - 1) * stride + filterSize;
413 if (temp > inputSize) {
414 *paddingFront = (temp - inputSize) / 2;
415 *paddingBack = (temp - inputSize) - *paddingFront;
420 void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t& outPadHead, uint32_t& outPadTail,
429 class ParsedTfOperation
432 ParsedTfOperation(
TfParser* parser,
const tensorflow::NodeDef& node)
438 virtual ~ParsedTfOperation() {};
440 const tensorflow::NodeDef& GetNode()
const {
return m_Node; }
444 virtual IOutputSlot& ResolveArmnnOutputSlot(
unsigned int tfOutputIndex) = 0;
447 virtual ParsedTfOperation* ResolveIdentityOperations()
454 const tensorflow::NodeDef& m_Node;
459 class SingleLayerParsedTfOperation :
public ParsedTfOperation
463 : ParsedTfOperation(parser, node)
468 IOutputSlot& ResolveArmnnOutputSlot(
unsigned int tfOutputIndex)
override 472 unsigned int armnnOutputSlotIdx = tfOutputIndex;
478 "The requested output slot #%1% " 479 "for %2% does not exist %3%")
492 class DeferredSingleLayerParsedTfOperation :
public SingleLayerParsedTfOperation
495 DeferredSingleLayerParsedTfOperation(
TfParser* parser,
const tensorflow::NodeDef& node)
496 : SingleLayerParsedTfOperation(parser, node,
nullptr)
500 IOutputSlot& ResolveArmnnOutputSlot(
unsigned int tfOutputIndex)
override 504 CreateLayerDeferred();
506 return SingleLayerParsedTfOperation::ResolveArmnnOutputSlot(tfOutputIndex);
510 virtual void CreateLayerDeferred() = 0;
515 : m_Network(nullptr, nullptr)
520 const tensorflow::NodeDef* TfParser::ResolveIdentityNode(
const tensorflow::NodeDef* nodeDef)
522 if (nodeDef->op() !=
"Identity")
527 if (nodeDef->input_size() != 1)
532 "Identity node should have a single input! %1% has %2% inputs %3%")
534 % nodeDef->input_size()
538 auto it = m_NodesByName.find(nodeDef->input(0));
539 if (it != m_NodesByName.end())
541 const tensorflow::NodeDef* inputNode = it->second;
542 return ResolveIdentityNode(inputNode);
549 "Cannot find what the Identity node %1% is linked to! %2%")
555 std::vector<OutputOfConstNodeDef>
556 TfParser::GetTfInputNodes(
const tensorflow::NodeDef& nodeDef)
const 558 std::vector<OutputOfConstNodeDef> ret;
560 if (nodeDef.op() ==
"Const")
566 ret.reserve(boost::numeric_cast<size_t>(nodeDef.input_size()));
567 for (
int j = 0; j < nodeDef.input_size(); ++j)
569 OutputId outputId = ParseOutputId(nodeDef.input(j));
571 if (nodeDef.input(j)[0] ==
'^')
578 if (inputIt == m_NodesByName.end())
583 "Can't find node '%1%', which is listed as an input of '%2%' %3%")
594 std::vector<OutputOfParsedTfOperation>
595 TfParser::GetInputParsedTfOperationsChecked(
const tensorflow::NodeDef& nodeDef,
596 std::size_t expectedNumInputs)
599 std::vector<OutputOfConstNodeDef> nodes = GetTfInputNodes(nodeDef);
600 const std::size_t numInputs = nodes.size();
601 if (numInputs != expectedNumInputs)
606 "Unexpected number of inputs for node %1%. Expected %2%, found %3% %4%")
613 std::vector<OutputOfParsedTfOperation> result;
614 for (
auto&& node : nodes)
616 auto it = m_ParsedTfOperations.find(node.m_IndexedValue->name());
617 if (it == m_ParsedTfOperations.end())
622 "Node with name '%1%' has not been parsed %2%")
623 % node.m_IndexedValue->name()
626 ParsedTfOperation* parsedOp = it->second.get();
628 parsedOp = parsedOp->ResolveIdentityOperations();
635 const tensorflow::NodeDef& nodeDef,
638 const std::string& layerName)
645 if (input0Dim != input1Dim)
649 if (input0Dim == 1 && input1Dim == 4)
651 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot,
true, *m_Network, nodeDef);
653 else if (input0Dim == 4 && input1Dim == 1)
655 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot,
true, *m_Network, nodeDef);
661 boost::format(
"Unsupported broadcast configuration for %1% operation %2% %3%")
674 std::vector<unsigned int> outputShape;
681 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
691 const tensorflow::NodeDef& nodeDef,
694 unsigned int numberOfAddition,
695 unsigned long numberOfLayersToConnect,
700 std::string layerName(nodeDef.name());
701 if (isOdd || numberOfLayersToConnect != 2)
704 layerName.append(
"_addN_").append(std::to_string(numberOfAddition));
706 return CreateAdditionLayer(nodeDef, input0Slot, input1Slot, layerName);
710 const tensorflow::NodeDef& nodeDef,
713 unsigned int numberOfAddition)
717 std::string layerName(nodeDef.name());
718 layerName.append(
"_addN_").append(std::to_string(numberOfAddition));
719 return CreateAdditionLayer(nodeDef, input0Slot, input1Slot, layerName);
723 const tensorflow::NodeDef& nodeDef,
729 return CreateAdditionLayer(nodeDef, input0Slot, input1Slot, nodeDef.name());
732 ParsedTfOperationPtr TfParser::ParseAddN(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
735 uint32_t numberOfInputs = ReadMandatoryNodeUint32Attribute(nodeDef,
"N");
736 if (numberOfInputs < 2)
742 "AddN Node with name '%1%' has less than two (%2) inputs %3%")
744 % std::to_string(numberOfInputs)
747 else if (numberOfInputs == 2)
750 return AddAdditionLayer(nodeDef,
false);
757 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, numberOfInputs);
758 unsigned int numberOfAdditions = 0;
759 std::vector<IConnectableLayer*> layers;
761 for (
unsigned int i = 0; i < numberOfInputs; ++i)
764 bool onSecondItem = i % 2;
769 nodeDef, inputs[ i - 1], inputs[i], numberOfAdditions);
770 layers.push_back(newLayer);
774 std::vector<IConnectableLayer*> layersToConnect(layers);
775 unsigned long numberOfLayersToConnect = layersToConnect.size();
776 bool isOdd = numberOfInputs % 2;
778 while (numberOfLayersToConnect > 1)
781 for (
unsigned long i = 0; i < numberOfLayersToConnect; ++i) {
782 bool onSecondItem = i % 2;
787 layersToConnect[i - 1],
790 numberOfLayersToConnect,
792 layers.push_back(newLayer);
796 layersToConnect = layers;
797 numberOfLayersToConnect = layersToConnect.size();
806 finalLayer = CreateAdditionLayer(nodeDef, inputs[numberOfInputs - 1], finalLayer);
808 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, finalLayer);
812 ParsedTfOperationPtr TfParser::ParseAdd(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
815 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
819 if (inputs[0].m_IndexedValue->GetNode().op() ==
"MatMul" &&
820 HasParsedConstTensor<float>(inputs[1].m_IndexedValue->GetNode().name()))
823 AddFullyConnectedLayer(inputs[0].m_IndexedValue->GetNode(),
824 &nodeDef,nodeDef.name().c_str());
825 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
827 else if (HasParsedConstTensor<float>(inputs[0].m_IndexedValue->GetNode().name()) &&
828 inputs[1].m_IndexedValue->GetNode().op() ==
"MatMul")
831 AddFullyConnectedLayer(inputs[1].m_IndexedValue->GetNode(),
832 &nodeDef,nodeDef.name().c_str());
833 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
838 return AddAdditionLayer(nodeDef);
842 ParsedTfOperationPtr TfParser::ParseBiasAdd(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
845 return AddAdditionLayer(nodeDef,
true);
849 class ParsedIdentityTfOperation :
public ParsedTfOperation
852 ParsedIdentityTfOperation(
TfParser* parser,
const tensorflow::NodeDef& node, ParsedTfOperation* representative)
853 : ParsedTfOperation(parser, node)
854 , m_Representative(representative)
858 virtual IOutputSlot& ResolveArmnnOutputSlot(
unsigned int tfOutputIndex)
override 861 return m_Representative->ResolveArmnnOutputSlot(tfOutputIndex);
864 virtual ParsedTfOperation* ResolveIdentityOperations()
override 866 return m_Representative->ResolveIdentityOperations();
870 ParsedTfOperation* m_Representative;
873 ParsedTfOperationPtr TfParser::ParseIdentity(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
876 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
878 return std::make_unique<ParsedIdentityTfOperation>(
this, nodeDef, inputs[0].m_IndexedValue);
884 template <
typename T>
889 const T* tensorData,
const TensorInfo& tensorInfo)
890 : DeferredSingleLayerParsedTfOperation(parser, node),
892 m_TensorInfo(tensorInfo)
897 void CreateLayerDeferred()
override 900 m_Layer = m_Parser->m_Network->AddConstantLayer(
ConstTensor(m_TensorInfo, m_Storage), m_Node.name().c_str());
904 ConstTensor GetConstTensor(std::vector<T>& outputTensorData)
const 908 memcpy(outputTensorData.data(), m_Storage.data(), m_TensorInfo.
GetNumBytes());
911 ConstTensor constTensor(m_TensorInfo, outputTensorData);
915 const T* GetStorage()
const 917 return m_Storage.data();
927 std::vector<T> m_Storage;
933 const tensorflow::NodeDef& nodeDef)
937 case tensorflow::DT_FLOAT:
938 return DataType::Float32;
940 case tensorflow::DT_INT32:
941 return DataType::Signed32;
947 "Unknown DataType %1% for node %2% %3%")
948 % tensorflow::DataType_Name(tfDataType)
954 struct ParseTfTensorValueList
956 template<
typename DataType>
958 const tensorflow::TensorProto& tfTensor,
959 unsigned int dstElements,
960 std::vector<int8_t>& outputData);
962 template <
typename DataType>
963 static void ReadData(
const void* srcData,
unsigned int numSrcElements,
964 std::vector<int8_t>& dstData,
unsigned int numDstElements)
967 if (numSrcElements == 0)
973 if (numDstElements == 0)
975 numDstElements = numSrcElements;
979 dstData.resize(std::max(numSrcElements, numDstElements) *
sizeof(
DataType));
985 std::copy(srcTensor, srcTensor + numSrcElements, dstTensor);
987 if (numDstElements > numSrcElements)
990 std::fill(dstTensor + numSrcElements, dstTensor + numDstElements, srcTensor[numSrcElements - 1]);
997 void ParseTfTensorValueList::Parse<float>(
const tensorflow::TensorProto& tfTensor,
998 unsigned int dstElements, std::vector<int8_t>& outputData)
1000 ReadData<float>(tfTensor.float_val().data(),
static_cast<unsigned int>(tfTensor.float_val_size()),
1001 outputData, dstElements);
1005 void ParseTfTensorValueList::Parse<int32_t>(
const tensorflow::TensorProto& tfTensor,
1006 unsigned int dstElements, std::vector<int8_t>& outputData)
1008 ReadData<int32_t>(tfTensor.int_val().data(),
static_cast<unsigned int>(tfTensor.int_val_size()),
1009 outputData, dstElements);
1012 template <
template<
typename>
class OperatorType,
typename T = int8_t>
1013 struct MakeTfOperation
1015 template<
typename DataType,
class... Args>
1016 inline static std::unique_ptr<OperatorType<DataType>> Parse(
TfParser* parser,
const tensorflow::NodeDef& node,
1019 return std::make_unique<OperatorType<DataType>>(parser, node, std::forward<Args>(args)...);
1024 struct MakeTfOperation<ParsedConstTfOperation>
1026 template<
typename DataType,
class... Args>
1027 inline static std::unique_ptr<ParsedConstTfOperation<DataType>> Parse(
TfParser* parser,
1028 const tensorflow::NodeDef& node,
const std::vector<int8_t>& tensorData,
const TensorInfo& tensorInfo)
1030 return std::make_unique<ParsedConstTfOperation<DataType>>(parser, node,
1031 reinterpret_cast<const DataType*
>(tensorData.data()), tensorInfo);
1035 template <
class FuncType>
1036 struct InvokeParseFunction
1038 template<
class ResType,
class... Args>
1039 inline static ResType Result(
DataType dataType, Args&&... args)
1041 if (dataType == DataType::Float32)
1043 return FuncType::template Parse<float>(std::forward<Args>(args)...);
1045 else if (dataType == DataType::Signed32)
1047 return FuncType::template Parse<int32_t>(std::forward<Args>(args)...);
1053 template<
class... Args>
1054 inline static void Result(
DataType dataType, Args&&... args)
1056 if (dataType == DataType::Float32)
1058 FuncType::template Parse<float>(std::forward<Args>(args)...);
1060 else if (dataType == DataType::Signed32)
1062 FuncType::template Parse<int32_t>(std::forward<Args>(args)...);
1067 ParsedTfOperationPtr TfParser::ParseConst(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
1072 if (nodeDef.attr().count(
"value") == 0)
1077 "Value not found for Const node - %1% %2%")
1082 const tensorflow::TensorProto& tfTensor = nodeDef.attr().at(
"value").tensor();
1083 const tensorflow::TensorShapeProto& tfTensorShape = tfTensor.tensor_shape();
1086 const auto GetDimensionSize = [](
auto& d) {
return d.size(); };
1088 std::vector<unsigned int> dimensionSizes;
1089 std::transform(tfTensorShape.dim().begin(), tfTensorShape.dim().end(),
1090 std::back_inserter(dimensionSizes), GetDimensionSize);
1094 unsigned int numElements = 0U;
1096 if (!dimensionSizes.empty())
1098 numElements = std::accumulate(dimensionSizes.begin(), dimensionSizes.end(),
1099 1U, std::multiplies<unsigned int>());
1102 std::vector<int8_t> tensorData;
1105 if (tfTensor.tensor_content().empty())
1107 InvokeParseFunction<ParseTfTensorValueList>::Result<
void>(dataType, tfTensor, numElements, tensorData);
1111 if (numElements == 0)
1113 const unsigned int tfNumElements =
1114 static_cast<unsigned int>(tensorData.size()) /
GetDataTypeSize(dataType);
1115 dimensionSizes.push_back(tfNumElements);
1121 tensorData.assign(tfTensor.tensor_content().begin(), tfTensor.tensor_content().end());
1124 if (numElements == 0)
1129 "No tensor shape found for Const node - %1% %2%")
1136 if (tensorData.empty())
1141 "No tensor data found for Const node - %1% %2%")
1146 const TensorInfo tensorInfo(static_cast<unsigned int>(dimensionSizes.size()),
1147 dimensionSizes.data(),
1152 if (tensorData.size() > tensorInfo.GetNumBytes())
1157 "Number of elements (%1%) should be less than or equal " 1158 "to the number of elements implied by the shape argument (%2%) for Const node - %3% %4%")
1160 % tensorInfo.GetNumElements()
1165 return InvokeParseFunction<MakeTfOperation<ParsedConstTfOperation>>::Result<ParsedTfOperationPtr>(
1166 dataType,
this, nodeDef, tensorData, tensorInfo);
1169 template<
typename Type>
1170 bool TfParser::HasParsedConstTensor(
const std::string & nodeName)
const 1172 auto it = m_ParsedTfOperations.find(nodeName);
1173 if (it == m_ParsedTfOperations.end())
1177 return dynamic_cast<ParsedConstTfOperation<Type>*
>(it->second.get()) !=
nullptr;
1180 template<
typename Type>
1181 bool TfParser::HasParsedConstTensor(ParsedTfOperation* parsedTfOpPtr)
const 1183 return dynamic_cast<ParsedConstTfOperation<Type>*
>(parsedTfOpPtr) !=
nullptr;
1186 unsigned int TfParser::GetConstInputIndex(
const std::vector<OutputOfParsedTfOperation>& inputs)
1188 for (
unsigned int i = 0; i < inputs.size(); i++)
1190 if (HasParsedConstTensor<int32_t>(inputs[i].m_IndexedValue->GetNode().name()))
1198 "ArmNN only supports operators with constant axis. %1%")
1204 const tensorflow::GraphDef& graphDef)
1207 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1208 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1211 if (!HasParsedConstTensor<float>(inputs[1].m_IndexedValue->GetNode().name()))
1216 "ArmNN only supports Convolution layers with constant weights for %1%, input %2% %3%")
1218 % inputs[1].m_IndexedValue->GetNode().name()
1221 ParsedConstTfOperation<float>* weightNode =
1222 PolymorphicDowncast<ParsedConstTfOperation<float> *>(inputs[1].m_IndexedValue);
1224 std::string paddingString = ReadMandatoryNodeStringAttribute(nodeDef,
"padding");
1225 std::string dataFormat = ReadMandatoryNodeStringAttribute(nodeDef,
"data_format");
1226 std::vector<uint32_t> strides = ReadMandatoryNodeUint32ListAttribute(nodeDef,
"strides");
1229 std::vector<uint32_t> dilations = ReadOptionalNodeUint32ListAttribute(nodeDef,
"dilations");
1230 if (!dilations.empty())
1232 for (
auto dilation : dilations)
1239 "ArmNN only supports Convolution layers with dilations [1,1,1,1] for %1% %2%")
1251 DataLayout dataLayout = dataFormat ==
"NHWC" ? DataLayout::NHWC : DataLayout::NCHW;
1268 dataLayout == DataLayout::NHWC ?
1269 std::initializer_list<unsigned int>{ 1, 2, 3, 0 } :
1270 std::initializer_list<unsigned int>{ 2, 3, 1, 0 };
1273 const TensorInfo& weightTensorInfo = weightNode->GetTensorInfo();
1277 std::vector<float> weightTensorSwizzledData(weightTensorInfo.
GetNumElements());
1279 weightNode->GetStorage(), weightTensorSwizzledData.data(),
sizeof(float));
1282 ConstTensor weightTensor(weightTensorSwizzledInfo, weightTensorSwizzledData);
1287 bool padding =
false;
1289 unsigned int outputHeight = 0;
1290 unsigned int outputWidth = 0;
1294 if (paddingString ==
"SAME")
1298 outputHeight =
static_cast<uint32_t
>(ceil(static_cast<float>(inputHeight) /
1300 outputWidth =
static_cast<uint32_t
>(ceil(static_cast<float>(inputWidth) /
1303 else if (paddingString ==
"VALID")
1307 outputHeight =
static_cast<uint32_t
>(ceil(static_cast<float>(inputHeight - weightHeight + 1) /
1309 outputWidth =
static_cast<uint32_t
>(ceil(static_cast<float>(inputWidth - weightWidth + 1) /
1315 case DataLayout::NHWC:
1322 case DataLayout::NCHW:
1338 nodeDef.name().c_str());
1342 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
1346 const tensorflow::GraphDef& graphDef)
1349 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1350 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1353 if (!HasParsedConstTensor<float>(inputs[1].m_IndexedValue->GetNode().name()))
1358 "ArmNN only supports Depthwise Convolution layer with constant weights. " 1359 "Non const input found %1% for node %2% %3%")
1360 % inputs[1].m_IndexedValue->GetNode().name()
1365 ParsedConstTfOperation<float>* weightNode =
1366 PolymorphicDowncast<ParsedConstTfOperation<float> *>(inputs[1].m_IndexedValue);
1368 std::string paddingString = ReadMandatoryNodeStringAttribute(nodeDef,
"padding");
1369 std::string dataFormat = ReadMandatoryNodeStringAttribute(nodeDef,
"data_format");
1370 std::vector<uint32_t> strides = ReadMandatoryNodeUint32ListAttribute(nodeDef,
"strides");
1377 DataLayout dataLayout = dataFormat ==
"NHWC" ? DataLayout::NHWC : DataLayout::NCHW;
1395 const TensorInfo& weightTensorInfo = weightNode->GetTensorInfo();
1399 std::vector<float> weightTensorSwizzledData(weightTensorInfo.
GetNumElements());
1401 weightNode->GetStorage(), weightTensorSwizzledData.data(),
sizeof(float));
1404 ConstTensor weightTensor(weightTensorSwizzledInfo, weightTensorSwizzledData);
1406 uint32_t weightHeight = weightTensor.
GetShape()[2];
1407 uint32_t weightWidth = weightTensor.
GetShape()[3];
1409 bool padding =
false;
1411 unsigned int outputHeight = 0;
1412 unsigned int outputWidth = 0;
1416 if (paddingString ==
"SAME")
1420 outputHeight =
static_cast<uint32_t
>(ceil(static_cast<float>(inputHeight) /
1422 outputWidth =
static_cast<uint32_t
>(ceil(static_cast<float>(inputWidth) /
1425 else if (paddingString ==
"VALID")
1429 outputHeight =
static_cast<uint32_t
>(ceil(static_cast<float>(inputHeight - weightHeight + 1) /
1431 outputWidth =
static_cast<uint32_t
>(ceil(static_cast<float>(inputWidth - weightWidth + 1) /
1437 case DataLayout::NHWC:
1444 case DataLayout::NCHW:
1460 nodeDef.name().c_str());
1464 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
1475 "Unsupported number of dimensions: %1% for input shape for ExpandDims %2% %3%")
1481 std::int32_t expandDim = ReadMandatoryNodeInt32Attribute(nodeDef,
"Tdim");
1484 std::vector<uint32_t> outputDims;
1487 if (expandDim >= -1 - inputDimSize && expandDim <= inputDimSize)
1491 auto currentDimension = inputTensorInfo.
GetShape()[i];
1492 outputDims.push_back(currentDimension);
1498 auto getPosition = std::next(outputDims.begin() + 0, expandDim);
1499 outputDims.insert(getPosition, 1);
1507 auto getPosition = std::next(outputDims.begin() + outputDimSize, expandDim);
1508 outputDims.insert(getPosition, 1);
1516 "Cannot expand dimension %1% in input tensor with %2% dimension %3%")
1522 if (outputDims.size() > 4)
1527 "Unsupported number of dimensions: %1% for output shape for ExpandDims %2% %3%")
1539 return outTensorInfo;
1542 ParsedTfOperationPtr TfParser::ParseExpandDims(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
1545 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
1547 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1559 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
1563 const tensorflow::GraphDef& graphDef)
1566 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 5);
1568 if (!HasParsedConstTensor<float>(inputs[1].m_IndexedValue->GetNode().name()))
1573 "ArmNN only supports FusedBatchNormalization layers with constant scale. " 1574 "Input %1%. Node %2% %3%")
1575 % inputs[1].m_IndexedValue->GetNode().name()
1579 ParsedConstTfOperation<float>* scaleNode =
1580 PolymorphicDowncast<ParsedConstTfOperation<float> *>(inputs[1].m_IndexedValue);
1582 if (!HasParsedConstTensor<float>(inputs[2].m_IndexedValue->GetNode().name()))
1587 "ArmNN only supports FusedBatchNormalization layers with constant offset. " 1588 "Input %1%. Node %2% %3%")
1589 % inputs[2].m_IndexedValue->GetNode().name()
1593 ParsedConstTfOperation<float>* offsetNode =
1594 PolymorphicDowncast<ParsedConstTfOperation<float> *>(inputs[2].m_IndexedValue);
1596 if (!HasParsedConstTensor<float>(inputs[3].m_IndexedValue->GetNode().name()))
1601 "ArmNN only supports FusedBatchNormalization layers with constant mean. " 1602 "Input %1%. Node %2% %3%")
1603 % inputs[3].m_IndexedValue->GetNode().name()
1607 ParsedConstTfOperation<float>* meanNode =
1608 PolymorphicDowncast<ParsedConstTfOperation<float> *>(inputs[3].m_IndexedValue);
1610 if (!HasParsedConstTensor<float>(inputs[4].m_IndexedValue->GetNode().name()))
1615 "ArmNN only supports FusedBatchNormalization layers with constant variance. " 1616 "Input %1%. Node %2% %3%")
1617 % inputs[4].m_IndexedValue->GetNode().name()
1621 ParsedConstTfOperation<float>* varianceNode =
1622 PolymorphicDowncast<ParsedConstTfOperation<float> *>(inputs[4].m_IndexedValue);
1624 const std::string dataFormat = ReadOptionalNodeStringAttribute(nodeDef,
"data_format",
"NHWC");
1629 desc.
m_Eps = ReadMandatoryNodeFloatAttribute(nodeDef,
"epsilon");
1630 desc.
m_DataLayout = dataFormat ==
"NHWC" ? DataLayout::NHWC : DataLayout::NCHW;
1634 std::vector<float> scaleTensorData;
1635 ConstTensor scaleTensor = scaleNode->GetConstTensor(scaleTensorData);
1637 std::vector<float> offsetTensorData;
1638 ConstTensor offsetTensor = offsetNode->GetConstTensor(offsetTensorData);
1640 std::vector<float> meanTensorData;
1641 ConstTensor meanTensor = meanNode->GetConstTensor(meanTensorData);
1643 std::vector<float> varianceTensorData;
1644 ConstTensor varianceTensor = varianceNode->GetConstTensor(varianceTensorData);
1651 nodeDef.name().c_str());
1653 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1658 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
1661 bool TfParser::IsSupportedLeakyReluPattern(
const tensorflow::NodeDef& mulNodeDef,
1662 size_t alphaLayerIndex,
1667 const tensorflow::NodeDef& otherNodeDef = otherOp.
m_IndexedValue->GetNode();
1676 if (mulNodeDef.op() ==
"Mul")
1678 size_t otherLayerIndex = (alphaLayerIndex == 0 ? 1 : 0);
1679 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(mulNodeDef, 2);
1682 ARMNN_ASSERT((otherLayerIndex == 0 || alphaLayerIndex == 0));
1683 ARMNN_ASSERT((otherLayerIndex == 1 || alphaLayerIndex == 1));
1684 ARMNN_ASSERT(((otherLayerIndex + alphaLayerIndex) == 1));
1686 if (inputs[otherLayerIndex].m_IndexedValue->GetNode().name() == otherNodeDef.name())
1688 if (HasParsedConstTensor<float>(inputs[alphaLayerIndex].m_IndexedValue->GetNode().name()))
1690 ParsedConstTfOperation<float>* alpha =
1691 PolymorphicDowncast<ParsedConstTfOperation<float> *>(
1692 inputs[alphaLayerIndex].m_IndexedValue);
1694 std::vector<float> const_data;
1695 ConstTensor const_tensor = alpha->GetConstTensor(const_data);
1697 if (const_data.size() == 1)
1699 desc.
m_Function = ActivationFunction::LeakyReLu;
1700 desc.
m_A = const_data[0];
1712 const tensorflow::GraphDef& graphDef)
1715 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1716 if (inputs.size() != 2)
1721 "Maximum expects two inputs!. Got %1% for Node %2% %3%")
1727 auto inputNode0 = inputs[0].m_IndexedValue->GetNode();
1728 auto inputNode1 = inputs[1].m_IndexedValue->GetNode();
1741 if (IsSupportedLeakyReluPattern(inputNode0, 0, inputs[1], &outputOfLeakyRelu, desc) ||
1742 IsSupportedLeakyReluPattern(inputNode0, 1, inputs[1], &outputOfLeakyRelu, desc) ||
1743 IsSupportedLeakyReluPattern(inputNode1, 0, inputs[0], &outputOfLeakyRelu, desc) ||
1744 IsSupportedLeakyReluPattern(inputNode1, 1, inputs[0], &outputOfLeakyRelu, desc))
1751 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
1757 return AddMaximumLayer(nodeDef);
1761 std::pair<armnn::IOutputSlot*, armnn::IOutputSlot*> TfParser::ProcessElementwiseInputSlots(
1762 const tensorflow::NodeDef& nodeDef,
const std::string& layerName)
1764 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1766 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1767 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
1771 if (input0Dim != input1Dim)
1775 if (input0Dim == 1 && input1Dim == 4)
1777 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot,
true, *m_Network, nodeDef);
1779 else if (input0Dim == 4 && input1Dim == 1)
1781 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot,
true, *m_Network, nodeDef);
1787 boost::format(
"Unsupported broadcast configuration for %1% operation %2% %3%")
1793 return {input0Slot, input1Slot};
1800 const tensorflow::NodeDef& nodeDef)
1807 std::vector<unsigned int> outputShape;
1814 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
1820 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
1827 const tensorflow::NodeDef& nodeDef)
1833 std::vector<unsigned int> outputShape;
1840 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
1846 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
1850 const tensorflow::GraphDef& graphDef)
1853 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1854 IOutputSlot& params = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1855 IOutputSlot& indices = inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
1857 descriptor.
m_Axis = ReadMandatoryNodeInt32Attribute(nodeDef,
"axis");
1862 unsigned int outputDim = paramsDim - 1 + indicesDim;
1864 std::vector<unsigned int> dimSizes;
1866 for (
unsigned int i = 0; i < indicesDim; ++i)
1870 for (
unsigned int i = 1; i < paramsDim; ++i)
1882 params.
Connect(layer->GetInputSlot(0));
1883 indices.
Connect(layer->GetInputSlot(1));
1885 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
1889 const tensorflow::GraphDef& graphDef)
1892 std::pair<armnn::IOutputSlot*, armnn::IOutputSlot*> inputLayers = ProcessElementwiseInputSlots(nodeDef,
"Greater");
1899 return ProcessComparisonLayer(input0Slot, input1Slot, layer, nodeDef);
1903 const tensorflow::GraphDef& graphDef)
1906 std::pair<armnn::IOutputSlot*, armnn::IOutputSlot*> inputLayers = ProcessElementwiseInputSlots(nodeDef,
"Equal");
1913 return ProcessComparisonLayer(input0Slot, input1Slot, layer, nodeDef);
1917 const tensorflow::GraphDef& graphDef)
1920 std::pair<armnn::IOutputSlot*, armnn::IOutputSlot*> inputLayers = ProcessElementwiseInputSlots(nodeDef,
"Minimum");
1926 return ProcessElementwiseLayer(input0Slot, input1Slot, layer, nodeDef);
1929 ParsedTfOperationPtr TfParser::ParseSub(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
1932 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
1934 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1935 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
1942 const bool isNHWC =
true;
1943 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
1948 const bool isNHWC =
true;
1949 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
1966 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
1969 ParsedTfOperationPtr TfParser::ParseStack(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
1972 std::vector<OutputOfConstNodeDef> nodes = GetTfInputNodes(nodeDef);
1974 unsigned int numInputs =
static_cast<unsigned int>(nodes.size());
1980 "Pack/Stack expects at least one input. Got %1% for Node %2% %3%")
1986 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, numInputs);
1988 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
1993 int32_t axis = ReadMandatoryNodeInt32Attribute(nodeDef,
"axis");
1994 const int sNumDimensions = (
static_cast<int>(numDimensions) + 1);
1995 if (!(axis < sNumDimensions && axis >= -sNumDimensions))
2000 "Axis index is not in range. Got %1% for Node %2% %3%")
2008 axis =
static_cast<int32_t
>(numDimensions) + axis + 1;
2012 stackDescriptor.
m_Axis =
static_cast<uint32_t
>(axis);
2013 stackDescriptor.
m_NumInputs =
static_cast<uint32_t
>(numInputs);
2016 const unsigned int supportedNumDims = 4;
2017 for (
unsigned int viewIndex = 0; viewIndex < numInputs; ++viewIndex)
2019 IOutputSlot& inputSlot = inputs[viewIndex].m_IndexedValue->ResolveArmnnOutputSlot(inputs[viewIndex].m_Index);
2028 "The number of dimensions: %1% for input tensors of the " 2029 "Pack/Stack op. Number of dimensions should be less than %2% %3%")
2036 std::vector<unsigned int> outputDimensions;
2039 outputDimensions.push_back(stackDescriptor.
m_InputShape[i]);
2041 outputDimensions.insert(outputDimensions.begin() + axis, numInputs);
2046 for (
unsigned int viewIndex = 0; viewIndex < numInputs; ++viewIndex)
2048 IOutputSlot& inputSlot = inputs[viewIndex].m_IndexedValue->ResolveArmnnOutputSlot(inputs[viewIndex].m_Index);
2054 outputDimensions.data(),
2057 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2060 ParsedTfOperationPtr TfParser::ParseTranspose(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
2064 auto inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2065 const auto inputCount = inputs.size();
2067 if (inputCount != 2)
2072 "The number of given input is %1%. It should be two for Transpose op." 2079 auto* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2081 const auto constInput = inputs[GetConstInputIndex(inputs)];
2082 auto* permuteVectorInput =
2083 PolymorphicDowncast<ParsedConstTfOperation<int32_t>*>(constInput.m_IndexedValue);
2084 const auto& permuteVectorInfo = permuteVectorInput->
GetTensorInfo();
2086 std::vector<int32_t> permuteVectorData;
2087 permuteVectorInput->GetConstTensor(permuteVectorData);
2089 std::vector<unsigned int> armnnPermuteVectorData(permuteVectorData.begin(), permuteVectorData.end());
2091 const auto permutationVector =
PermutationVector(armnnPermuteVectorData.data(), permuteVectorInfo.GetNumElements());
2104 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2109 const std::string& nodeName)
2111 unsigned int rank = paddingTensor.
GetShape()[0];
2113 if (rank != expectedRank)
2118 "Expected the padding tensor to be of rank %1 not %2 on Node %3 %4.")
2124 unsigned int second = paddingTensor.
GetShape()[1];
2130 "Expected the padding tensor to be of dimensions [%1, 2] not [%1, %2] on Node %3 %4.")
2140 const std::vector<std::pair<unsigned int, unsigned int>>& padList)
2143 std::vector<unsigned int> outDims;
2144 for (
unsigned int i = 0; i < numDims; ++i)
2146 unsigned int dimSize = inputTensorInfo.
GetShape()[i];
2147 const std::pair<unsigned int, unsigned int>& dimPadding = padList[i];
2148 dimSize += dimPadding.first;
2149 dimSize += dimPadding.second;
2150 outDims.push_back(dimSize);
2152 TensorInfo paddedTensorInfo = inputTensorInfo;
2153 unsigned int outDimsSize =
static_cast<unsigned int>(outDims.size());
2155 return paddedTensorInfo;
2159 const tensorflow::GraphDef& graphDef)
2165 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2166 IOutputSlot& previousLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2168 if (!HasParsedConstTensor<int32_t>(inputs[1].m_IndexedValue))
2173 "ArmNN only supports Pad with constant padding. " 2174 "Input %1%. Node %2% %3%")
2175 % inputs[1].m_IndexedValue->GetNode().name()
2180 ParsedConstTfOperation<int32_t>* paddingTensorOp =
2181 PolymorphicDowncast<ParsedConstTfOperation<int32_t>*>(inputs[1].m_IndexedValue);
2183 std::vector<int32_t> paddingTensorData;
2184 ConstTensor paddingTensor = paddingTensorOp->GetConstTensor(paddingTensorData);
2191 std::vector<std::pair<unsigned int, unsigned int>> padList;
2192 unsigned int rank =
CheckPaddingTensor(paddingTensor, inputTensorInfo, nodeDef.name());
2193 for (
unsigned int i = 0; i < rank; ++i)
2195 std::pair<unsigned int, unsigned int> paddingForDim;
2196 for (
unsigned int j = 0; j < 2; j++)
2198 unsigned int index = (i * 2) + j;
2199 int paddingAmount = paddingTensorData[index];
2201 if (paddingAmount < 0)
2206 "Negative amount %1 specified at [%2, %3] of padding tensor on Node %4 %5.")
2215 paddingForDim.first =
static_cast<unsigned int>(paddingAmount);
2219 paddingForDim.second =
static_cast<unsigned int>(paddingAmount);
2222 padList.push_back(paddingForDim);
2230 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2234 const tensorflow::GraphDef& graphDef)
2237 std::vector<OutputOfConstNodeDef> nodes = GetTfInputNodes(nodeDef);
2240 unsigned int numInputs =
static_cast<unsigned int>(nodes.size());
2242 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, numInputs);
2245 unsigned int index = GetConstInputIndex(inputs);
2247 ParsedConstTfOperation<int32_t>* shapeNode =
2248 PolymorphicDowncast<ParsedConstTfOperation<int32_t>*>(inputs[index].m_IndexedValue);
2250 std::vector<int32_t> axisTensorData;
2251 shapeNode->GetConstTensor(axisTensorData);
2254 const unsigned int concatDim =
static_cast<unsigned int>(axisTensorData[0]);
2257 if (concatDim == 0 || concatDim == 2)
2262 "Dimension %1% for concatenation is not supported by Armnn. " 2269 const unsigned int supportedNumDims = 4;
2270 unsigned int numConcatViews = numInputs - 1;
2271 OriginsDescriptor concatDescriptor(static_cast<uint32_t>(numConcatViews), supportedNumDims);
2274 unsigned int mergeDim = 0;
2275 for (
unsigned int viewIndex = 0; viewIndex < numConcatViews; ++viewIndex)
2278 IOutputSlot& inputSlot = inputs[viewIndex].m_IndexedValue->ResolveArmnnOutputSlot(inputs[viewIndex].m_Index);
2287 "The number of dimensions: %1% for input tensors of the " 2288 "concatenation op should be %2% %3%")
2295 mergeDims = inputTensorInfo.
GetShape();
2296 unsigned int* viewOrigin =
const_cast<unsigned int*
>(concatDescriptor.
GetViewOrigin(viewIndex));
2297 std::fill(viewOrigin, viewOrigin + supportedNumDims, 0);
2301 mergeDim += mergeDims[concatDim];
2305 mergeDims[concatDim] = mergeDim;
2310 for (
unsigned int viewIndex = 0; viewIndex < numConcatViews; ++viewIndex)
2312 IOutputSlot& inputSlot = inputs[viewIndex].m_IndexedValue->ResolveArmnnOutputSlot(inputs[viewIndex].m_Index);
2316 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2320 const tensorflow::GraphDef& graphDef)
2330 if (tfDataType != tensorflow::DT_INT32)
2335 "Armnn only supports DT_INT32 as out_type. Got %1% for Node %2% %3%")
2336 % tensorflow::DataType_Name(tfDataType)
2341 const std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2342 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2346 std::vector<int32_t> shapeTensorData;
2347 shapeTensorData.reserve(prevLayerDimensions);
2349 for (
unsigned int i=0; i<prevLayerDimensions; ++i)
2351 shapeTensorData.push_back(static_cast<int32_t>(prevLayerTensorInfo.
GetShape()[i]));
2354 TensorInfo shapeTensorInfo(1, &prevLayerDimensions, DataType::Signed32);
2356 return std::make_unique<ParsedConstTfOperation<int32_t>>(
this,
2358 &shapeTensorData[0],
2363 const tensorflow::GraphDef& graphDef)
2366 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2367 ParsedTfOperation* inputNode = inputs[0].m_IndexedValue;
2369 if (!HasParsedConstTensor<int32_t>(inputs[1].m_IndexedValue->GetNode().name()))
2374 "ArmNN only supports Reshape layers with constant shapes. " 2375 "Input %1% Node %2% %3%")
2376 % inputs[1].m_IndexedValue->GetNode().name()
2380 ParsedConstTfOperation<int32_t>* shapeNode =
2381 PolymorphicDowncast<ParsedConstTfOperation<int32_t>*>(inputs[1].m_IndexedValue);
2383 armnn::IOutputSlot& prevLayerOutputSlot = inputNode->ResolveArmnnOutputSlot(inputs[0].m_Index);
2384 TensorInfo inputTensorInfo = prevLayerOutputSlot.GetTensorInfo();
2386 std::vector<int32_t> shapeTensorData;
2387 ConstTensor shapeTensor = shapeNode->GetConstTensor(shapeTensorData);
2388 const TensorInfo outputTensorInfo = PrepareReshape(inputTensorInfo, shapeTensorData);
2398 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2402 const tensorflow::GraphDef& graphDef)
2405 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2407 if (!HasParsedConstTensor<int32_t>(inputs[1].m_IndexedValue->GetNode().name()))
2412 "ArmNN only supports ResizeBilinear layers with constant sizes. " 2413 "Input %1%. Node %2% %3%")
2414 % inputs[1].m_IndexedValue->GetNode().name()
2418 ParsedConstTfOperation<int32_t>* sizeNode =
2419 PolymorphicDowncast<ParsedConstTfOperation<int32_t>*>(inputs[1].m_IndexedValue);
2422 if (ReadOptionalNodeBoolAttribute(nodeDef,
"align_corners",
false))
2427 "ArmNN only supports ResizeBilinear layers with align_corners set to false. " 2434 std::vector<int32_t> sizeTensorData;
2435 ConstTensor sizeTensor = sizeNode->GetConstTensor(sizeTensorData);
2441 desc.
m_TargetWidth =
static_cast<uint32_t
> (sizeTensorData[1]);
2446 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2450 unsigned int outBatch = inputTensorInfo.
GetShape()[0];
2451 unsigned int outChannels = inputTensorInfo.
GetShape()[3];
2454 TensorShape outShape({outBatch, outHeight, outWidth, outChannels });
2461 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2470 if (tfDataType == tensorflow::DT_FLOAT)
2472 type = DataType::Float32;
2474 else if (tfDataType == tensorflow::DT_INT32)
2476 type = DataType::Signed32;
2482 boost::format(
"Unsupported DataType %1% for Squeeze operation %2% %3%")
2483 % tensorflow::DataType_Name(tfDataType)
2494 "Unsupported number of dimensions: %1% for input shape for Squeeze %2% %3%")
2500 std::vector<uint32_t> squeezeDims = ReadOptionalNodeUint32ListAttribute(nodeDef,
"squeeze_dims");
2501 static const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
2503 if (squeezeDims.empty())
2505 squeezeDims.assign(dimensionSequence,
2509 std::vector<uint32_t> outputDims;
2512 bool skipSqueeze = (std::find(squeezeDims.begin(), squeezeDims.end(), i) == squeezeDims.end());
2513 auto currentDimension = inputTensorInfo.
GetShape()[i];
2514 if (skipSqueeze || currentDimension != 1)
2516 outputDims.push_back(currentDimension);
2520 if (outputDims.size() > 4)
2525 "Unsupported number of dimensions: %1% for output shape for Squeeze %2% %3%")
2536 outTensorInfo.SetDataType(type);
2538 return outTensorInfo;
2541 ParsedTfOperationPtr TfParser::ParseSqueeze(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
2544 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2546 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2558 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2561 ParsedTfOperationPtr TfParser::ParseLrn(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
2564 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2567 normalizationDescriptor.
m_NormMethodType = NormalizationAlgorithmMethod::LocalBrightness;
2568 normalizationDescriptor.
m_NormChannelType = NormalizationAlgorithmChannel::Across;
2569 normalizationDescriptor.
m_Alpha = ReadMandatoryNodeFloatAttribute(nodeDef,
"alpha");
2570 normalizationDescriptor.
m_Beta = ReadMandatoryNodeFloatAttribute(nodeDef,
"beta");
2571 normalizationDescriptor.
m_K = ReadMandatoryNodeFloatAttribute(nodeDef,
"bias");
2572 normalizationDescriptor.
m_NormSize = ReadMandatoryNodeUint32Attribute(nodeDef,
"depth_radius");
2578 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2580 nodeDef.name().c_str());
2584 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2596 : DeferredSingleLayerParsedTfOperation(parser, node)
2600 void CreateLayerDeferred()
override 2603 m_Layer = m_Parser->AddFullyConnectedLayer(m_Node,
nullptr, m_Node.name().c_str());
2607 ParsedTfOperationPtr TfParser::ParseMatMul(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
2612 return std::make_unique<ParsedMatMulTfOperation>(
this, nodeDef);
2615 ParsedTfOperationPtr TfParser::ParseMean(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
2618 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
2619 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2622 if (inputs.size() != 2)
2625 boost::str(boost::format(
"Mean expects two inputs!. Got %1% for Node %2% %3%")
2631 bool keepDims = ReadMandatoryNodeBoolAttribute(nodeDef,
"keep_dims");
2633 ParsedConstTfOperation<int32_t>* axisNode =
2634 PolymorphicDowncast<ParsedConstTfOperation<int32_t>*>(inputs[1].m_IndexedValue);
2636 const TensorInfo& axisTensorInfo = axisNode->GetTensorInfo();
2638 ConstTensor axisTensor(axisTensorInfo, axisNode->GetStorage());
2639 const int* axisData =
static_cast<const int*
>(axisTensor.GetMemoryArea());
2648 std::vector<int> rawAxisVector(axisData, axisData + axisTensorInfo.GetNumElements());
2649 std::set<unsigned int> positiveAxisSet;
2652 std::transform(rawAxisVector.begin(), rawAxisVector.end(),
2653 std::inserter(positiveAxisSet, positiveAxisSet.begin()),
2654 [rank](
int i) ->
unsigned int {
return static_cast<unsigned int>((i + rank) % rank); });
2660 meanDescriptor.
m_Axis.assign(positiveAxisSet.begin(), positiveAxisSet.end());
2667 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2679 : DeferredSingleLayerParsedTfOperation(parser, node)
2683 void CreateLayerDeferred()
override 2686 m_Layer = m_Parser->AddMultiplicationLayer(m_Node);
2690 ParsedTfOperationPtr TfParser::ParseMul(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
2694 return std::make_unique<ParsedMulTfOperation>(
this, nodeDef);
2698 const tensorflow::GraphDef& graphDef)
2702 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 0);
2706 auto it = m_InputShapes.find(nodeDef.name());
2707 if (it == m_InputShapes.end())
2712 "Missing input shape for Placeholder '%1%' %2%")
2716 TensorInfo tensorInfo(it->second, DataType::Float32);
2722 TrackInputBinding(layer, layerId, tensorInfo);
2724 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2727 ParsedTfOperationPtr TfParser::ParseRealDiv(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
2730 return AddRealDivLayer(nodeDef);
2734 const tensorflow::GraphDef& graphDef)
2739 activationDesc.
m_Function = ActivationFunction::ReLu;
2740 return AddActivationLayer(nodeDef, activationDesc);
2744 const tensorflow::GraphDef& graphDef)
2749 activationDesc.
m_Function = ActivationFunction::BoundedReLu;
2750 activationDesc.
m_A = 6.0f;
2751 activationDesc.
m_B = 0.0f;
2753 return AddActivationLayer(nodeDef, activationDesc);
2757 const tensorflow::GraphDef& graphDef)
2762 activationDesc.
m_Function = ActivationFunction::Sigmoid;
2764 return AddActivationLayer(nodeDef, activationDesc);
2768 const tensorflow::GraphDef &graphDef)
2772 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2777 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2781 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2785 const tensorflow::GraphDef& graphDef)
2789 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2794 IOutputSlot& prevLayerSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2798 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2802 const tensorflow::GraphDef& graphDef)
2806 std::vector<OutputOfConstNodeDef> nodes = GetTfInputNodes(nodeDef);
2807 unsigned int numInputs =
static_cast<unsigned int>(nodes.size());
2808 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, numInputs);
2811 unsigned int index = GetConstInputIndex(inputs);
2813 ParsedConstTfOperation<int32_t>* shapeNode =
2814 PolymorphicDowncast<ParsedConstTfOperation<int32_t>*>(inputs[index].m_IndexedValue);
2816 std::vector<int32_t> axisTensorData;
2817 shapeNode->GetConstTensor(axisTensorData);
2820 const unsigned int splitDim =
static_cast<unsigned int>(axisTensorData[0]);
2823 if (splitDim == 0 || splitDim == 2)
2828 "Dimension %1% for split is not supported by Armnn. " 2836 uint32_t num_split = ReadMandatoryNodeUint32Attribute(nodeDef,
"num_split");
2838 IOutputSlot& inputSlot = inputs[1 - index].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1 - index].m_Index);
2841 const unsigned int supportedNumDims = 4;
2844 if (inputDimSize != supportedNumDims)
2849 "The number of dimensions: %1% for input tensors of the " 2850 "split op should be %2% %3%")
2856 std::vector<unsigned int> splitterDimSizes(inputDimSize);
2859 for (
unsigned int i = 0; i < inputDimSize; ++i)
2861 splitterDimSizes[i] = inputTensorInfo.
GetShape()[i];
2864 if (splitterDimSizes[splitDim] % num_split != 0)
2866 throw ParseException(
"Number of splits must evenly divide the dimension");
2868 splitterDimSizes[splitDim] /= num_split;
2871 for (
unsigned int g = 0; g < num_split; ++g)
2874 for (
unsigned int dimIdx = 0; dimIdx < splitterDimSizes.size(); ++dimIdx)
2876 splitDesc.
SetViewSize(g, dimIdx, splitterDimSizes[dimIdx]);
2886 splitterDimSizes.data());
2893 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2897 const tensorflow::GraphDef& graphDef)
2902 activationDesc.
m_Function = ActivationFunction::SoftReLu;
2904 return AddActivationLayer(nodeDef, activationDesc);
2908 const tensorflow::GraphDef& graphDef)
2912 std::vector<OutputOfConstNodeDef> nodes = GetTfInputNodes(nodeDef);
2913 unsigned int numInputs =
static_cast<unsigned int>(nodes.size());
2914 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, numInputs);
2916 ParsedConstTfOperation<int32_t>* beginNode =
2917 PolymorphicDowncast<ParsedConstTfOperation<int32_t> *>(inputs[1].m_IndexedValue);
2918 std::vector<int32_t> beginTensorData;
2919 beginNode->GetConstTensor(beginTensorData);
2921 ParsedConstTfOperation<int32_t>* endNode =
2922 PolymorphicDowncast<ParsedConstTfOperation<int32_t> *>(inputs[2].m_IndexedValue);
2923 std::vector<int32_t> endTensorData;
2924 endNode->GetConstTensor(endTensorData);
2926 ParsedConstTfOperation<int32_t>* stridesNode =
2927 PolymorphicDowncast<ParsedConstTfOperation<int32_t> *>(inputs[3].m_IndexedValue);
2928 std::vector<int32_t> stridesTensorData;
2929 stridesNode->GetConstTensor(stridesTensorData);
2932 desc.
m_Begin = beginTensorData;
2933 desc.
m_End = endTensorData;
2935 desc.
m_BeginMask = ReadMandatoryNodeInt32Attribute(nodeDef,
"begin_mask");
2936 desc.
m_EndMask = ReadMandatoryNodeInt32Attribute(nodeDef,
"end_mask");
2937 desc.
m_EllipsisMask = ReadMandatoryNodeInt32Attribute(nodeDef,
"ellipsis_mask");
2938 desc.
m_NewAxisMask = ReadMandatoryNodeInt32Attribute(nodeDef,
"new_axis_mask");
2939 desc.
m_ShrinkAxisMask = ReadMandatoryNodeInt32Attribute(nodeDef,
"shrink_axis_mask");
2943 IOutputSlot& prevLayerSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2952 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2955 ParsedTfOperationPtr TfParser::ParseTanh(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
2960 activationDesc.
m_Function = ActivationFunction::TanH;
2961 activationDesc.
m_A = 1.0f;
2962 activationDesc.
m_B = 1.0f;
2964 return AddActivationLayer(nodeDef, activationDesc);
2970 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2974 IOutputSlot& prevLayerOutputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
2977 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
2981 const tensorflow::GraphDef& graphDef)
2983 return ParsePooling2d(nodeDef, graphDef, PoolingAlgorithm::Max);
2987 const tensorflow::GraphDef& graphDef)
2989 return ParsePooling2d(nodeDef, graphDef, PoolingAlgorithm::Average);
2997 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 1);
2998 IOutputSlot& inputSlot = inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
3001 if (inputs.size() != 1)
3006 "2D Pooling expects one input!. Got %1% for Node %2% %3%")
3012 std::string paddingString = ReadMandatoryNodeStringAttribute(nodeDef,
"padding");
3013 std::string dataFormat = ReadMandatoryNodeStringAttribute(nodeDef,
"data_format");
3014 std::vector<uint32_t> strides = ReadMandatoryNodeUint32ListAttribute(nodeDef,
"strides");
3015 std::vector<uint32_t> ksize = ReadMandatoryNodeUint32ListAttribute(nodeDef,
"ksize");
3023 DataLayout dataLayout = dataFormat ==
"NHWC" ? DataLayout::NHWC : DataLayout::NCHW;
3035 bool padding =
false;
3037 unsigned int outputHeight = 0;
3038 unsigned int outputWidth = 0;
3042 if (paddingString ==
"SAME")
3046 outputHeight =
static_cast<uint32_t
>(ceil(static_cast<float>(inputHeight) /
3047 static_cast<float>(pooling2dDescriptor.
m_StrideY)));
3048 outputWidth =
static_cast<uint32_t
>(ceil(static_cast<float>(inputWidth) /
3049 static_cast<float>(pooling2dDescriptor.
m_StrideX)));
3051 else if (paddingString ==
"VALID")
3055 outputHeight =
static_cast<uint32_t
>(ceil(
3056 static_cast<float>(inputHeight - pooling2dDescriptor.
m_PoolHeight + 1) /
3057 static_cast<float>(pooling2dDescriptor.
m_StrideY)));
3058 outputWidth =
static_cast<uint32_t
>(ceil(
3059 static_cast<float>(inputWidth - pooling2dDescriptor.
m_PoolWidth + 1) /
3060 static_cast<float>(pooling2dDescriptor.
m_StrideX)));
3065 case DataLayout::NHWC:
3072 case DataLayout::NCHW:
3088 if (layer ==
nullptr)
3093 "Failed to add pooling2d layer for %1% %2%")
3102 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
3105 ParsedTfOperationPtr TfParser::AddAdditionLayer(
const tensorflow::NodeDef& nodeDef,
bool isBiasAdd)
3107 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
3109 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
3110 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
3124 "Unsupported bias for BiasAdd. It should be a 1D vector. " 3125 "Got %1% dimensions for input %2%. Node %3% %4%")
3127 % inputs[1].m_IndexedValue->GetNode().name()
3132 const std::string dataFormat = ReadMandatoryNodeStringAttribute(nodeDef,
"data_format");
3135 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, dataFormat ==
"NHWC", *m_Network, nodeDef);
3141 const bool isNHWC =
true;
3142 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
3147 const bool isNHWC =
true;
3148 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
3162 std::vector<unsigned int> outputShape;
3168 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
3184 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
3189 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
3192 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
3193 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
3199 if (input0NumDims < input1NumDims)
3201 const bool isNHWC =
true;
3202 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
3204 if (input1NumDims < input0NumDims)
3206 const bool isNHWC =
true;
3207 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
3213 if (input0NumDims < input1NumDims)
3222 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
3227 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
3229 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
3230 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
3235 if (input0NumDims < input1NumDims)
3237 const bool isNHWC =
true;
3238 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
3240 if (input1NumDims < input0NumDims)
3242 const bool isNHWC =
true;
3243 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
3252 std::vector<unsigned int> outputShape;
3259 outputShape.push_back(std::max(input0Shape[i], input1Shape[i]));
3265 return std::make_unique<SingleLayerParsedTfOperation>(
this, nodeDef, layer);
3268 IConnectableLayer* TfParser::AddMultiplicationLayer(
const tensorflow::NodeDef& nodeDef)
3270 std::vector<OutputOfParsedTfOperation> inputs = GetInputParsedTfOperationsChecked(nodeDef, 2);
3273 IOutputSlot* input0Slot = &inputs[0].m_IndexedValue->ResolveArmnnOutputSlot(inputs[0].m_Index);
3274 IOutputSlot* input1Slot = &inputs[1].m_IndexedValue->ResolveArmnnOutputSlot(inputs[1].m_Index);
3279 if (input0NumDims < input1NumDims)
3281 const bool isNHWC =
true;
3282 input0Slot = AddBroadcastReshapeLayer(input1Slot, input0Slot, isNHWC, *m_Network, nodeDef);
3284 if (input1NumDims < input0NumDims)
3286 const bool isNHWC =
true;
3287 input1Slot = AddBroadcastReshapeLayer(input0Slot, input1Slot, isNHWC, *m_Network, nodeDef);
3293 if (input0NumDims < input1NumDims)
3304 IConnectableLayer* TfParser::AddFullyConnectedLayer(
const tensorflow::NodeDef& matMulNodeDef,
3305 const tensorflow::NodeDef* addNodeDef,
const char* armnnLayerName)
3308 ParsedConstTfOperation<float>* biasNode =
nullptr;
3309 if (addNodeDef !=
nullptr)
3311 std::vector<OutputOfParsedTfOperation> addInputs = GetInputParsedTfOperationsChecked(*addNodeDef, 2);
3313 if (HasParsedConstTensor<float>(addInputs[0].m_IndexedValue->GetNode().name()))
3315 biasNode = PolymorphicDowncast<ParsedConstTfOperation<float>*>(addInputs[0].m_IndexedValue);
3317 else if (HasParsedConstTensor<float>(addInputs[1].m_IndexedValue->GetNode().name()))
3319 biasNode = PolymorphicDowncast<ParsedConstTfOperation<float>*>(addInputs[1].m_IndexedValue);
3326 "ArmNN only supports fully connected layers with constant bias. " 3327 "Inputs %1% and %2%. AddNode %3%. MatMulNode %4% %5%")
3328 % addInputs[0].m_IndexedValue->GetNode().name()
3329 % addInputs[1].m_IndexedValue->GetNode().name()
3330 % addNodeDef->name()
3331 % matMulNodeDef.name()
3337 ParsedConstTfOperation<float>* weightNode =
nullptr;
3338 ParsedTfOperation* inputNode =
nullptr;
3339 unsigned int inputIdx = 0;
3340 std::vector<OutputOfParsedTfOperation> mulInputs = GetInputParsedTfOperationsChecked(matMulNodeDef, 2);
3341 if (HasParsedConstTensor<float>(mulInputs[0].m_IndexedValue->GetNode().name()))
3343 weightNode = PolymorphicDowncast<ParsedConstTfOperation<float>*>(mulInputs[0].m_IndexedValue);
3344 inputNode = mulInputs[1].m_IndexedValue;
3345 inputIdx = mulInputs[1].m_Index;
3347 else if (HasParsedConstTensor<float>(mulInputs[1].m_IndexedValue->GetNode().name()))
3349 weightNode = PolymorphicDowncast<ParsedConstTfOperation<float>*>(mulInputs[1].m_IndexedValue);
3350 inputNode = mulInputs[0].m_IndexedValue;
3351 inputIdx = mulInputs[0].m_Index;
3358 "ArmNN only supports fully connected layers with constant weights. " 3359 "Inputs %1% and %2%. MatMulNode %3% %4%")
3360 % mulInputs[0].m_IndexedValue->GetNode().name()
3361 % mulInputs[1].m_IndexedValue->GetNode().name()
3362 % matMulNodeDef.name()
3366 std::vector<float> weightTensorData;
3368 ConstTensor weights = weightNode->GetConstTensor(weightTensorData);
3375 std::vector<float> biasTensorData;
3377 if (addNodeDef !=
nullptr)
3379 ConstTensor biases = biasNode->GetConstTensor(biasTensorData);
3386 "Shape of matmul weights and bias do not match. " 3387 "AddNode %1%. MatMulNode %2% %3%")
3388 % addNodeDef->name()
3389 % matMulNodeDef.name()
3399 inputNode->ResolveArmnnOutputSlot(inputIdx).Connect(layer->GetInputSlot(0));
3400 unsigned int batches = inputNode->ResolveArmnnOutputSlot(inputIdx).GetTensorInfo().GetShape()[0];
3404 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
3408 void TfParser::LoadNodeDef(
const tensorflow::NodeDef& nodeDef,
const tensorflow::GraphDef& graphDef)
3412 if (nodeDef.attr().count(
"T") != 0)
3414 auto attr = nodeDef.attr().at(
"T");
3417 else if (nodeDef.attr().count(
"dtype") != 0)
3419 auto attr = nodeDef.attr().at(
"dtype");
3423 if ((type != tensorflow::DT_FLOAT && type != tensorflow::DT_INT32) && nodeDef.op() !=
"Const")
3428 "Currently only FLOAT and INT32 are supported for tensorflow nodes (apart from Const). " 3429 "Got %1% for Node %2% %3%")
3430 % tensorflow::DataType_Name(type)
3435 const std::string& operation = nodeDef.op();
3436 auto itControlInput = std::find(m_ControlInputs.begin(), m_ControlInputs.end(), operation);
3437 if (itControlInput != m_ControlInputs.end())
3442 auto it = ms_OperationNameToParsingFunctions.find(operation);
3443 if (it != ms_OperationNameToParsingFunctions.end())
3445 auto func = it->second;
3447 ParsedTfOperation* parsedTfOperationRaw = parsedTfOperation.get();
3450 auto it = m_ParsedTfOperations.find(nodeDef.name());
3451 if (it != m_ParsedTfOperations.end())
3453 throw ParseException(boost::str(boost::format(
"Name %1% used by more than one node") % nodeDef.name()));
3455 m_ParsedTfOperations[nodeDef.name()] = std::move(parsedTfOperation);
3458 if (std::find(m_RequestedOutputs.begin(), m_RequestedOutputs.end(), nodeDef.name()) !=
3459 m_RequestedOutputs.end())
3461 auto outId = ParseOutputId(nodeDef.name());
3463 IOutputSlot& prevSlot = parsedTfOperationRaw->ResolveArmnnOutputSlot(outId.m_Index);
3465 TensorInfo tensorInfo = prevSlot.GetTensorInfo();
3471 TrackOutputBinding(outputLayer, layerId, tensorInfo);
3479 "Unsupported operation %1% in tensorflow::GraphDef %2%")
3485 void TfParser::LoadGraphDef(
const tensorflow::GraphDef& graphDef)
3488 m_NodesByName.clear();
3489 m_NetworkInputsBindingInfo.clear();
3490 m_NetworkOutputsBindingInfo.clear();
3492 for (
int i = 0; i < graphDef.node_size(); ++i)
3494 const tensorflow::NodeDef& node = graphDef.node(i);
3495 m_NodesByName[node.name()] = &node;
3499 for (
const auto& pair : m_InputShapes)
3501 const std::string& requestedInputName = pair.first;
3502 auto nodeIt = m_NodesByName.find(requestedInputName);
3503 if (nodeIt == m_NodesByName.end())
3508 "Couldn't find requested input node '%1%' in graph %2%")
3509 % requestedInputName
3515 std::vector<const tensorflow::NodeDef*> targetNodes;
3516 for (
const std::string& requestedOutputName : m_RequestedOutputs)
3518 auto nodeIt = m_NodesByName.find(requestedOutputName);
3519 if (nodeIt == m_NodesByName.end())
3524 "Couldn't find requested output node '%1%' in graph %2%")
3525 % requestedOutputName
3528 targetNodes.push_back(nodeIt->second);
3532 std::vector<const tensorflow::NodeDef*> sortedNodes;
3533 if (!armnnUtils::GraphTopologicalSort<const tensorflow::NodeDef*>(
3535 [
this](
const tensorflow::NodeDef* node)
3537 auto outputs = GetTfInputNodes(*node);
3538 std::vector<const tensorflow::NodeDef*> nodesOnly;
3539 for (
const auto & o : outputs) {
3540 nodesOnly.push_back(o.m_IndexedValue);
3549 "Cycle detected in graph %1%")
3554 for (
const auto& it : sortedNodes)
3556 const tensorflow::NodeDef& currentNode = *it;
3557 LoadNodeDef(currentNode, graphDef);
3562 const std::map<std::string, TensorShape>& inputShapes,
3563 const std::vector<std::string>& requestedOutputs)
3565 FILE* fd = fopen(graphFile,
"r");
3572 "Graph file %1% failed to open %2%")
3578 tensorflow::GraphDef graphDef;
3579 auto input =
new google::protobuf::io::FileInputStream(fileno(fd));
3580 bool success = google::protobuf::TextFormat::Parse(input, &graphDef);
3589 "Failed to parse graph file %1%")
3593 return CreateNetworkFromGraphDef(graphDef, inputShapes, requestedOutputs);
3597 const std::map<std::string, TensorShape>& inputShapes,
3598 const std::vector<std::string>& requestedOutputs)
3601 tensorflow::GraphDef graphDef;
3602 bool success = google::protobuf::TextFormat::ParseFromString(protoText, &graphDef);
3609 "Failed to parse graph file %1%")
3613 return CreateNetworkFromGraphDef(graphDef, inputShapes, requestedOutputs);
3617 const std::map<std::string, TensorShape>& inputShapes,
3618 const std::vector<std::string>& requestedOutputs)
3620 FILE* fd = fopen(graphFile,
"rb");
3627 "Graph file %1% failed to open %2%")
3633 tensorflow::GraphDef graphDef;
3635 google::protobuf::io::FileInputStream inStream(fileno(fd));
3636 google::protobuf::io::CodedInputStream codedStream(&inStream);
3637 codedStream.SetTotalBytesLimit(INT_MAX, INT_MAX);
3638 bool success = graphDef.ParseFromCodedStream(&codedStream);
3646 "Failed to parse protobuf file %1% %2%")
3651 return CreateNetworkFromGraphDef(graphDef, inputShapes, requestedOutputs);
3654 INetworkPtr TfParser::CreateNetworkFromGraphDef(
const tensorflow::GraphDef& graphDef,
3655 const std::map<std::string, TensorShape>& inputShapes,
3656 const std::vector<std::string>& requestedOutputs)
3658 m_Network = INetwork::Create();
3660 m_InputShapes = inputShapes;
3661 if (requestedOutputs.size() == 0)
3666 "requestedOutputs must have at least one entry %1%")
3669 m_RequestedOutputs = requestedOutputs;
3673 LoadGraphDef(graphDef);
3683 return std::move(m_Network);
3686 void TfParser::Cleanup()
3689 m_InputShapes.clear();
3690 m_RequestedOutputs.clear();
3691 m_NodesByName.clear();
3692 m_ParsedTfOperations.clear();
3697 return GetBindingInfo(name,
"input", m_NetworkInputsBindingInfo);
3702 return GetBindingInfo(name,
"output", m_NetworkOutputsBindingInfo);
3705 std::pair<LayerBindingId, TensorInfo> TfParser::GetBindingInfo(
const std::string& layerName,
3706 const char* bindingPointDesc,
3707 const std::unordered_map<std::string, BindingPointInfo>& nameToBindingInfo)
3709 auto it = nameToBindingInfo.find(layerName);
3710 if (it == nameToBindingInfo.end())
3715 "Unknown %1% '%2%' %3%")
3725 return TrackBindingPoint(layer,
id, tensorInfo,
"input", m_NetworkInputsBindingInfo);
3730 return TrackBindingPoint(layer,
id, tensorInfo,
"output", m_NetworkOutputsBindingInfo);
3736 const char* bindingPointDesc,
3737 std::unordered_map<std::string, BindingPointInfo>& nameToBindingInfo)
3739 const std::string layerName = layer->
GetName();
3740 auto it = nameToBindingInfo.find(layerName);
3741 if (it == nameToBindingInfo.end())
3743 nameToBindingInfo[layerName] = std::make_pair(
id, tensorInfo);
3750 "Id %1% used by more than one %2% layer %3%")
uint32_t m_PadBottom
Padding bottom value in the height dimension.
bool m_BiasEnabled
Enable/disable bias.
std::unique_ptr< ITfParser, void(*)(ITfParser *parser)> ITfParserPtr
virtual IConnectableLayer * AddGatherLayer(const char *name=nullptr)=0
Add Gather layer to the network.
virtual IConnectableLayer * AddComparisonLayer(const ComparisonDescriptor &comparisonDescriptor, const char *name=nullptr)=0
Add a Comparison layer to the network.
virtual unsigned int GetNumOutputSlots() const =0
Returns the number of connectable output slots.
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
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.
virtual IConnectableLayer * AddMeanLayer(const MeanDescriptor &meanDescriptor, const char *name=nullptr)=0
Add a Mean layer to the network.
uint32_t m_PadBottom
Padding bottom value in the height dimension.
bool m_BiasEnabled
Enable/disable bias.
unsigned int GetWidthIndex() const
float m_K
Kappa value used for the across channel normalization equation.
friend class ParsedMulTfOperation
WithOutputTensorIndex< ParsedTfOperation * > OutputOfParsedTfOperation
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.
armnn::BindingPointInfo BindingPointInfo
int32_t m_ShrinkAxisMask
Shrink axis mask value. If set, the nth specification shrinks the dimensionality by 1...
A ReshapeDescriptor for the ReshapeLayer.
WithOutputTensorIndex< std::string > OutputId
std::vector< int > m_Begin
Begin values for the input that will be sliced.
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
virtual IConnectableLayer * AddSoftmaxLayer(const SoftmaxDescriptor &softmaxDescriptor, const char *name=nullptr)=0
Adds a softmax layer to the network.
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
A ComparisonDescriptor for the ComparisonLayer.
TensorShape m_InputShape
Required shape of all input tensors.
virtual IConnectableLayer * AddMinimumLayer(const char *name=nullptr)=0
Add a Minimum layer to the network.
uint32_t m_PoolWidth
Pooling width value.
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.
virtual IConnectableLayer * AddPadLayer(const PadDescriptor &padDescriptor, const char *name=nullptr)=0
Adds a fully pad layer to the network.
void CalculateReducedOutputTensoInfo(const armnn::TensorInfo &inputTensorInfo, const std::set< unsigned int > &axisSet, bool keepDims, armnn::TensorInfo &outputTensorInfo)
Creates a tensor info after reducing the dimensions mentioned in axisData.
const TensorShape & GetShape() const
unsigned int GetNumBytes() const
ResizeMethod m_Method
The Interpolation method to use (Bilinear, NearestNeighbor).
virtual IConnectableLayer * AddActivationLayer(const ActivationDescriptor &activationDescriptor, const char *name=nullptr)=0
Adds an activation layer to the network.
float m_Eps
Value to add to the variance. Used to avoid dividing by zero.
PaddingMethod m_PaddingMethod
The padding method to be used. (Exclude, IgnoreValue).
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
virtual IConnectableLayer * AddElementwiseUnaryLayer(const ElementwiseUnaryDescriptor &elementwiseUnaryDescriptor, const char *name=nullptr)=0
Add an ElementwiseUnary layer to the network.
unsigned int CheckPaddingTensor(const ConstTensor &paddingTensor, const TensorInfo &inputTensorInfo, const std::string &nodeName)
virtual BindingPointInfo GetNetworkOutputBindingInfo(const std::string &name) const override
Retrieves binding info (layer id and tensor info) for the network output identified by the given laye...
Main network class which provides the interface for building up a neural network. ...
virtual IConnectableLayer * AddBatchNormalizationLayer(const BatchNormalizationDescriptor &desc, const ConstTensor &mean, const ConstTensor &variance, const ConstTensor &beta, const ConstTensor &gamma, const char *name=nullptr)=0
Adds a batch normalization layer to the network.
uint32_t m_PadTop
Padding top value in the height dimension.
void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t &outPadHead, uint32_t &outPadTail, bool samePadding)
uint32_t m_PadRight
Padding right value in the width dimension.
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
Copyright (c) 2020 ARM Limited.
void IgnoreUnused(Ts &&...)
int32_t m_BeginMask
Begin mask value.
int32_t m_EndMask
End mask value.
friend class ParsedConstTfOperation
const armnn::PermutationVector NHWCToArmNN
unsigned int GetNumOutputSlots() const override
Returns the number of connectable output slots.
uint32_t m_StrideX
Stride value when proceeding through input for the width dimension.
int LayerBindingId
Type of identifiers for bindable layers (inputs, outputs).
virtual IConnectableLayer * AddNormalizationLayer(const NormalizationDescriptor &normalizationDescriptor, const char *name=nullptr)=0
Adds a normalization layer to the network.
virtual IConnectableLayer * AddFullyConnectedLayer(const FullyConnectedDescriptor &fullyConnectedDescriptor, const ConstTensor &weights, const Optional< ConstTensor > &biases, const char *name=nullptr)=0
Adds a fully connected layer to the network.
unsigned int GetHeightIndex() const
virtual void SetTensorInfo(const TensorInfo &tensorInfo)=0
NormalizationAlgorithmMethod m_NormMethodType
Normalization method algorithm to use (LocalBrightness, LocalContrast).
void SetShape(const TensorShape &newShape)
A ResizeDescriptor for the ResizeLayer.
std::vector< unsigned int > m_Axis
Values for the dimensions to reduce.
A StackDescriptor for the StackLayer.
virtual IConnectableLayer * AddConvolution2dLayer(const Convolution2dDescriptor &convolution2dDescriptor, const ConstTensor &weights, const Optional< ConstTensor > &biases, const char *name=nullptr)=0
Adds a 2D convolution layer to the network.
TensorShape m_TargetShape
Target shape value.
virtual IConnectableLayer * AddOutputLayer(LayerBindingId id, const char *name=nullptr)=0
Adds an output layer to the network.
std::unique_ptr< ParsedTfOperation > ParsedTfOperationPtr
virtual IConnectableLayer * AddAdditionLayer(const char *name=nullptr)=0
Adds an addition layer to the network.
uint32_t m_PoolHeight
Pooling height value.
uint32_t m_PadTop
Padding top value in the height dimension.
A PadDescriptor for the PadLayer.
void Permute(const armnn::TensorShape &dstShape, const armnn::PermutationVector &mappings, const void *src, void *dst, size_t dataTypeSize)
virtual IConnectableLayer * AddConcatLayer(const ConcatDescriptor &concatDescriptor, const char *name=nullptr)=0
Adds a concatenation layer to the network.
const uint32_t * GetViewOrigin(uint32_t idx) const
Return the view origin at the int value idx.
uint32_t m_StrideX
Stride value when proceeding through input for the width dimension.
virtual IConnectableLayer * AddStackLayer(const StackDescriptor &descriptor, const char *name=nullptr)=0
Adds a stack layer to the network.
WithOutputTensorIndex< const tensorflow::NodeDef * > OutputOfConstNodeDef
uint32_t m_StrideX
Stride value when proceeding through input for the width dimension.
uint32_t m_PadRight
Padding right value in the width dimension.
uint32_t m_PadTop
Padding top value in the height dimension.
Status SetViewSize(uint32_t view, uint32_t coord, uint32_t value)
Set the size of the views.
virtual IConnectableLayer * AddResizeLayer(const ResizeDescriptor &resizeDescriptor, const char *name=nullptr)=0
Adds a resize layer to the network.
int32_t m_NewAxisMask
New axis mask value.
virtual IConnectableLayer * AddPooling2dLayer(const Pooling2dDescriptor &pooling2dDescriptor, const char *name=nullptr)=0
Adds a pooling layer to the network.
bool m_KeepDims
Enable/disable keep dimensions. If true, then the reduced dimensions that are of length 1 are kept...
An output connection slot for a layer.
Provides access to the appropriate indexes for Channels, Height and Width based on DataLayout...
DataType GetDataType() const
An OriginsDescriptor for the ConcatLayer.
A FullyConnectedDescriptor for the FullyConnectedLayer.
int32_t m_EllipsisMask
Ellipsis mask value.
virtual IConnectableLayer * AddSplitterLayer(const ViewsDescriptor &splitterDescriptor, const char *name=nullptr)=0
Adds a splitter layer to the network.
bool m_BiasEnabled
Enable/disable bias.
WithOutputTensorIndex wraps a value and an index.
A tensor defined by a TensorInfo (shape and data type) and an immutable backing store.
uint32_t m_TargetWidth
Target width value.
A GatherDescriptor for the GatherLayer.
virtual armnn::INetworkPtr CreateNetworkFromString(const char *protoText, const std::map< std::string, armnn::TensorShape > &inputShapes, const std::vector< std::string > &requestedOutputs) override
Creates the network directly from protobuf text in a string. Useful for debugging/testing.
#define ARMNN_ASSERT(COND)
std::enable_if_t< std::is_unsigned< Source >::value &&std::is_unsigned< Dest >::value, Dest > numeric_cast(Source source)
std::vector< int > m_Stride
Stride values for the input that will be sliced.
An ActivationDescriptor for the ActivationLayer.
friend class ParsedMatMulTfOperation
void CalculateSamePadding(uint32_t inputSize, uint32_t stride, uint32_t filterSize, bool samePadding, uint32_t *paddingFront, uint32_t *paddingBack)
void SetDataType(DataType type)
uint32_t m_NumInputs
Number of input tensors.
uint32_t m_TargetHeight
Target height value.
virtual IConnectableLayer * AddDepthwiseConvolution2dLayer(const DepthwiseConvolution2dDescriptor &convolution2dDescriptor, const ConstTensor &weights, const Optional< ConstTensor > &biases, const char *name=nullptr)=0
Adds a 2D depthwise convolution layer to the network.
uint32_t m_StrideY
Stride value when proceeding through input for the height dimension.
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
void CalculateStridedSliceOutputTensorInfo(const armnn::TensorInfo &inputTensorInfo, const armnn::StridedSliceDescriptor &desc, armnn::TensorInfo &outputTensorInfo)
Create output tensor info for a StridedSlice operator.
std::vector< int > m_End
End values for the input that will be sliced.
NormalizationAlgorithmChannel m_NormChannelType
Normalization channel algorithm to use (Across, Within).
DataType ConvertTfTensorDataType(const tensorflow::DataType tfDataType, const tensorflow::NodeDef &nodeDef)
float m_A
Alpha upper bound value used by the activation functions. (BoundedReLu, Linear, TanH, Elu).
#define CHECK_DATA_FORMAT(NODE_DEF, FORMAT, NODE_TYPE)
virtual IConnectableLayer * AddStridedSliceLayer(const StridedSliceDescriptor &stridedSliceDescriptor, const char *name=nullptr)=0
Adds a strided slice layer to the network.
EmptyOptional is used to initialize the Optional class in case we want to have default value for an O...
virtual IConnectableLayer * AddReshapeLayer(const ReshapeDescriptor &reshapeDescriptor, const char *name=nullptr)=0
Adds a reshape layer to the network.
int32_t m_Axis
The axis in params to gather indices from.
A ElementwiseUnaryDescriptor for the ElementwiseUnaryLayer.
PoolingAlgorithm m_PoolType
The pooling algorithm to use (Max. Average, L2).
uint32_t m_StrideY
Stride value when proceeding through input for the height dimension.
Parses a directed acyclic graph from a tensorflow protobuf file.
virtual IConnectableLayer * AddMaximumLayer(const char *name=nullptr)=0
Add a Maximum layer to the network.
unsigned int GetNumDimensions() const
Function that returns the tensor rank.
virtual armnn::INetworkPtr CreateNetworkFromTextFile(const char *graphFile, const std::map< std::string, armnn::TensorShape > &inputShapes, const std::vector< std::string > &requestedOutputs) override
Creates the network from a protobuf text file on the disk.
OutputShapeRounding m_OutputShapeRounding
The rounding method for the output shape. (Floor, Ceiling).
void SetConcatAxis(unsigned int concatAxis)
Set the concatenation axis value.
void SetTensorInfo(const TensorInfo &tensorInfo) override
virtual const IInputSlot & GetInputSlot(unsigned int index) const =0
Get a const input slot handle by slot index.
A MeanDescriptor for the MeanLayer.
armnn::TensorInfo GetTensorInfo(unsigned int numberOfBatches, unsigned int numberOfChannels, unsigned int height, unsigned int width, const armnn::DataLayout dataLayout, const armnn::DataType dataType)
const OutputSlot & GetOutputSlot(unsigned int index=0) const override
Get the const output slot handle by slot index.
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.
const char * GetName() const override
Returns the name of the layer.
virtual const char * GetName() const =0
Returns the name of the layer.
std::unique_ptr< INetwork, void(*)(INetwork *network)> INetworkPtr
armnn::TensorShape TransposeTensorShape(const armnn::TensorShape &srcShape, const armnn::PermutationVector &mappings)
#define CHECK_PADDING_TYPE(NODE_DEF, PADDING)
virtual int Connect(IInputSlot &destination)=0
A Pooling2dDescriptor for the Pooling2dLayer.
A NormalizationDescriptor for the NormalizationLayer.
virtual BindingPointInfo GetNetworkInputBindingInfo(const std::string &name) const override
Retrieves binding info (layer id and tensor info) for the network input identified by the given layer...
DataLayout m_DataLayout
The data layout to be used (NCHW, NHWC).
const armnn::PermutationVector ArmNNToNHWC
unsigned int GetNumDimensions() const
virtual IConnectableLayer * AddDivisionLayer(const char *name=nullptr)=0
Adds a division layer to the network.
virtual IConnectableLayer * AddInputLayer(LayerBindingId id, const char *name=nullptr)=0
Adds an input layer to the network.
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_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).
virtual armnn::INetworkPtr CreateNetworkFromBinaryFile(const char *graphFile, const std::map< std::string, armnn::TensorShape > &inputShapes, const std::vector< std::string > &requestedOutputs) override
Creates the network from a protobuf binary file on the disk.
uint32_t m_StrideY
Stride value when proceeding through input for the height dimension.
A DepthwiseConvolution2dDescriptor for the DepthwiseConvolution2dLayer.
A BatchNormalizationDescriptor for the BatchNormalizationLayer.
uint32_t m_PadLeft
Padding left value in the width dimension.
unsigned int GetNumElements() const
Status SetViewOriginCoord(uint32_t view, uint32_t coord, uint32_t value)
Set the view origin coordinates.
constexpr unsigned int GetDataTypeSize(DataType dataType)
virtual IConnectableLayer * AddTransposeLayer(const TransposeDescriptor &transposeDescriptor, const char *name=nullptr)=0
Adds a transpose layer to the network.
TensorInfo CalculatePaddedOutputTensorInfo(const TensorInfo &inputTensorInfo, const std::vector< std::pair< unsigned int, unsigned int >> &padList)
uint32_t m_PadRight
Padding right value in the width dimension.
virtual IConnectableLayer * AddMultiplicationLayer(const char *name=nullptr)=0
Adds a multiplication layer to the network.
TensorInfo OutputShapeOfExpandDims(const tensorflow::NodeDef &nodeDef, TensorInfo inputTensorInfo)
virtual IConnectableLayer * AddSubtractionLayer(const char *name=nullptr)=0
Adds a subtraction layer to the network.
TensorInfo OutputShapeOfSqueeze(const tensorflow::NodeDef &nodeDef, TensorInfo inputTensorInfo)