ArmNN
 22.11
INetwork.hpp
Go to the documentation of this file.
1 //
2 // Copyright © 2017 Arm Ltd and Contributors. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5 #pragma once
6 
8 #include <armnn/Deprecated.hpp>
10 #include <armnn/IStrategy.hpp>
11 #include <armnn/NetworkFwd.hpp>
12 #include <armnn/Optional.hpp>
13 #include <armnn/TensorFwd.hpp>
14 #include <armnn/Logging.hpp>
16 
17 #include <memory>
18 #include <vector>
19 
20 namespace armnn
21 {
22 /// @brief An input connection slot for a layer.
23 /// The input slot can be connected to an output slot of the preceding layer in the graph.
24 /// Only one connection to the input slot is allowed.
26 {
27 public:
28  virtual const IOutputSlot* GetConnection() const = 0;
29  virtual IOutputSlot* GetConnection() = 0;
30  virtual const IConnectableLayer& GetOwningIConnectableLayer() const = 0;
32  virtual unsigned int GetSlotIndex() const = 0;
33 
34 protected:
35  /// Not user deletable.
37 };
38 
39 /// @brief An output connection slot for a layer.
40 /// The output slot may be connected to 1 or more input slots of subsequent layers in the graph.
42 {
43 public:
44  virtual unsigned int GetNumConnections() const = 0;
45  virtual const IInputSlot* GetConnection(unsigned int index) const = 0;
46  virtual IInputSlot* GetConnection(unsigned int outputindex) = 0;
47 
48  virtual void SetTensorInfo(const TensorInfo& tensorInfo) = 0;
49  virtual const TensorInfo& GetTensorInfo() const = 0;
50  virtual bool IsTensorInfoSet() const = 0;
51 
52  virtual int Connect(IInputSlot& destination) = 0;
53  virtual void Disconnect(IInputSlot& slot) = 0;
54 
55  virtual unsigned int CalculateIndexOnOwner() const = 0;
56 
57  virtual LayerGuid GetOwningLayerGuid() const = 0;
58 
59  virtual const IConnectableLayer& GetOwningIConnectableLayer() const = 0;
61 
62 protected:
63  /// Not user deletable.
65 };
66 
67 /// @brief Interface for a layer that is connectable to other layers via InputSlots and OutputSlots.
69 {
70 public:
71  /// Returns the name of the layer
72  virtual const char* GetName() const = 0;
73 
74  /// Returns the number of connectable input slots
75  virtual unsigned int GetNumInputSlots() const = 0;
76 
77  /// Returns the number of connectable output slots
78  virtual unsigned int GetNumOutputSlots() const = 0;
79 
80  /// Get a const input slot handle by slot index
81  virtual const IInputSlot& GetInputSlot(unsigned int index) const = 0;
82 
83  /// Get the input slot handle by slot index
84  virtual IInputSlot& GetInputSlot(unsigned int index) = 0;
85 
86  /// Get the const output slot handle by slot index
87  virtual const IOutputSlot& GetOutputSlot(unsigned int index) const = 0;
88 
89  /// Get the output slot handle by slot index
90  virtual IOutputSlot& GetOutputSlot(unsigned int index) = 0;
91 
92  /// Infer the shape of the output(s) based on the provided input shape(s)
93  virtual std::vector<TensorShape> InferOutputShapes(const std::vector<TensorShape>& inputShapes) const = 0;
94 
95  /// Returns the unique id of the layer
96  virtual LayerGuid GetGuid() const = 0;
97 
98  /// Apply a visitor to this layer
99  virtual void ExecuteStrategy(IStrategy& strategy) const = 0;
100 
101  /// Provide a hint for the optimizer as to which backend to prefer for this layer
102  virtual void BackendSelectionHint(Optional<BackendId> backend) = 0;
103 
104  /// Returns the armnn::LayerType of this layer
105  virtual LayerType GetType() const = 0;
106 
107  /// If the layer has a descriptor return it.
108  /// The base descriptor can then be cast to the correct descriptor class.
109  /// If the layer has no associated descriptor a struct of type NullDescriptor will be returned.
110  /// Note: NullDescriptors can be detected because they return true when
111  /// the BaseDescriptor IsNull function is invoked.
112  virtual const BaseDescriptor& GetParameters() const = 0;
113 
114  using ConstantTensors = std::vector<std::reference_wrapper<std::shared_ptr<ConstTensorHandle>>>;
115 
116  // Returns ConstantTensors of this Layer if it has any, otherwise returns empty vector.
117  virtual ConstantTensors GetConstantTensorsByRef() = 0;
118 
119 protected:
120  /// Objects are not deletable via the handle
122 };
123 
124 
125 /// ArmNN performs an optimization on each model/network before it gets loaded for execution. OptimizerOptions provides
126 /// a set of features that allows the user to customize this optimization on a per model basis.
128 {
130  : m_ReduceFp32ToFp16(false)
131  , m_Debug(false)
132  , m_DebugToFile(false)
133  , m_ReduceFp32ToBf16(false)
134  , m_shapeInferenceMethod(armnn::ShapeInferenceMethod::ValidateOnly)
135  , m_ImportEnabled(false)
136  , m_ModelOptions()
137  , m_ProfilingEnabled(false)
138  , m_ExportEnabled(false)
139  , m_AllowExpandedDims(false)
140  {}
141 
142  OptimizerOptions(bool reduceFp32ToFp16, bool debug, bool reduceFp32ToBf16, bool importEnabled,
143  ModelOptions modelOptions = {}, bool exportEnabled = false, bool debugToFile = false)
144  : m_ReduceFp32ToFp16(reduceFp32ToFp16)
145  , m_Debug(debug)
146  , m_DebugToFile(debugToFile)
147  , m_ReduceFp32ToBf16(reduceFp32ToBf16)
148  , m_shapeInferenceMethod(armnn::ShapeInferenceMethod::ValidateOnly)
149  , m_ImportEnabled(importEnabled)
150  , m_ModelOptions(modelOptions)
151  , m_ProfilingEnabled(false)
152  , m_ExportEnabled(exportEnabled)
153  , m_AllowExpandedDims(false)
154  {
155  if (m_ReduceFp32ToFp16 && m_ReduceFp32ToBf16)
156  {
157  throw InvalidArgumentException("BFloat16 and Float16 optimization cannot be enabled at the same time.");
158  }
159  }
160 
161  OptimizerOptions(bool reduceFp32ToFp16, bool debug, bool reduceFp32ToBf16 = false,
163  bool importEnabled = false, ModelOptions modelOptions = {}, bool exportEnabled = false,
164  bool debugToFile = false, bool allowExpandedDims = false)
165  : m_ReduceFp32ToFp16(reduceFp32ToFp16)
166  , m_Debug(debug)
167  , m_DebugToFile(debugToFile)
168  , m_ReduceFp32ToBf16(reduceFp32ToBf16)
169  , m_shapeInferenceMethod(shapeInferenceMethod)
170  , m_ImportEnabled(importEnabled)
171  , m_ModelOptions(modelOptions)
172  , m_ProfilingEnabled(false)
173  , m_ExportEnabled(exportEnabled)
174  , m_AllowExpandedDims(allowExpandedDims)
175  {
176  if (m_ReduceFp32ToFp16 && m_ReduceFp32ToBf16)
177  {
178  throw InvalidArgumentException("BFloat16 and Float16 optimization cannot be enabled at the same time.");
179  }
180  }
181 
182  const std::string ToString() const
183  {
184  std::stringstream stream;
185  stream << "OptimizerOptions: \n";
186  stream << "\tReduceFp32ToFp16: " << m_ReduceFp32ToFp16 << "\n";
187  stream << "\tReduceFp32ToBf16: " << m_ReduceFp32ToBf16 << "\n";
188  stream << "\tDebug: " << m_Debug << "\n";
189  stream << "\tDebug to file: " << m_DebugToFile << "\n";
190  stream << "\tShapeInferenceMethod: " <<
191  (m_shapeInferenceMethod == ShapeInferenceMethod::ValidateOnly ? "ValidateOnly" : "InferAndValidate") << "\n";
192  stream << "\tImportEnabled: " << m_ImportEnabled << "\n";
193  stream << "\tExportEnabled: " << m_ExportEnabled << "\n";
194  stream << "\tProfilingEnabled: " << m_ProfilingEnabled << "\n";
195  stream << "\tAllowExpandedDims: " << m_AllowExpandedDims << "\n";
196 
197  stream << "\tModelOptions: \n";
198  for (auto optionsGroup : m_ModelOptions)
199  {
200  for (size_t i=0; i < optionsGroup.GetOptionCount(); i++)
201  {
202  const armnn::BackendOptions::BackendOption option = optionsGroup.GetOption(i);
203  stream << "\t\tBackend: " << optionsGroup.GetBackendId() << "\n"
204  << "\t\t\tOption: " << option.GetName() << "\n"
205  << "\t\t\tValue: " << std::string(option.GetValue().ToString()) << "\n";
206  }
207  }
208 
209  return stream.str();
210  }
211 
212  /// Reduces all Fp32 operators in the model to Fp16 for faster processing.
213  /// @Note This feature works best if all operators of the model are in Fp32. ArmNN will add conversion layers
214  /// between layers that weren't in Fp32 in the first place or if the operator is not supported in Fp16.
215  /// The overhead of these conversions can lead to a slower overall performance if too many conversions are
216  /// required.
218 
219  // Add debug data for easier troubleshooting
220  bool m_Debug;
221 
222  // Pass debug data to separate output files for easier troubleshooting
224 
225  /// Reduces all Fp32 operators in the model to Bf16 for faster processing.
226  /// @Note This feature works best if all operators of the model are in Fp32. ArmNN will add conversion layers
227  /// between layers that weren't in Fp32 in the first place or if the operator is not supported in Bf16.
228  /// The overhead of these conversions can lead to a slower overall performance if too many conversions are
229  /// required.
231 
232  // Infer output size when not available
234 
235  // Enable Import
237 
238  // Enable Model Options
240 
241  // Enable profiling dump of the optimizer phase
243 
244  // Enable Export
246 
247  // When calculating tensor sizes dimensions of size == 1 will be ignored
249 };
250 
251 class IWorkloadFactory;
252 class NetworkImpl;
253 using INetworkPtr = std::unique_ptr<INetwork, void(*)(INetwork* network)>;
254 using IOptimizedNetworkPtr = std::unique_ptr<IOptimizedNetwork, void(*)(IOptimizedNetwork* network)>;
255 
256 using CompiledBlobDeleter = std::function<void(const void*)>;
257 using CompiledBlobPtr = std::unique_ptr<void, CompiledBlobDeleter>;
258 
259 /// Main network class which provides the interface for building up a neural network.
260 /// This object is subsequently required by the IRuntime::Load() method.
261 class INetwork
262 {
263 public:
264  static INetwork* CreateRaw(const NetworkOptions& networkOptions = {});
265  static INetworkPtr Create(const NetworkOptions& networkOptions = {});
266  static void Destroy(INetwork* network);
267 
268  Status PrintGraph();
269 
270  /// Adds an input layer to the network.
271  /// @param id - User generated id to uniquely identify a particular input. The same id needs to be specified.
272  /// when passing the inputs to the IRuntime::EnqueueWorkload() function.
273  /// @param name - Optional name for the layer.
274  /// @return - Interface for configuring the layer.
275  IConnectableLayer* AddInputLayer(LayerBindingId id, const char* name = nullptr);
276 
277  /// Adds an ArgMinMax layer to the network.
278  /// @param desc - Parameters for the L2 normalization operation.
279  /// @param name - Optional name for the layer.
280  /// @return - Interface for configuring the layer.
281  IConnectableLayer* AddArgMinMaxLayer(const ArgMinMaxDescriptor& desc,
282  const char* name = nullptr);
283 
284  /// Adds a cast layer to the network.
285  /// @param name - Optional name for the layer.
286  /// @return - Interface for configuring the layer.
287  IConnectableLayer* AddCastLayer(const char* name = nullptr);
288 
289  /// Add a Comparison layer to the network.
290  /// @param name - Optional name for the layer.
291  /// @param desc - Descriptor for the comparison operation.
292  /// @return - Interface for configuring the layer.
293  IConnectableLayer* AddComparisonLayer(const ComparisonDescriptor& comparisonDescriptor,
294  const char* name = nullptr);
295 
296  /// Adds a concatenation layer to the network.
297  /// @param concatDescriptor - ConcatDescriptor (synonym for OriginsDescriptor) to configure the concatenation
298  /// process. Number of Views must be equal to the number of inputs, and their order
299  /// must match - e.g. first view corresponds to the first input, second view to the
300  /// second input, etc....
301  /// @param name - Optional name for the layer.
302  /// @return - Interface for configuring the layer.
303  IConnectableLayer* AddConcatLayer(const ConcatDescriptor& concatDescriptor,
304  const char* name = nullptr);
305 
306  /// Adds a 2D convolution layer to the network.
307  /// @param convolution2dDescriptor - Description of the 2D convolution layer.
308  /// @param name - Optional name for the layer.
309  /// @return - Interface for configuring the layer.
310  IConnectableLayer* AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
311  const char* name = nullptr);
312 
313  /// Adds a 3D convolution layer to the network.
314  /// @param convolution3dDescriptor - Description of the 3D convolution layer.
315  /// @param name - Optional name for the layer.
316  /// @return - Interface for configuring the layer.
317  IConnectableLayer* AddConvolution3dLayer(const Convolution3dDescriptor& convolution3dDescriptor,
318  const char* name = nullptr);
319 
320  /// Adds a depth to space layer to the network.
321  /// @param depthToSpaceDescriptor - Parameters for the depth to space operation.
322  /// @param name - Optional name for the layer.
323  /// @return - Interface for configuring the layer.
324  IConnectableLayer* AddDepthToSpaceLayer(const DepthToSpaceDescriptor& depthToSpaceDescriptor,
325  const char* name = nullptr);
326 
327  /// Adds a 2D depthwise convolution layer to the network.
328  /// @param convolution2dDescriptor - Description of the 2D depthwise convolution layer.
329  /// @param name - Optional name for the layer.
330  /// @return - Interface for configuring the layer.
331  IConnectableLayer* AddDepthwiseConvolution2dLayer(const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
332  const char* name = nullptr);
333 
334  /// Adds a Dequantize layer to the network.
335  /// @return - Interface for configuring the layer.
336  IConnectableLayer* AddDequantizeLayer(const char* name = nullptr);
337 
338  /// Adds a Detection PostProcess layer to the network.
339  /// @param descriptor - Description of the Detection PostProcess layer.
340  /// @param anchors - Tensor for anchors.
341  /// @param name - Optional name for the layer.
342  /// @return - Interface for configuring the layer.
343  IConnectableLayer* AddDetectionPostProcessLayer(
344  const DetectionPostProcessDescriptor& descriptor,
345  const ConstTensor& anchors,
346  const char* name = nullptr);
347 
348  /// Add an ElementwiseUnary layer to the network.
349  /// @param name - Optional name for the layer.
350  /// @param desc - Descriptor for the elementwiseUnary operation.
351  /// @return - Interface for configuring the layer.
352  IConnectableLayer* AddElementwiseUnaryLayer(const ElementwiseUnaryDescriptor& elementwiseUnaryDescriptor,
353  const char* name = nullptr);
354 
355  /// Add an Fill layer to the network.
356  /// @param name - Optional name for the layer.
357  /// @param fillDescriptor - Descriptor for the fill operation.
358  /// @return - Interface for configuring the layer.
359  IConnectableLayer* AddFillLayer(const FillDescriptor& fillDescriptor,
360  const char* name = nullptr);
361 
362 
363  /// Adds a fully connected layer to the network.
364  /// @param fullyConnectedDescriptor - Description of the fully connected layer.
365  /// @return - Interface for configuring the layer.
366  ///
367  /// @note Weights and biases are passed in as inputs. If they are constant tensors you can simply store
368  /// them in a ConstantLayer as seen below. A full example can be found in samples/SimpleSample.cpp.
369  ///
370  /// @code
371  /// // Make sure the IsConstant flag is set on the weightsInfo before passing it to the ConstTensor.
372  /// ConstTensor weights(weightsInfo, weightsData);
373  ///
374  /// // Constant layer that now holds weights data for FullyConnected
375  /// IConnectableLayer* const constantWeightsLayer = myNetwork->AddConstantLayer(weights, "weights");
376  ///
377  /// FullyConnectedDescriptor fullyConnectedDesc;
378  /// IConnectableLayer* const fullyConnectedLayer = myNetwork->AddFullyConnectedLayer(fullyConnectedDesc,
379  /// "fully connected");
380  /// IConnectableLayer* InputLayer = myNetwork->AddInputLayer(0);
381  /// InputLayer->GetOutputSlot(0).Connect(fullyConnectedLayer->GetInputSlot(0));
382  /// constantWeightsLayer->GetOutputSlot(0).Connect(fullyConnectedLayer->GetInputSlot(1));
383  /// @endcode
384  IConnectableLayer* AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
385  const char* name = nullptr);
386 
387  /// Adds a permute layer to the network.
388  /// @param permuteDescriptor - PermuteDescriptor to configure the permute.
389  /// @param name - Optional name for the layer.
390  /// @return - Interface for configuring the layer.
391  IConnectableLayer* AddPermuteLayer(const PermuteDescriptor& permuteDescriptor,
392  const char* name = nullptr);
393 
394  /// Adds a batch to space ND layer to the network.
395  /// @param batchToSpaceNdDescriptor - Description of the layer.
396  /// @param name - Optional name for the layer.
397  /// @return - Interface for configuring the layer.
398  IConnectableLayer* AddBatchToSpaceNdLayer(const BatchToSpaceNdDescriptor& batchToSpaceNdDescriptor,
399  const char* name = nullptr);
400 
401  /// Adds a 2D pooling layer to the network.
402  /// @param pooling2dDescriptor - Pooling2dDescriptor to configure the pooling.
403  /// @param name - Optional name for the layer.
404  /// @return - Interface for configuring the layer.
405  IConnectableLayer* AddPooling2dLayer(const Pooling2dDescriptor& pooling2dDescriptor,
406  const char* name = nullptr);
407 
408  /// Adds a 3D pooling layer to the network.
409  /// @param pooling3dDescriptor - Pooling3dDescriptor to configure the pooling.
410  /// @param name - Optional name for the layer.
411  /// @return - Interface for configuring the layer.
412  IConnectableLayer* AddPooling3dLayer(const Pooling3dDescriptor& pooling3dDescriptor,
413  const char* name = nullptr);
414 
415  /// Adds a Precompiled layer to the network.
416  /// Method use is for backend users.
417  /// @param preCompiledDescriptor - PreCompiledDescriptor contains parameters for the Precompiled layer.
418  /// @param compiledBlobPtr - CompiledBlobPtr pre-compiled object set for the Precompiled layer.
419  /// @param backend - optional BackendId set for the Precompiled layer.
420  /// @return - Interface for configuring the layer.
421  IConnectableLayer* AddPrecompiledLayer(const PreCompiledDescriptor& preCompiledDescriptor,
422  CompiledBlobPtr compiledBlobPtr,
423  const Optional<BackendId>& backend,
424  const char* name = nullptr);
425 
426  /// Adds an activation layer to the network.
427  /// @param activationDescriptor - ActivationDescriptor to configure the activation.
428  /// @param name - Optional name for the layer.
429  /// @return - Interface for configuring the layer.
430  IConnectableLayer* AddActivationLayer(const ActivationDescriptor& activationDescriptor,
431  const char* name = nullptr);
432 
433  /// Adds a normalization layer to the network.
434  /// @param normalizationDescriptor - NormalizationDescriptor to configure the normalization.
435  /// @param name - Optional name for the layer.
436  /// @return - Interface for configuring the layer.
437  IConnectableLayer* AddNormalizationLayer(const NormalizationDescriptor& normalizationDescriptor,
438  const char* name = nullptr);
439 
440  /// Adds a slice layer to the network.
441  /// @param sliceDescriptor - SliceDescriptor to configure the slice operation.
442  /// @param name - Optional name for the layer.
443  /// @return - Interface for configuring the layer.
444  IConnectableLayer* AddSliceLayer(const SliceDescriptor& sliceDescriptor, const char* name = nullptr);
445 
446  /// Adds a softmax layer to the network.
447  /// If the data type is QAsymm8, then the output quantization parameters
448  /// must have a scale of 1/256 and an offset of 0
449  /// @param softmaxDescriptor - SoftmaxDescriptor to configure the softmax.
450  /// @param name - Optional name for the layer.
451  /// @return - Interface for configuring the layer.
452  IConnectableLayer* AddSoftmaxLayer(const SoftmaxDescriptor& softmaxDescriptor,
453  const char* name = nullptr);
454 
455  /// Adds a splitter layer to the network.
456  /// @param splitterDescriptor - ViewsDescriptor to configure the splitting process.
457  /// Number of Views must be equal to the number of outputs,
458  /// and their order must match - e.g. first view corresponds to
459  /// the first output, second view to the second output, etc....
460  /// @param name - Optional name for the layer.
461  /// @return - Interface for configuring the layer.
462  IConnectableLayer* AddSplitterLayer(const ViewsDescriptor& splitterDescriptor,
463  const char* name = nullptr);
464 
465  /// Adds a merge layer to the network.
466  /// @param name - Optional name for the layer.
467  /// @return - Interface for configuring the layer.
468  IConnectableLayer* AddMergeLayer(const char* name = nullptr);
469 
470  /// Adds an addition layer to the network.
471  /// @param name - Optional name for the layer.
472  /// @return - Interface for configuring the layer.
473  IConnectableLayer* AddAdditionLayer(const char* name = nullptr);
474 
475  /// Adds a multiplication layer to the network.
476  /// @param name - Optional name for the layer.
477  /// @return - Interface for configuring the layer.
478  IConnectableLayer* AddMultiplicationLayer(const char* name = nullptr);
479 
480  /// Adds a batch normalization layer to the network.
481  /// @param mean - Pre-calculated mean for each channel.
482  /// @param variance - Pre-calculated variance for each channel.
483  /// @param beta - Per-channel additive factor.
484  /// @param gamma - Per-channel multiplicative factor.
485  /// @return - Interface for configuring the layer.
486  /// @param name - Optional name for the layer.
487  IConnectableLayer* AddBatchNormalizationLayer(const BatchNormalizationDescriptor& desc,
488  const ConstTensor& mean,
489  const ConstTensor& variance,
490  const ConstTensor& beta,
491  const ConstTensor& gamma,
492  const char* name = nullptr);
493 
494  /// Adds a rank layer to the network.
495  /// @param name - Optional name for the layer.
496  /// @return - Interface for configuring the layer.
497  IConnectableLayer* AddRankLayer(const char* name = nullptr);
498 
499  /// Adds a resize layer to the network.
500  /// @param resizeDescriptor - Parameters for the resize operation.
501  /// @param name - Optional name for the layer.
502  /// @return - Interface for configuring the layer.
503  IConnectableLayer* AddResizeLayer(const ResizeDescriptor& resizeDescriptor,
504  const char* name = nullptr);
505 
506  /// Adds a reduce layer to the network.
507  /// @param ReduceDescriptor - Parameters for the reduce operation.
508  /// @param name - Optional name for the layer.
509  /// @return - Interface for configuring the layer.
510  IConnectableLayer* AddReduceLayer(const ReduceDescriptor& reduceDescriptor,
511  const char* name = nullptr);
512 
513  /// Adds an instance normalization layer to the network.
514  /// @param desc - Parameters for the instance normalization operation.
515  /// @param name - Optional name for the layer.
516  /// @return - Interface for configuring the layer.
517  IConnectableLayer* AddInstanceNormalizationLayer(const InstanceNormalizationDescriptor& desc,
518  const char* name = nullptr);
519 
520  /// Adds an L2 normalization layer to the network.
521  /// Normalization is performed along dimension 1, but requires a 4d input.
522  /// @param desc - Parameters for the L2 normalization operation.
523  /// @param name - Optional name for the layer.
524  /// @return - Interface for configuring the layer.
525  IConnectableLayer* AddL2NormalizationLayer(const L2NormalizationDescriptor& desc,
526  const char* name = nullptr);
527 
528  /// Adds a log softmax layer to the network.
529  /// @param logSoftmaxDescriptor - LogSoftmaxDescriptor to configure the log softmax.
530  /// @param name - Optional name for the layer.
531  /// @return - Interface for configuring the layer.
532  IConnectableLayer* AddLogSoftmaxLayer(const LogSoftmaxDescriptor& logSoftmaxDescriptor,
533  const char* name = nullptr);
534 
535  /// Adds a layer with no inputs and a single output, which always corresponds to
536  /// the passed in constant tensor.
537  /// @param input - Tensor to be provided as the only output of the layer. The layer will maintain
538  /// its own copy of the tensor data, meaning the memory referenced by @a input can
539  /// be freed or reused after this function is called.
540  /// @param name - Optional name for the layer.
541  /// @return - Interface for configuring the layer.
542  IConnectableLayer* AddConstantLayer(const ConstTensor& input,
543  const char* name = nullptr);
544 
545  /// Adds a reshape layer to the network.
546  /// @param reshapeDescriptor - Parameters for the reshape operation.
547  /// @param name - Optional name for the layer.
548  /// @return - Interface for configuring the layer.
549  IConnectableLayer* AddReshapeLayer(const ReshapeDescriptor& reshapeDescriptor,
550  const char* name = nullptr);
551 
552  /// Adds a shape layer to the network.
553  /// @param name - Optional name for the layer.
554  /// @return - Interface for configuring the layer.
555  IConnectableLayer* AddShapeLayer(const char* name = nullptr);
556 
557  /// Adds a space to batch layer to the network.
558  /// @param spaceToBatchNdDescriptor - Parameters for the space to batch operation.
559  /// @param name - Optional name for the layer.
560  /// @return - Interface for configuring the layer.
561  IConnectableLayer* AddSpaceToBatchNdLayer(const SpaceToBatchNdDescriptor& spaceToBatchNdDescriptor,
562  const char* name = nullptr);
563 
564  /// Adds a space to depth layer to the network.
565  /// @param spaceToDepthDescriptor - Parameters for the space to depth operation.
566  /// @param name - Optional name for the layer.
567  /// @return - Interface for configuring the layer.
568  IConnectableLayer* AddSpaceToDepthLayer(const SpaceToDepthDescriptor& spaceToDepthDescriptor,
569  const char* name = nullptr);
570 
571  /// Adds a floor layer to the network.
572  /// @param name - Optional name for the layer.
573  /// @return - Interface for configuring the layer.
574  IConnectableLayer* AddFloorLayer(const char* name = nullptr);
575 
576  /// Adds an output layer to the network.
577  /// @param id - User generated id to uniquely identify a particular output. The same id needs to be specified
578  /// when passing the outputs to the IRuntime::EnqueueWorkload() function.
579  /// @param name - Optional name for the layer.
580  /// @return - Interface for configuring the layer.
581  IConnectableLayer* AddOutputLayer(LayerBindingId id, const char* name = nullptr);
582 
583  /// Add a Lstm layer to the network
584  /// @param descriptor - Parameters for the Lstm operation
585  /// @param params - Weights and biases for the LSTM cell
586  /// @param name - Optional name for the layer
587  /// @return - Interface for configuring the layer.
588  IConnectableLayer* AddLstmLayer(const LstmDescriptor& descriptor,
589  const LstmInputParams& params,
590  const char* name = nullptr);
591 
592  /// Adds a division layer to the network.
593  /// @param name - Optional name for the layer.
594  /// @return - Interface for configuring the layer.
595  IConnectableLayer* AddDivisionLayer(const char* name = nullptr);
596 
597  /// Adds a subtraction layer to the network.
598  /// @param name - Optional name for the layer.
599  /// @return - Interface for configuring the layer.
600  IConnectableLayer* AddSubtractionLayer(const char* name = nullptr);
601 
602  /// Add a Maximum layer to the network.
603  /// @param name - Optional name for the layer.
604  /// @return - Interface for configuring the layer.
605  IConnectableLayer* AddMaximumLayer(const char* name = nullptr);
606 
607  /// Add a Mean layer to the network.
608  /// @param meanDescriptor - Parameters for the mean operation.
609  /// @param name - Optional name for the layer.
610  /// @return - Interface for configuring the layer.
611  IConnectableLayer* AddMeanLayer(const MeanDescriptor& meanDescriptor, const char* name = nullptr);
612 
613  /// Adds a fully pad layer to the network.
614  /// @param paddings - n by 2 tensor, where n is the rank of the input tensor,
615  /// such that paddings[i,0] indicates the amount of padding to add in front of dimonsion i, and
616  /// paddings[i,1] indicates the amount of padding to add after the end of dimension i
617  /// @param name - Optional name for the layer.
618  /// @return - Interface for configuring the layer.
619  IConnectableLayer* AddPadLayer(const PadDescriptor& padDescriptor,
620  const char* name = nullptr);
621 
622  /// Add a quantize layer to the network
623  ///@param name - Optional name for the layer.
624  /// @return - Interface for configuring the layer.
625  IConnectableLayer* AddQuantizeLayer(const char* name = nullptr);
626 
627  /// Adds a strided slice layer to the network.
628  /// @param StridedSliceDescriptor - Parameters for the strided slice operation.
629  /// @param name - Optional name for the layer.
630  /// @return - Interface for configuring the layer.
631  IConnectableLayer* AddStridedSliceLayer(const StridedSliceDescriptor& stridedSliceDescriptor,
632  const char* name = nullptr);
633 
634  /// Add a Minimum layer to the network.
635  /// @param name - Optional name for the layer.
636  /// @return - Interface for configuring the layer.
637  IConnectableLayer* AddMinimumLayer(const char* name = nullptr);
638 
639  /// Add Gather layer to the network.
640  /// @param descriptor - Description of the gather layer.
641  /// @param name - Optional name for the layer.
642  /// @return - Interface for configuring the layer.
643  IConnectableLayer* AddGatherLayer(const GatherDescriptor& descriptor,
644  const char* name = nullptr);
645 
646  /// Add GatherNd layer to the network.
647  /// @param name - Optional name for the layer.
648  /// @return - Interface for configuring the layer.
649  IConnectableLayer* AddGatherNdLayer(const char* name = nullptr);
650 
651  /// Adds a switch layer to the network.
652  /// @param name - Optional name for the layer.
653  /// @return - Interface for configuring the layer.
654  IConnectableLayer* AddSwitchLayer(const char* name = nullptr);
655 
656  /// Adds a PReLU layer to the network.
657  /// @param name - Optional name for the layer.
658  /// @return - Interface for configuring the layer.
659  IConnectableLayer* AddPreluLayer(const char* name = nullptr);
660 
661  /// Adds a 2D transpose convolution layer to the network.
662  /// @param descriptor - Description of the 2D transpose convolution layer.
663  /// @param weights - Tensor for the weights data.
664  /// @param biases - Optional tensor for the bias data.
665  /// @param name - Optional name for the layer.
666  /// @return - Interface for configuring the layer.
667  IConnectableLayer* AddTransposeConvolution2dLayer(const TransposeConvolution2dDescriptor& descriptor,
668  const ConstTensor& weights,
669  const Optional<ConstTensor>& biases,
670  const char* name = nullptr);
671 
672  /// Adds a transpose layer to the network.
673  /// @param transposeDescriptor - TransposeDescriptor to configure the transpose.
674  /// @param name - Optional name for the layer.
675  /// @return - Interface for configuring the layer.
676  IConnectableLayer* AddTransposeLayer(const TransposeDescriptor& transposeDescriptor,
677  const char* name = nullptr);
678 
679  /// Adds a stack layer to the network.
680  /// @param descriptor - Description of the stack layer.
681  /// @param name - Optional name for the layer.
682  /// @return - Interface for configuring the layer.
683  IConnectableLayer* AddStackLayer(const StackDescriptor& descriptor,
684  const char* name = nullptr);
685 
686  /// Add a stand-in layer for a type unknown to the Arm NN framework.
687  /// Note: Due to the nature of this layer, no validation can be performed by the framework.
688  /// Furthermore, Any model containing this layer cannot make use of dynamic tensors since the
689  /// tensor sizes cannot be inferred.
690  /// @descriptor - Descriptor for the StandIn layer.
691  /// @return - Interface for configuring the layer.
692  IConnectableLayer* AddStandInLayer(const StandInDescriptor& descriptor,
693  const char* name = nullptr);
694 
695  /// Add a QuantizedLstm layer to the network
696  /// @param params - The weights and biases for the Quantized LSTM cell
697  /// @param name - Optional name for the layer
698  /// @return - Interface for configuring the layer.
699  IConnectableLayer* AddQuantizedLstmLayer(const QuantizedLstmInputParams& params,
700  const char* name = nullptr);
701 
702  /// Add a QLstm layer to the network
703  /// @param descriptor - Parameters for the QLstm operation
704  /// @param params - Weights and biases for the layer
705  /// @param name - Optional name for the layer
706  /// @return - Interface for configuring the layer.
707  IConnectableLayer* AddQLstmLayer(const QLstmDescriptor& descriptor,
708  const LstmInputParams& params,
709  const char* name = nullptr);
710 
711  /// Adds a Logical Binary layer to the network.
712  /// @param descriptor - Description of the Logical Binary layer.
713  /// @param name - Optional name for the layer.
714  /// @return - Interface for configuring the layer.
715  IConnectableLayer* AddLogicalBinaryLayer(const LogicalBinaryDescriptor& descriptor,
716  const char* name = nullptr);
717 
718  /// Add a UnidirectionalSequenceLstm layer to the network
719  /// @param descriptor - Parameters for the UnidirectionalSequenceLstm operation
720  /// @param params - Weights and biases for the UnidirectionalSequenceLstm
721  /// @param name - Optional name for the layer
722  /// @return - Interface for configuring the layer.
723  IConnectableLayer* AddUnidirectionalSequenceLstmLayer(const UnidirectionalSequenceLstmDescriptor& descriptor,
724  const LstmInputParams& params,
725  const char* name = nullptr);
726 
727  /// Add a ChannelShuffle layer to the network
728  /// @param descriptor - Parameters for the ChannelShuffle operation
729  /// @param name - Optional name for the layer
730  /// @return - Interface for configuring the layer
731  IConnectableLayer* AddChannelShuffleLayer(const ChannelShuffleDescriptor& descriptor,
732  const char* name = nullptr);
733 
734  /// Add a BatchMatMul layer to the network
735  /// @param descriptor - Parameters for the BatchMatMul operation
736  /// @param name - Optional name for the layer
737  /// @return - Interface for configuring the layer
738  IConnectableLayer* AddBatchMatMulLayer(const BatchMatMulDescriptor& descriptor,
739  const char* name = nullptr);
740 
741  void ExecuteStrategy(IStrategy& strategy) const;
742 
743 protected:
744  ~INetwork();
745 
746  friend void VisitLayersTopologically(const INetwork* inputNetwork, IStrategy& strategy);
747  friend class TestConnectionPreservation;
748  friend TensorInfo GetInputTensorInfo(const INetwork* network);
749  friend IOptimizedNetworkPtr Optimize(const INetwork& network,
750  const std::vector<BackendId>& backendPreferences,
751  const IDeviceSpec& deviceSpec,
752  const OptimizerOptions& options,
753  Optional<std::vector<std::string>&> messages);
754 
755  INetwork(NetworkOptions networkOptions = {});
756 
757  std::unique_ptr<NetworkImpl> pNetworkImpl;
758 };
759 
760 namespace experimental
761 {
762 class AsyncNetworkImpl;
763 class WorkingMemHandle;
764 }
765 
766 struct BackendSettings;
767 struct OptimizationResult;
769 class IProfiler;
771 {
772 public:
773  static void Destroy(IOptimizedNetwork* network);
774 
775  Status PrintGraph();
776  Status SerializeToDot(std::ostream& stream) const;
777 
778  arm::pipe::ProfilingGuid GetGuid() const;
779 
780  size_t GetNumInputs() const;
781  size_t GetNumOutputs() const;
782 
783  void ExecuteStrategy(IStrategy& strategy) const;
784 
785  // Creates a copy of the IOptimizedNetwork. The IOptimizedNetwork will not be reoptimized,
786  // the provided ModelOptions will only be used when creating a LoadedNetwork.
787  IOptimizedNetwork(const IOptimizedNetwork& other, const ModelOptions& modelOptions);
788  IOptimizedNetwork(std::unique_ptr<Graph> graph);
789  IOptimizedNetwork(std::unique_ptr<OptimizedNetworkImpl> impl);
791 
792  const std::shared_ptr<IProfiler>& GetProfiler() const;
793 
794 protected:
795  friend class LoadedNetwork;
796 
797  friend class experimental::AsyncNetworkImpl;
799 
800  friend Graph& GetGraphForTesting(IOptimizedNetwork* optNetPtr);
802  friend IOptimizedNetworkPtr Optimize(const INetwork& inNetwork,
803  const std::vector<BackendId>& backendPreferences,
804  const IDeviceSpec& deviceSpec,
805  const OptimizerOptions& options,
806  Optional<std::vector<std::string>&> messages);
807  friend IOptimizedNetworkPtr Optimize(const Graph& inGraph,
808  const std::vector<BackendId>& backendPreferences,
809  const IDeviceSpec& deviceSpec,
810  const OptimizerOptions& options,
811  Optional<std::vector<std::string>&> messages);
812 
813  IOptimizedNetwork(std::unique_ptr<Graph> graph, const ModelOptions& modelOptions);
814 
815  std::unique_ptr<OptimizedNetworkImpl> pOptimizedNetworkImpl;
816 };
817 
818 /// Create an optimized version of the network
819 /// @param network INetwork description of the network to be optimized.
820 /// @param backendPreferences The choice of the backend ordered by user preferences.
821 /// @param deviceSpec DeviceSpec object as queried from the runtime. See IRuntime::GetDeviceSpec()
822 /// @param messages If there are failures or warnings a string describing same will be added to the vector
823 /// @param options OptimizerOptions object with optimizer configuration options
824 /// @return An IOptimizedNetworkPtr interface to the optimized network, throws an exception derived from
825 /// armnn::Exception if process fails.
826 
827 IOptimizedNetworkPtr Optimize(const INetwork& network,
828  const std::vector<BackendId>& backendPreferences,
829  const IDeviceSpec& deviceSpec,
830  const OptimizerOptions& options = OptimizerOptions(),
831  Optional<std::vector<std::string>&> messages = EmptyOptional());
832 
833 /// Create an optimized version of the network
834 /// @param inGraph Graph to be optimized.
835 /// @param backendPreferences The choice of the backend ordered by user preferences.
836 /// @param deviceSpec DeviceSpec object as queried from the runtime. See IRuntime::GetDeviceSpec()
837 /// @param messages If there are failures or warnings a string describing same will be added to the vector
838 /// @param options OptimizerOptions object with optimizer configuration options
839 /// @return An IOptimizedNetworkPtr interface to the optimized network, throws an exception derived from
840 /// armnn::Exception if process fails.
841 
842 IOptimizedNetworkPtr Optimize(const Graph& inGraph,
843  const std::vector<BackendId>& backendPreferences,
844  const IDeviceSpec& deviceSpec,
845  const OptimizerOptions& options,
846  Optional<std::vector<std::string>&> messages = EmptyOptional());
847 } //namespace armnn
ModelOptions m_ModelOptions
Definition: INetwork.hpp:239
A ViewsDescriptor for the SplitterLayer.
Interface for a layer that is connectable to other layers via InputSlots and OutputSlots.
Definition: INetwork.hpp:68
ShapeInferenceMethod m_shapeInferenceMethod
Definition: INetwork.hpp:233
A TransposeConvolution2dDescriptor for the TransposeConvolution2dLayer.
~IConnectableLayer()
Objects are not deletable via the handle.
Definition: INetwork.hpp:121
A ReshapeDescriptor for the ReshapeLayer.
A ComparisonDescriptor for the ComparisonLayer.
Definition: Descriptors.hpp:89
std::vector< BackendOptions > ModelOptions
A Convolution2dDescriptor for the Convolution2dLayer.
Main network class which provides the interface for building up a neural network. ...
Definition: INetwork.hpp:261
std::vector< BackendOptions > NetworkOptions
bool m_ReduceFp32ToBf16
Reduces all Fp32 operators in the model to Bf16 for faster processing.
Definition: INetwork.hpp:230
A LogicalBinaryDescriptor for the LogicalBinaryLayer.
Copyright (c) 2021 ARM Limited and Contributors.
A SpaceToDepthDescriptor for the SpaceToDepthLayer.
A BatchToSpaceNdDescriptor for the BatchToSpaceNdLayer.
Private implementation of INetwork.
Definition: Network.hpp:31
int LayerBindingId
Type of identifiers for bindable layers (inputs, outputs).
Definition: Types.hpp:290
A ResizeDescriptor for the ResizeLayer.
Base class for all descriptors.
Definition: Descriptors.hpp:22
A StackDescriptor for the StackLayer.
std::unique_ptr< void, CompiledBlobDeleter > CompiledBlobPtr
Definition: INetwork.hpp:257
bool m_ReduceFp32ToFp16
Reduces all Fp32 operators in the model to Fp16 for faster processing.
Definition: INetwork.hpp:217
A PadDescriptor for the PadLayer.
const std::string ToString() const
Definition: INetwork.hpp:182
std::unique_ptr< NetworkImpl > pNetworkImpl
Definition: INetwork.hpp:757
uint32_t GetNumInputs(bool biasEnabled)
std::vector< std::reference_wrapper< std::shared_ptr< ConstTensorHandle > >> ConstantTensors
Definition: INetwork.hpp:114
An LstmDescriptor for the LstmLayer.
IOptimizedNetworkPtr Optimize(const INetwork &network, const std::vector< BackendId > &backendPreferences, const IDeviceSpec &deviceSpec, const OptimizerOptions &options=OptimizerOptions(), Optional< std::vector< std::string > &> messages=EmptyOptional())
Create an optimized version of the network.
Definition: Network.cpp:1850
An output connection slot for a layer.
Definition: INetwork.hpp:41
A L2NormalizationDescriptor for the L2NormalizationLayer.
An ArgMinMaxDescriptor for ArgMinMaxLayer.
Definition: Descriptors.hpp:67
An OriginsDescriptor for the ConcatLayer.
A ReduceDescriptor for the REDUCE operators.
A FullyConnectedDescriptor for the FullyConnectedLayer.
A tensor defined by a TensorInfo (shape and data type) and an immutable backing store.
Definition: Tensor.hpp:327
Validate all output shapes.
A GatherDescriptor for the GatherLayer.
Status
enumeration
Definition: Types.hpp:42
std::unique_ptr< OptimizedNetworkImpl > pOptimizedNetworkImpl
Definition: INetwork.hpp:815
std::unique_ptr< IOptimizedNetwork, void(*)(IOptimizedNetwork *network)> IOptimizedNetworkPtr
Definition: INetwork.hpp:254
A StandInDescriptor for the StandIn layer.
A QLstmDescriptor for the QLstmLayer.
Device specific knowledge to be passed to the optimizer.
Definition: Types.hpp:280
ArmNN performs an optimization on each model/network before it gets loaded for execution.
Definition: INetwork.hpp:127
An ActivationDescriptor for the ActivationLayer.
Definition: Descriptors.hpp:36
A SliceDescriptor for the SliceLayer.
std::function< void(const void *)> CompiledBlobDeleter
Definition: INetwork.hpp:256
A Convolution3dDescriptor for the Convolution3dLayer.
A BatchMatMulDescriptor for the BatchMatMul operator.
A Pooling3dDescriptor for the Pooling3dLayer.
Graph & GetGraphForTesting(IOptimizedNetwork *optNet)
Definition: TestUtils.cpp:49
A SpaceToBatchNdDescriptor for the SpaceToBatchNdLayer.
virtual unsigned int GetSlotIndex() const =0
arm::pipe::ProfilingGuid LayerGuid
Define LayerGuid type.
Definition: Types.hpp:26
OptimizerOptions(bool reduceFp32ToFp16, bool debug, bool reduceFp32ToBf16=false, ShapeInferenceMethod shapeInferenceMethod=armnn::ShapeInferenceMethod::ValidateOnly, bool importEnabled=false, ModelOptions modelOptions={}, bool exportEnabled=false, bool debugToFile=false, bool allowExpandedDims=false)
Definition: INetwork.hpp:161
EmptyOptional is used to initialize the Optional class in case we want to have default value for an O...
Definition: Optional.hpp:32
A ElementwiseUnaryDescriptor for the ElementwiseUnaryLayer.
OptimizerOptions(bool reduceFp32ToFp16, bool debug, bool reduceFp32ToBf16, bool importEnabled, ModelOptions modelOptions={}, bool exportEnabled=false, bool debugToFile=false)
Definition: INetwork.hpp:142
~IInputSlot()
Not user deletable.
Definition: INetwork.hpp:36
A MeanDescriptor for the MeanLayer.
virtual const IOutputSlot * GetConnection() const =0
A TransposeDescriptor for the TransposeLayer.
A StridedSliceDescriptor for the StridedSliceLayer.
ModelOptions & GetModelOptionsForTesting(IOptimizedNetwork *optNet)
Definition: TestUtils.cpp:54
void Connect(armnn::IConnectableLayer *from, armnn::IConnectableLayer *to, const armnn::TensorInfo &tensorInfo, unsigned int fromIndex, unsigned int toIndex)
Definition: TestUtils.cpp:14
std::unique_ptr< INetwork, void(*)(INetwork *network)> INetworkPtr
Definition: INetwork.hpp:253
A PreCompiledDescriptor for the PreCompiledLayer.
~IOutputSlot()
Not user deletable.
Definition: INetwork.hpp:64
A Pooling2dDescriptor for the Pooling2dLayer.
A NormalizationDescriptor for the NormalizationLayer.
An InstanceNormalizationDescriptor for InstanceNormalizationLayer.
A ChannelShuffleDescriptor for the ChannelShuffle operator.
A SoftmaxDescriptor for the SoftmaxLayer.
ShapeInferenceMethod
The ShapeInferenceMethod modify how the output shapes are treated.
Definition: Types.hpp:221
An input connection slot for a layer.
Definition: INetwork.hpp:25
A DepthwiseConvolution2dDescriptor for the DepthwiseConvolution2dLayer.
A FillDescriptor for the FillLayer.
A BatchNormalizationDescriptor for the BatchNormalizationLayer.
const TensorInfo & GetTensorInfo(const ITensorHandle *tensorHandle)
float32 helpers
A PermuteDescriptor for the PermuteLayer.
LayerType
When adding a new layer, adapt also the LastLayer enum value in the enum class LayerType below...
Definition: Types.hpp:468
virtual const IConnectableLayer & GetOwningIConnectableLayer() const =0