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