ArmNN
 22.02
Layer.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 
7 #include "LayerFwd.hpp"
8 
10 #include <OutputHandler.hpp>
14 #include "InternalTypes.hpp"
16 #include "DllExport.hpp"
17 
18 #include <armnn/Types.hpp>
19 #include <armnn/Tensor.hpp>
20 #include <armnn/INetwork.hpp>
24 
25 #include <algorithm>
26 #include <functional>
27 #include <iostream>
28 #include <list>
29 #include <memory>
30 #include <string>
31 #include <vector>
33 
34 namespace armnn
35 {
36 
37 class IWorkload;
38 class IWorkloadFactory;
39 class Layer;
40 class Graph;
41 
42 class InputSlot final : public IInputSlot
43 {
44 public:
45  explicit InputSlot(Layer& owner, unsigned int slotIndex)
46  : m_OwningLayer(owner)
47  , m_Connection(nullptr)
48  , m_SlotIndex(slotIndex)
49  {}
50 
51  ~InputSlot();
52 
53  Layer& GetOwningLayer() const { return m_OwningLayer; }
54  unsigned int GetSlotIndex() const { return m_SlotIndex; }
55 
56  const OutputSlot* GetConnectedOutputSlot() const { return m_Connection; }
57  OutputSlot* GetConnectedOutputSlot() { return m_Connection; }
58 
59  const IConnectableLayer& GetOwningIConnectableLayer() const override;
60 
61  /// Links the slot to an output slot or breaks an existing link if passing nullptr.
62  void SetConnection(OutputSlot* source)
63  {
64  if (m_Connection != nullptr && source != nullptr)
65  {
66  throw InvalidArgumentException("Tried to connect an output slot to an input slot, "
67  "but the latter already has a connection");
68  }
69  m_Connection = source;
70  }
71 
72  // Inserts single-output existing layer at this point in the graph.
73  void Insert(Layer& layer);
74 
75  // IInputSlot
76 
77  const IOutputSlot* GetConnection() const override;
78  IOutputSlot* GetConnection() override;
79 
80 private:
81  Layer& m_OwningLayer;
82  OutputSlot* m_Connection;
83  const unsigned int m_SlotIndex;
84 };
85 
86 class OutputSlot final : public IOutputSlot
87 {
88 public:
89  explicit OutputSlot(Layer& owner, OutputHandler& outputHandler)
90  : m_OwningLayer(owner)
91  , m_OutputHandler(outputHandler)
92  , m_TensorHandleFactoryId(ITensorHandleFactory::LegacyFactoryId)
93  {}
94 
95  OutputSlot(const OutputSlot&) = delete;
96  OutputSlot& operator=(const OutputSlot&) = delete;
97  OutputSlot& operator=(OutputSlot&&) = delete;
98 
99  OutputSlot(OutputSlot&&) = default;
100 
102  {
103  try
104  {
105  // Coverity fix: DisconnectAll() may throw uncaught exceptions.
106  DisconnectAll();
107  }
108  catch (const std::exception& e)
109  {
110  // Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an
111  // exception of type std::length_error.
112  // Using stderr instead in this context as there is no point in nesting try-catch blocks here.
113  std::cerr << "WARNING: An error has occurred when disconnecting all output slots: "
114  << e.what() << std::endl;
115  }
116  }
117 
118  Layer& GetOwningLayer() const { return m_OwningLayer; }
119 
120  const IConnectableLayer& GetOwningIConnectableLayer() const override;
121 
122  LayerGuid GetOwningLayerGuid() const override;
123 
124  const OutputHandler& GetOutputHandler() const { return m_OutputHandler; }
125  OutputHandler& GetOutputHandler() { return m_OutputHandler; }
126 
127  int Connect(InputSlot& destination);
128  void Disconnect(InputSlot& slot);
129 
130  const std::vector<InputSlot*>& GetConnections() const { return m_Connections; }
131  const std::vector<EdgeStrategy>& GetEdgeStrategies() const { return m_EdgeStrategies; }
132 
133  bool ValidateTensorShape(const TensorShape& shape) const;
134 
135  // Disconnect all conections.
136  void DisconnectAll();
137 
138  /// Moves all connections to another OutputSlot.
139  void MoveAllConnections(OutputSlot& destination);
140 
141  // IOutputSlot
142 
143  unsigned int GetNumConnections() const override { return armnn::numeric_cast<unsigned int>(m_Connections.size()); }
144  const InputSlot* GetConnection(unsigned int index) const override;
145  InputSlot* GetConnection(unsigned int index) override;
146 
147  void SetTensorInfo(const TensorInfo& tensorInfo) override;
148  const TensorInfo& GetTensorInfo() const override;
149  bool IsTensorInfoSet() const override;
150 
151  int Connect(IInputSlot& destination) override
152  {
153  return Connect(*PolymorphicDowncast<InputSlot*>(&destination));
154  }
155 
156  void Disconnect(IInputSlot& slot) override
157  {
158  return Disconnect(*PolymorphicDowncast<InputSlot*>(&slot));
159  }
160 
161  unsigned int CalculateIndexOnOwner() const override;
162 
163  bool operator==(const OutputSlot& other) const;
164 
165  void SetTensorHandleFactory(const ITensorHandleFactory::FactoryId& id);
166  ITensorHandleFactory::FactoryId GetTensorHandleFactoryId() const;
167 
168  void SetEdgeStrategy(unsigned int connectionIndex, EdgeStrategy strategy);
169  EdgeStrategy GetEdgeStrategyForConnection(unsigned int connectionIdx) const;
170 
171 private:
172  void ValidateConnectionIndex(unsigned int index) const;
173 
174  Layer& m_OwningLayer;
175  OutputHandler& m_OutputHandler;
176  std::vector<InputSlot*> m_Connections;
177 
178  ITensorHandleFactory::FactoryId m_TensorHandleFactoryId;
179  std::vector<EdgeStrategy> m_EdgeStrategies;
180 };
181 
182 // InputSlot inlines that need OutputSlot declaration.
183 
185 {
186  if (m_Connection != nullptr)
187  {
188  try
189  {
190  // Coverity fix: Disconnect() may throw uncaught exceptions.
191  m_Connection->Disconnect(*this);
192  }
193  catch (const std::exception& e)
194  {
195  // Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an
196  // exception of type std::length_error.
197  // Using stderr instead in this context as there is no point in nesting try-catch blocks here.
198  std::cerr << "WARNING: An error has occurred when disconnecting an input slot: "
199  << e.what() << std::endl;
200  }
201  }
202 }
203 
206 
207 
208 class ScopedTensorHandle;
209 
210 // Base layer class
211 
212 using LayerPriority = unsigned int;
213 using AdditionalInfoObjectPtr = std::shared_ptr<void>;
214 
215 class Layer : public IConnectableLayer
216 {
217 public:
218  /// @param name - Optional name for the layer (may be nullptr).
219  Layer(unsigned int numInputSlots, unsigned int numOutputSlots, LayerType type, const char* name);
220  Layer(unsigned int numInputSlots, unsigned int numOutputSlots, LayerType type, DataLayout layout, const char* name);
221 
222  void ExecuteStrategy(IStrategy& strategy) const override;
223 
224 
225  const std::string& GetNameStr() const
226  {
227  return m_LayerName;
228  }
229 
230  const OutputHandler& GetOutputHandler(unsigned int i = 0) const
231  {
232  return m_OutputHandlers[i];
233  }
234 
235  OutputHandler& GetOutputHandler(unsigned int i = 0)
236  {
237  return const_cast<OutputHandler&>(const_cast<const Layer*>(this)->GetOutputHandler(i));
238  }
239 
240  ShapeInferenceMethod GetShapeInferenceMethod() const { return m_ShapeInferenceMethod; };
241 
242  const std::vector<InputSlot>& GetInputSlots() const { return m_InputSlots; }
243  const std::vector<OutputSlot>& GetOutputSlots() const { return m_OutputSlots; }
244 
245  // Allows non-const access to input slots, but don't expose vector (vector size is fixed at layer construction).
246  std::vector<InputSlot>::iterator BeginInputSlots() { return m_InputSlots.begin(); }
247  std::vector<InputSlot>::iterator EndInputSlots() { return m_InputSlots.end(); }
248 
249  // Allows non-const access to output slots, but don't expose vector (vector size is fixed at layer construction).
250  std::vector<OutputSlot>::iterator BeginOutputSlots() { return m_OutputSlots.begin(); }
251  std::vector<OutputSlot>::iterator EndOutputSlots() { return m_OutputSlots.end(); }
252 
253  // Checks whether the outputs of this layer don't have any connection.
255  {
256  unsigned int numConnections = 0;
257 
258  for (auto&& output : GetOutputSlots())
259  {
260  numConnections += output.GetNumConnections();
261  }
262 
263  return (GetNumOutputSlots() > 0) && (numConnections == 0);
264  }
265 
266  // Used for sorting.
267  void ResetPriority() const;
268  LayerPriority GetPriority() const;
269 
270  LayerType GetType() const override { return m_Type; }
271 
272  DataType GetDataType() const;
273 
274  const BackendId& GetBackendId() const { return m_BackendId; }
275  void SetBackendId(const BackendId& id) { m_BackendId = id; }
276 
277  // Virtuals
278 
279  virtual std::unique_ptr<IWorkload> CreateWorkload(const IWorkloadFactory& factory) const = 0;
280 
281  virtual void CreateTensorHandles(const TensorHandleFactoryRegistry& registry,
282  const IWorkloadFactory& factory,
283  const bool IsMemoryManaged = true);
284 
285  /// Creates a dynamically-allocated copy of this layer.
286  /// @param graph - The Graph into which this Layer is being cloned.
287  virtual Layer* Clone(Graph& graph) const = 0;
288 
289  void VerifyLayerConnections(unsigned int expectedConnections, const CheckLocation& location) const;
290 
291  virtual void ValidateTensorShapesFromInputs() = 0;
292 
293  std::vector<TensorShape> InferOutputShapes(const std::vector<TensorShape>& inputShapes) const override;
294 
295  /// Helper to serialize the layer parameters to string.
296  /// (currently used in DotSerializer and company).
297  virtual void SerializeLayerParameters(ParameterStringifyFunction& fn) const;
298 
299  // Free up the constant source data
300  virtual void ReleaseConstantData();
301 
302  template<typename Op>
304  {
305  for (auto constant : GetConstantTensorsByRef())
306  {
307  if (constant.get())
308  {
309  op(constant);
310  }
311  }
312  };
313 
314  // IConnectableLayer
315 
316  const char* GetName() const override { return m_LayerName.c_str(); }
317 
318  unsigned int GetNumInputSlots() const override { return static_cast<unsigned int>(m_InputSlots.size()); }
319  unsigned int GetNumOutputSlots() const override { return static_cast<unsigned int>(m_OutputSlots.size()); }
320 
321  const InputSlot& GetInputSlot(unsigned int index) const override { return m_InputSlots.at(index); }
322  InputSlot& GetInputSlot(unsigned int index) override { return m_InputSlots.at(index); }
323  const OutputSlot& GetOutputSlot(unsigned int index = 0) const override { return m_OutputSlots.at(index); }
324  OutputSlot& GetOutputSlot(unsigned int index = 0) override { return m_OutputSlots.at(index); }
325 
326  void SetGuid(LayerGuid guid) { m_Guid = guid; }
327  LayerGuid GetGuid() const final { return m_Guid; }
328 
329  void AddRelatedLayerName(const std::string layerName) { m_RelatedLayerNames.emplace_back(layerName); }
330 
331  const std::list<std::string>& GetRelatedLayerNames() { return m_RelatedLayerNames; }
332 
333  virtual void Reparent(Graph& dest, std::list<Layer*>::const_iterator iterator) = 0;
334 
336  {
337  m_BackendHint = backend;
338  }
339  Optional<BackendId> GetBackendHint() const { return m_BackendHint; }
340 
342  {
343  m_ShapeInferenceMethod = shapeInferenceMethod;
344  }
345 
346  template<typename T>
347  std::shared_ptr<T> GetAdditionalInformation() const
348  {
349  return std::static_pointer_cast<T>(m_AdditionalInfoObject);
350  }
351 
353  {
354  m_AdditionalInfoObject = additionalInfo;
355  }
356 
357  virtual const BaseDescriptor& GetParameters() const override { return m_NullDescriptor; }
358 
359 protected:
360  // Graph needs access to the virtual destructor.
361  friend class Graph;
362  virtual ~Layer() = default;
363 
364  template <typename QueueDescriptor>
366  {
367  WorkloadDataCollector dataCollector(descriptor.m_Inputs, info.m_InputTensorInfos);
368  CollectWorkloadInputs(dataCollector);
369  }
370 
371  template <typename QueueDescriptor>
373  {
374  WorkloadDataCollector dataCollector(descriptor.m_Outputs, info.m_OutputTensorInfos);
375  CollectWorkloadOutputs(dataCollector);
376  }
377 
378  void ValidateAndCopyShape(const TensorShape& outputShape,
379  const TensorShape& inferredShape,
380  const ShapeInferenceMethod shapeInferenceMethod,
381  const std::string& layerName,
382  const unsigned int outputSlotIndex = 0);
383 
384  void VerifyShapeInferenceType(const TensorShape& outputShape, ShapeInferenceMethod shapeInferenceMethod);
385 
386  /// Helper function to reduce duplication in *Layer::CreateWorkload.
387  template <typename QueueDescriptor>
389  {
391  CollectQueueDescriptorInputs(descriptor, info);
392  CollectQueueDescriptorOutputs(descriptor, info);
393  return info;
394  }
395 
396  template <typename LayerType, typename ... Params>
397  LayerType* CloneBase(Graph& graph, Params&& ... params) const;
398 
399  // Retrieve the Handles to the constants
400  // Marking this as override and having this here keeps IConnectable abstract with only pure virtual function
401  virtual ConstantTensors GetConstantTensorsByRef() override {return ConstantTensors(); };
402 
403  // "Blob"
405 
406  // Utility method to set a pointer in the queueDescriptor to the "blob" location in the layer
407  void SetAdditionalInfo(QueueDescriptor& descriptor) const;
408 
409 private:
410  void CollectWorkloadInputs(WorkloadDataCollector& dataCollector) const;
411  void CollectWorkloadOutputs(WorkloadDataCollector& dataCollector) const;
412 
413 protected:
414  std::vector<OutputHandler> m_OutputHandlers;
416 
417 private:
418  const std::string m_LayerName;
419 
420  std::vector<InputSlot> m_InputSlots;
421  std::vector<OutputSlot> m_OutputSlots;
422 
423  const LayerType m_Type;
424  BackendId m_BackendId;
425  Optional<BackendId> m_BackendHint;
426 
427  /// Used for sorting.
428  mutable LayerPriority m_Priority = 0;
429  mutable bool m_Visiting = false;
430 
431  LayerGuid m_Guid;
432 
433  std::list<std::string> m_RelatedLayerNames;
434 
435  /// returned by layers which have no parameters associated with them.
436  /// has to be a member as it is returned as a const reference
437  /// declared static so that there is only ever one of them in memory
438  ARMNN_DLLEXPORT static NullDescriptor m_NullDescriptor;
439 };
440 
441 // A layer user-provided data can be bound to (e.g. inputs, outputs).
442 class BindableLayer : public Layer
443 {
444 public:
445  BindableLayer(unsigned int numInputSlots,
446  unsigned int numOutputSlots,
447  LayerType type,
448  const char* name,
449  LayerBindingId id)
450  : Layer(numInputSlots, numOutputSlots, type, name)
451  , m_Id(id)
452  {
453  }
454 
455  LayerBindingId GetBindingId() const { return m_Id; };
456 
457  void ExecuteStrategy(IStrategy& strategy) const override
458  {
459  strategy.ExecuteStrategy(this, BaseDescriptor(), {}, GetName(), GetBindingId());
460  }
461 
462 protected:
463  ~BindableLayer() = default;
464 
465 private:
466  LayerBindingId m_Id;
467 };
468 
469 }
std::vector< InputSlot >::iterator EndInputSlots()
Definition: Layer.hpp:247
void CollectQueueDescriptorInputs(QueueDescriptor &descriptor, WorkloadInfo &info) const
Definition: Layer.hpp:365
const std::vector< InputSlot * > & GetConnections() const
Definition: Layer.hpp:130
void Insert(Layer &layer)
Definition: Layer.cpp:23
Interface for a layer that is connectable to other layers via InputSlots and OutputSlots.
Definition: INetwork.hpp:66
DataLayout
Definition: Types.hpp:49
unsigned int GetNumInputSlots() const override
Returns the number of connectable input slots.
Definition: Layer.hpp:318
std::unique_ptr< armnn::IWorkload > CreateWorkload(const armnn::IWorkloadFactory &workloadFactory, const armnn::WorkloadInfo &info, const DescriptorType &descriptor)
Optional< BackendId > GetBackendHint() const
Definition: Layer.hpp:339
void AddRelatedLayerName(const std::string layerName)
Definition: Layer.hpp:329
void BackendSelectionHint(Optional< BackendId > backend) final
Provide a hint for the optimizer as to which backend to prefer for this layer.
Definition: Layer.hpp:335
void SetShapeInferenceMethod(ShapeInferenceMethod shapeInferenceMethod)
Definition: Layer.hpp:341
const std::vector< EdgeStrategy > & GetEdgeStrategies() const
Definition: Layer.hpp:131
LayerBindingId GetBindingId() const
Definition: Layer.hpp:455
void OperateOnConstantTensors(Op op)
Definition: Layer.hpp:303
void ExecuteStrategy(IStrategy &strategy) const override
Apply a visitor to this layer.
Definition: Layer.hpp:457
OutputSlot & GetOutputSlot(unsigned int index=0) override
Get the output slot handle by slot index.
Definition: Layer.hpp:324
Layer & GetOwningLayer() const
Definition: Layer.hpp:118
virtual void ExecuteStrategy(const armnn::IConnectableLayer *layer, const armnn::BaseDescriptor &descriptor, const std::vector< armnn::ConstTensor > &constants, const char *name, const armnn::LayerBindingId id=0)=0
ShapeInferenceMethod GetShapeInferenceMethod() const
Definition: Layer.hpp:240
unsigned int LayerPriority
Definition: Layer.hpp:212
void Disconnect(IInputSlot &slot) override
Definition: Layer.hpp:156
int Connect(IInputSlot &destination) override
Definition: Layer.hpp:151
Copyright (c) 2021 ARM Limited and Contributors.
void SetBackendId(const BackendId &id)
Definition: Layer.hpp:275
const std::vector< InputSlot > & GetInputSlots() const
Definition: Layer.hpp:242
const IOutputSlot * GetConnection() const override
Definition: Layer.hpp:204
bool IsOutputUnconnected()
Definition: Layer.hpp:254
unsigned int GetNumOutputSlots() const override
Returns the number of connectable output slots.
Definition: Layer.hpp:319
int LayerBindingId
Type of identifiers for bindable layers (inputs, outputs).
Definition: Types.hpp:277
Base class for all descriptors.
Definition: Descriptors.hpp:22
std::vector< InputSlot >::iterator BeginInputSlots()
Definition: Layer.hpp:246
const IConnectableLayer & GetOwningIConnectableLayer() const override
Definition: Layer.cpp:491
std::shared_ptr< void > AdditionalInfoObjectPtr
Definition: Layer.hpp:213
unsigned int GetNumConnections() const override
Definition: Layer.hpp:143
const InputSlot & GetInputSlot(unsigned int index) const override
Get a const input slot handle by slot index.
Definition: Layer.hpp:321
std::vector< TensorInfo > m_InputTensorInfos
#define ARMNN_DLLEXPORT
Definition: DllExport.hpp:17
bool operator==(const armnn::DataLayout &dataLayout, const DataLayoutIndexed &indexed)
Equality methods.
Null Descriptor used as a return value from the IConnectableLayer GetParameters method by layers whic...
Definition: Descriptors.hpp:30
std::vector< std::reference_wrapper< std::shared_ptr< ConstTensorHandle > >> ConstantTensors
Definition: INetwork.hpp:124
DataType
Definition: Types.hpp:35
void SetGuid(LayerGuid guid)
Definition: Layer.hpp:326
AdditionalInfoObjectPtr m_AdditionalInfoObject
Definition: Layer.hpp:401
WorkloadInfo PrepInfoAndDesc(QueueDescriptor &descriptor) const
Helper function to reduce duplication in *LayerCreateWorkload.
Definition: Layer.hpp:388
An output connection slot for a layer.
Definition: INetwork.hpp:40
InputSlot(Layer &owner, unsigned int slotIndex)
Definition: Layer.hpp:45
unsigned int GetSlotIndex() const
Definition: Layer.hpp:54
const std::string & GetNameStr() const
Definition: Layer.hpp:225
LayerType GetType() const override
Returns the armnn::LayerType of this layer.
Definition: Layer.hpp:270
const OutputSlot * GetConnectedOutputSlot() const
Definition: Layer.hpp:56
std::vector< TensorInfo > m_OutputTensorInfos
InputSlot & GetInputSlot(unsigned int index) override
Get the input slot handle by slot index.
Definition: Layer.hpp:322
Layer & GetOwningLayer() const
Definition: Layer.hpp:53
OutputSlot * GetConnectedOutputSlot()
Definition: Layer.hpp:57
const BackendId & GetBackendId() const
Definition: Layer.hpp:274
std::vector< OutputHandler > m_OutputHandlers
Definition: Layer.hpp:414
const std::vector< OutputSlot > & GetOutputSlots() const
Definition: Layer.hpp:243
BindableLayer(unsigned int numInputSlots, unsigned int numOutputSlots, LayerType type, const char *name, LayerBindingId id)
Definition: Layer.hpp:445
void SetAdditionalInfoForObject(const AdditionalInfoObjectPtr &additionalInfo)
Definition: Layer.hpp:352
const std::list< std::string > & GetRelatedLayerNames()
Definition: Layer.hpp:331
std::vector< OutputSlot >::iterator BeginOutputSlots()
Definition: Layer.hpp:250
std::vector< ITensorHandle * > m_Outputs
void CollectQueueDescriptorOutputs(QueueDescriptor &descriptor, WorkloadInfo &info) const
Definition: Layer.hpp:372
void SetConnection(OutputSlot *source)
Links the slot to an output slot or breaks an existing link if passing nullptr.
Definition: Layer.hpp:62
const OutputHandler & GetOutputHandler(unsigned int i=0) const
Definition: Layer.hpp:230
virtual const BaseDescriptor & GetParameters() const override
If the layer has a descriptor return it.
Definition: Layer.hpp:357
profiling::ProfilingGuid LayerGuid
Define LayerGuid type.
Definition: Types.hpp:363
std::vector< OutputSlot >::iterator EndOutputSlots()
Definition: Layer.hpp:251
std::enable_if_t< std::is_unsigned< Source >::value &&std::is_unsigned< Dest >::value, Dest > numeric_cast(Source source)
Definition: NumericCast.hpp:35
const OutputSlot & GetOutputSlot(unsigned int index=0) const override
Get the const output slot handle by slot index.
Definition: Layer.hpp:323
OutputHandler & GetOutputHandler()
Definition: Layer.hpp:125
OutputSlot(Layer &owner, OutputHandler &outputHandler)
Definition: Layer.hpp:89
const OutputHandler & GetOutputHandler() const
Definition: Layer.hpp:124
Contains information about TensorInfos of a layer.
const char * GetName() const override
Returns the name of the layer.
Definition: Layer.hpp:316
void Connect(armnn::IConnectableLayer *from, armnn::IConnectableLayer *to, const armnn::TensorInfo &tensorInfo, unsigned int fromIndex, unsigned int toIndex)
Definition: TestUtils.cpp:12
std::vector< ITensorHandle * > m_Inputs
std::function< void(const std::string &name, const std::string &value)> ParameterStringifyFunction
const TensorInfo & GetTensorInfo(const ITensorHandle *tensorHandle)
float32 helpers
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
ShapeInferenceMethod m_ShapeInferenceMethod
Definition: Layer.hpp:415
OutputHandler & GetOutputHandler(unsigned int i=0)
Definition: Layer.hpp:235
std::shared_ptr< T > GetAdditionalInformation() const
Definition: Layer.hpp:347
LayerType
When adding a new layer, adapt also the LastLayer enum value in the enum class LayerType below...
Definition: Types.hpp:458
LayerGuid GetGuid() const final
Returns the unique id of the layer.
Definition: Layer.hpp:327