ArmNN
 22.02
TfLiteParser.hpp
Go to the documentation of this file.
1 //
2 // Copyright © 2017 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5 #pragma once
6 
7 #include "armnn/INetwork.hpp"
9 #include "armnn/Types.hpp"
10 
11 #include <schema_generated.h>
12 #include <functional>
13 #include <unordered_map>
14 #include <vector>
15 
16 #include <tensorflow/lite/version.h>
17 
18 #if TF_MAJOR_VERSION > 2 || (TF_MAJOR_VERSION == 2 && TF_MINOR_VERSION > 3)
19 #define ARMNN_POST_TFLITE_2_3
20 #endif
21 
22 namespace armnnTfLiteParser
23 {
24 
26 {
27 public:
28  // Shorthands for TfLite types
29  using ModelPtr = std::unique_ptr<tflite::ModelT>;
30  using SubgraphPtr = std::unique_ptr<tflite::SubGraphT>;
31  using OperatorPtr = std::unique_ptr<tflite::OperatorT>;
32  using OperatorCodePtr = std::unique_ptr<tflite::OperatorCodeT>;
33  using TensorPtr = std::unique_ptr<tflite::TensorT>;
34  using TensorRawPtr = const tflite::TensorT *;
35  using TensorRawPtrVector = std::vector<TensorRawPtr>;
36  using TensorIdRawPtr = std::pair<size_t, TensorRawPtr>;
37  using TensorIdRawPtrVector = std::vector<TensorIdRawPtr>;
38  using BufferPtr = std::unique_ptr<tflite::BufferT>;
39  using BufferRawPtr = const tflite::BufferT *;
40 
41 public:
42  /// Create the network from a flatbuffers binary file on disk
43  armnn::INetworkPtr CreateNetworkFromBinaryFile(const char* graphFile);
44 
45  /// Create the network from a flatbuffers binary
46  armnn::INetworkPtr CreateNetworkFromBinary(const std::vector<uint8_t> & binaryContent);
47 
48 
49  /// Retrieve binding info (layer id and tensor info) for the network input identified by
50  /// the given layer name and subgraph id
52  const std::string& name) const;
53 
54  /// Retrieve binding info (layer id and tensor info) for the network output identified by
55  /// the given layer name and subgraph id
57  const std::string& name) const;
58 
59  /// Return the number of subgraphs in the parsed model
60  size_t GetSubgraphCount() const;
61 
62  /// Return the input tensor names for a given subgraph
63  std::vector<std::string> GetSubgraphInputTensorNames(size_t subgraphId) const;
64 
65  /// Return the output tensor names for a given subgraph
66  std::vector<std::string> GetSubgraphOutputTensorNames(size_t subgraphId) const;
67 
69  ~TfLiteParserImpl() = default;
70 
71 public:
72  // testable helpers
73  armnn::INetworkPtr CreateNetworkFromBinaryAsDynamic(const std::vector<uint8_t>& binaryContent);
74 
75  armnn::INetworkPtr LoadModel(std::unique_ptr<tflite::ModelT> model);
76 
77  static ModelPtr LoadModelFromFile(const char* fileName);
78  static ModelPtr LoadModelFromBinary(const uint8_t* binaryContent, size_t len);
79  static TensorRawPtrVector GetInputs(const ModelPtr& model, size_t subgraphIndex, size_t operatorIndex);
80  static TensorRawPtrVector GetOutputs(const ModelPtr& model, size_t subgraphIndex, size_t operatorIndex);
81  static TensorIdRawPtrVector GetSubgraphInputs(const ModelPtr& model, size_t subgraphIndex);
82  static TensorIdRawPtrVector GetSubgraphOutputs(const ModelPtr& model, size_t subgraphIndex);
83  static std::vector<int32_t>& GetInputTensorIds(const ModelPtr& model, size_t subgraphIndex, size_t operatorIndex);
84  static std::vector<int32_t>& GetOutputTensorIds(const ModelPtr& model, size_t subgraphIndex, size_t operatorIndex);
85 
86  static BufferRawPtr GetBuffer(const ModelPtr& model, size_t bufferIndex);
87  static armnn::TensorInfo OutputShapeOfSqueeze(std::vector<uint32_t> squeezeDims,
88  const armnn::TensorInfo& inputTensorInfo);
89  static armnn::TensorInfo OutputShapeOfReshape(const armnn::TensorInfo& inputTensorInfo,
90  const std::vector<int32_t>& targetDimsIn);
91 
92  /// Retrieve version in X.Y.Z form
93  static const std::string GetVersion();
94 
95 private:
96 
97  // No copying allowed until it is wanted and properly implemented
98  TfLiteParserImpl(const TfLiteParserImpl &) = delete;
99  TfLiteParserImpl & operator=(const TfLiteParserImpl &) = delete;
100 
101  /// Create the network from an already loaded flatbuffers model
102  armnn::INetworkPtr CreateNetworkFromModel();
103 
104  // signature for the parser functions
105  using OperatorParsingFunction = void(TfLiteParserImpl::*)(size_t subgraphIndex, size_t operatorIndex);
106 
107  void ParseCustomOperator(size_t subgraphIndex, size_t operatorIndex);
108  void ParseUnsupportedOperator(size_t subgraphIndex, size_t operatorIndex);
109 
110  void ParseAbs(size_t subgraphIndex, size_t operatorIndex);
111  void ParseActivation(size_t subgraphIndex, size_t operatorIndex, armnn::ActivationFunction activationType);
112  void ParseAdd(size_t subgraphIndex, size_t operatorIndex);
113  void ParseArgMinMax(size_t subgraphIndex, size_t operatorIndex, armnn::ArgMinMaxFunction argMinMaxFunction);
114  void ParseArgMin(size_t subgraphIndex, size_t operatorIndex);
115  void ParseArgMax(size_t subgraphIndex, size_t operatorIndex);
116  void ParseAveragePool2D(size_t subgraphIndex, size_t operatorIndex);
117  void ParseBatchToSpaceND(size_t subgraphIndex, size_t operatorIndex);
118  void ParseCast(size_t subgraphIndex, size_t operatorIndex);
119  void ParseComparison(size_t subgraphIndex, size_t operatorIndex, armnn::ComparisonOperation comparisonOperation);
120  void ParseConcatenation(size_t subgraphIndex, size_t operatorIndex);
121  void ParseConv2D(size_t subgraphIndex, size_t operatorIndex);
122  // Conv3D support was added in TF 2.5, so for backwards compatibility a hash define is needed.
123  #if defined(ARMNN_POST_TFLITE_2_3)
124  void ParseConv3D(size_t subgraphIndex, size_t operatorIndex);
125  #endif
126  void ParseDepthToSpace(size_t subgraphIndex, size_t operatorIndex);
127  void ParseDepthwiseConv2D(size_t subgraphIndex, size_t operatorIndex);
128  void ParseDequantize(size_t subgraphIndex, size_t operatorIndex);
129  void ParseDetectionPostProcess(size_t subgraphIndex, size_t operatorIndex);
130  void ParseDiv(size_t subgraphIndex, size_t operatorIndex);
131  void ParseElementwiseUnary(size_t subgraphIndex, size_t operatorIndex, armnn::UnaryOperation unaryOperation);
132  void ParseElu(size_t subgraphIndex, size_t operatorIndex);
133  void ParseEqual(size_t subgraphIndex, size_t operatorIndex);
134  void ParseExp(size_t subgraphIndex, size_t operatorIndex);
135  void ParseExpandDims(size_t subgraphIndex, size_t operatorIndex);
136  void ParseFullyConnected(size_t subgraphIndex, size_t operatorIndex);
137  void ParseGather(size_t subgraphIndex, size_t operatorIndex);
138  void ParseGreater(size_t subgraphIndex, size_t operatorIndex);
139  void ParseGreaterOrEqual(size_t subgraphIndex, size_t operatorIndex);
140  void ParseHardSwish(size_t subgraphIndex, size_t operatorIndex);
141  void ParseLeakyRelu(size_t subgraphIndex, size_t operatorIndex);
142  void ParseLess(size_t subgraphIndex, size_t operatorIndex);
143  void ParseLessOrEqual(size_t subgraphIndex, size_t operatorIndex);
144  void ParseLocalResponseNormalization(size_t subgraphIndex, size_t operatorIndex);
145  void ParseLogicalNot(size_t subgraphIndex, size_t operatorIndex);
146  void ParseLogistic(size_t subgraphIndex, size_t operatorIndex);
147  void ParseL2Normalization(size_t subgraphIndex, size_t operatorIndex);
148  void ParseMaxPool2D(size_t subgraphIndex, size_t operatorIndex);
149  void ParseMaximum(size_t subgraphIndex, size_t operatorIndex);
150  void ParseMean(size_t subgraphIndex, size_t operatorIndex);
151  void ParseMinimum(size_t subgraphIndex, size_t operatorIndex);
152  void ParseMirrorPad(size_t subgraphIndex, size_t operatorIndex);
153  void ParseMul(size_t subgraphIndex, size_t operatorIndex);
154  void ParseNeg(size_t subgraphIndex, size_t operatorIndex);
155  void ParseNotEqual(size_t subgraphIndex, size_t operatorIndex);
156  void ParsePack(size_t subgraphIndex, size_t operatorIndex);
157  void ParsePad(size_t subgraphIndex, size_t operatorIndex);
158  void ParsePool(size_t subgraphIndex, size_t operatorIndex, armnn::PoolingAlgorithm algorithm);
159  void ParsePrelu(size_t subgraphIndex, size_t operatorIndex);
160  void ParseQuantize(size_t subgraphIndex, size_t operatorIndex);
161  void ParseReduce(size_t subgraphIndex, size_t operatorIndex, armnn::ReduceOperation reduceOperation);
162  void ParseReduceMax(size_t subgraphIndex, size_t operatorIndex);
163  void ParseReduceMin(size_t subgraphIndex, size_t operatorIndex);
164  void ParseReduceProd(size_t subgraphIndex, size_t operatorIndex);
165  void ParseRelu(size_t subgraphIndex, size_t operatorIndex);
166  void ParseRelu6(size_t subgraphIndex, size_t operatorIndex);
167  void ParseReshape(size_t subgraphIndex, size_t operatorIndex);
168  void ParseResize(size_t subgraphIndex, size_t operatorIndex, armnn::ResizeMethod resizeMethod);
169  void ParseResizeBilinear(size_t subgraphIndex, size_t operatorIndex);
170  void ParseResizeNearestNeighbor(size_t subgraphIndex, size_t operatorIndex);
171  void ParseRsqrt(size_t subgraphIndex, size_t operatorIndex);
172  void ParseShape(size_t subgraphIndex, size_t operatorIndex);
173  void ParseSlice(size_t subgraphIndex, size_t operatorIndex);
174  void ParseSoftmax(size_t subgraphIndex, size_t operatorIndex);
175  void ParseSpaceToBatchND(size_t subgraphIndex, size_t operatorIndex);
176  void ParseSplit(size_t subgraphIndex, size_t operatorIndex);
177  void ParseSplitV(size_t subgraphIndex, size_t operatorIndex);
178  void ParseSqueeze(size_t subgraphIndex, size_t operatorIndex);
179  void ParseStridedSlice(size_t subgraphIndex, size_t operatorIndex);
180  void ParseSub(size_t subgraphIndex, size_t operatorIndex);
181  void ParseSum(size_t subgraphIndex, size_t operatorIndex);
182  void ParseTanH(size_t subgraphIndex, size_t operatorIndex);
183  void ParseTranspose(size_t subgraphIndex, size_t operatorIndex);
184  void ParseTransposeConv(size_t subgraphIndex, size_t operatorIndex);
185  void ParseUnpack(size_t subgraphIndex, size_t operatorIndex);
186 
187  void RegisterProducerOfTensor(size_t subgraphIndex, size_t tensorIndex, armnn::IOutputSlot* slot);
188  void RegisterConsumerOfTensor(size_t subgraphIndex, size_t tensorIndex, armnn::IInputSlot* slot);
189  void RegisterInputSlots(size_t subgraphIndex,
190  size_t operatorIndex,
192  const std::vector<unsigned int>& tensorIndexes,
193  unsigned int startingSlotIndex = 0);
194  void RegisterOutputSlots(size_t subgraphIndex,
195  size_t operatorIndex,
197  const std::vector<unsigned int>& tensorIndexes);
198 
199  void SetupInputLayers(size_t subgraphIndex);
200  void SetupOutputLayers(size_t subgraphIndex);
201  void SetupConstantLayers(size_t subgraphIndex);
202 
203  void ResetParser();
204 
205  void AddBroadcastReshapeLayer(size_t subgraphIndex,
206  size_t operatorIndex,
207  armnn::IConnectableLayer* layer);
208 
209  /// Attach an activation layer to the one passed as a parameter
210  armnn::IConnectableLayer* AddFusedActivationLayer(armnn::IConnectableLayer* layer,
211  unsigned int outputSlot,
212  tflite::ActivationFunctionType activationType);
213 
214  // SupportedDataStorage's purpose is to hold data till we pass over to the network.
215  // We don't care about the content, and we want a single datatype to simplify the code.
216  struct SupportedDataStorage
217  {
218  public:
219  // Convenience constructors
220  SupportedDataStorage(std::unique_ptr<float[]>&& data);
221  SupportedDataStorage(std::unique_ptr<uint8_t[]>&& data);
222  SupportedDataStorage(std::unique_ptr<int8_t[]>&& data);
223  SupportedDataStorage(std::unique_ptr<int32_t[]>&& data);
224 
225  private:
226  // Pointers to the data buffers
227  std::unique_ptr<float[]> m_FloatData;
228  std::unique_ptr<uint8_t[]> m_Uint8Data;
229  std::unique_ptr<int8_t[]> m_Int8Data;
230  std::unique_ptr<int32_t[]> m_Int32Data;
231  };
232 
233  bool IsConstTensor(TensorRawPtr tensorPtr);
234  armnn::ConstTensor CreateConstTensorNonPermuted(TensorRawPtr tensorPtr,
235  armnn::TensorInfo& tensorInfo);
236  std::pair<armnn::ConstTensor, SupportedDataStorage>
237  CreateConstTensorPermuted(TensorRawPtr tensorPtr,
238  armnn::TensorInfo& tensorInfo,
240 
241  template<typename T>
242  std::pair<armnn::ConstTensor, TfLiteParserImpl::SupportedDataStorage>
243  CreateConstTensorAndStoreData(TfLiteParserImpl::BufferRawPtr bufferPtr,
245  armnn::TensorInfo& tensorInfo,
247 
248  // Settings for configuring the TfLiteParser
250 
251  /// The network we're building. Gets cleared after it is passed to the user
252  armnn::INetworkPtr m_Network;
253  ModelPtr m_Model;
254 
255  std::vector<OperatorParsingFunction> m_ParserFunctions;
256  std::unordered_map<std::string, OperatorParsingFunction> m_CustomParserFunctions;
257 
258  /// A mapping of an output slot to each of the input slots it should be connected to
259  /// The outputSlot is from the layer that creates this tensor as one of its ouputs
260  /// The inputSlots are from the layers that use this tensor as one of their inputs
261  struct TensorSlots
262  {
263  armnn::IOutputSlot* outputSlot;
264  std::vector<armnn::IInputSlot*> inputSlots;
265 
266  TensorSlots() : outputSlot(nullptr) { }
267  };
268  typedef std::vector<TensorSlots> TensorConnections;
269  /// Connections for tensors in each subgraph
270  /// The first index is the subgraph ID, the second index is the tensor ID
271  std::vector<TensorConnections> m_SubgraphConnections;
272 
273  /// This is used in case that the model does not speciry the output.
274  /// The shape can be calculated from the options.
275  std::vector<std::vector<unsigned int>> m_OverridenOutputShapes;
276 };
277 
278 }
std::unique_ptr< tflite::TensorT > TensorPtr
std::unique_ptr< tflite::ModelT > ModelPtr
static TensorIdRawPtrVector GetSubgraphOutputs(const ModelPtr &model, size_t subgraphIndex)
Interface for a layer that is connectable to other layers via InputSlots and OutputSlots.
Definition: INetwork.hpp:66
const tflite::TensorT * TensorRawPtr
const tflite::BufferT * BufferRawPtr
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...
std::vector< std::string > GetSubgraphOutputTensorNames(size_t subgraphId) const
Return the output tensor names for a given subgraph.
std::unique_ptr< tflite::OperatorT > OperatorPtr
static armnn::TensorInfo OutputShapeOfReshape(const armnn::TensorInfo &inputTensorInfo, const std::vector< int32_t > &targetDimsIn)
PoolingAlgorithm
Definition: Types.hpp:123
TfLiteParserImpl(const armnn::Optional< ITfLiteParser::TfLiteParserOptions > &options=armnn::EmptyOptional())
std::unique_ptr< tflite::BufferT > BufferPtr
armnn::INetworkPtr CreateNetworkFromBinary(const std::vector< uint8_t > &binaryContent)
Create the network from a flatbuffers binary.
static BufferRawPtr GetBuffer(const ModelPtr &model, size_t bufferIndex)
armnn::INetworkPtr CreateNetworkFromBinaryFile(const char *graphFile)
Create the network from a flatbuffers binary file on disk.
std::unique_ptr< tflite::OperatorCodeT > OperatorCodePtr
ComparisonOperation
Definition: Types.hpp:95
ReduceOperation
Definition: Types.hpp:130
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 ...
static ModelPtr LoadModelFromBinary(const uint8_t *binaryContent, size_t len)
std::vector< TensorIdRawPtr > TensorIdRawPtrVector
static std::vector< int32_t > & GetInputTensorIds(const ModelPtr &model, size_t subgraphIndex, size_t operatorIndex)
An output connection slot for a layer.
Definition: INetwork.hpp:40
static const std::string GetVersion()
Retrieve version in X.Y.Z form.
static ModelPtr LoadModelFromFile(const char *fileName)
A tensor defined by a TensorInfo (shape and data type) and an immutable backing store.
Definition: Tensor.hpp:327
std::vector< TensorRawPtr > TensorRawPtrVector
size_t GetSubgraphCount() const
Return the number of subgraphs in the parsed model.
armnn::INetworkPtr LoadModel(std::unique_ptr< tflite::ModelT > model)
std::pair< size_t, TensorRawPtr > TensorIdRawPtr
std::unique_ptr< tflite::SubGraphT > SubgraphPtr
static TensorIdRawPtrVector GetSubgraphInputs(const ModelPtr &model, size_t subgraphIndex)
static TensorRawPtrVector GetInputs(const ModelPtr &model, size_t subgraphIndex, size_t operatorIndex)
static TensorRawPtrVector GetOutputs(const ModelPtr &model, size_t subgraphIndex, size_t operatorIndex)
EmptyOptional is used to initialize the Optional class in case we want to have default value for an O...
Definition: Optional.hpp:32
static std::vector< int32_t > & GetOutputTensorIds(const ModelPtr &model, size_t subgraphIndex, size_t operatorIndex)
ArgMinMaxFunction
Definition: Types.hpp:89
ResizeMethod
Definition: Types.hpp:139
UnaryOperation
Definition: Types.hpp:111
armnn::BindingPointInfo BindingPointInfo
std::unique_ptr< INetwork, void(*)(INetwork *network)> INetworkPtr
Definition: INetwork.hpp:241
armnn::INetworkPtr CreateNetworkFromBinaryAsDynamic(const std::vector< uint8_t > &binaryContent)
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.
An input connection slot for a layer.
Definition: INetwork.hpp:26
ActivationFunction
Definition: Types.hpp:73