ArmNN  NotReleased
Layer.hpp
Go to the documentation of this file.
1 //
2 // Copyright © 2017 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5 #pragma once
6 
7 #include "LayerFwd.hpp"
8 
10 #include <OutputHandler.hpp>
14 #include "InternalTypes.hpp"
16 
17 #include <armnn/Types.hpp>
18 #include <armnn/Tensor.hpp>
19 #include <armnn/INetwork.hpp>
20 
21 #include <algorithm>
22 #include <memory>
23 #include <string>
24 #include <vector>
25 #include <iostream>
26 #include <functional>
27 #include <list>
28 
29 #include <boost/numeric/conversion/cast.hpp>
30 #include <boost/core/ignore_unused.hpp>
31 #include <boost/cast.hpp>
32 
33 namespace armnn
34 {
35 
36 class IWorkload;
37 class IWorkloadFactory;
38 class Layer;
39 class Graph;
40 
41 class InputSlot final : public IInputSlot
42 {
43 public:
44  explicit InputSlot(Layer& owner, unsigned int slotIndex)
45  : m_OwningLayer(owner)
46  , m_Connection(nullptr)
47  , m_SlotIndex(slotIndex)
48  {}
49 
50  ~InputSlot();
51 
52  Layer& GetOwningLayer() const { return m_OwningLayer; }
53  unsigned int GetSlotIndex() const { return m_SlotIndex; }
54 
55  const OutputSlot* GetConnectedOutputSlot() const { return m_Connection; }
56  OutputSlot* GetConnectedOutputSlot() { return m_Connection; }
57 
59  void SetConnection(OutputSlot* source)
60  {
61  if (m_Connection != nullptr && source != nullptr)
62  {
63  throw InvalidArgumentException("Tried to connect an output slot to an input slot, "
64  "but the latter already has a connection");
65  }
66  m_Connection = source;
67  }
68 
69  // Inserts single-output existing layer at this point in the graph.
70  void Insert(Layer& layer);
71 
72  // IInputSlot
73 
74  const IOutputSlot* GetConnection() const override;
75  IOutputSlot* GetConnection() override;
76 
77 private:
78  Layer& m_OwningLayer;
79  OutputSlot* m_Connection;
80  const unsigned int m_SlotIndex;
81 };
82 
83 class OutputSlot final : public IOutputSlot
84 {
85 public:
86  explicit OutputSlot(Layer& owner, OutputHandler& outputHandler)
87  : m_OwningLayer(owner)
88  , m_OutputHandler(outputHandler)
89  , m_TensorHandleFactoryId(ITensorHandleFactory::LegacyFactoryId)
90  {}
91 
92  OutputSlot(const OutputSlot&) = delete;
93  OutputSlot& operator=(const OutputSlot&) = delete;
94  OutputSlot& operator=(OutputSlot&&) = delete;
95 
96  OutputSlot(OutputSlot&&) = default;
97 
99  {
100  try
101  {
102  // Coverity fix: DisconnectAll() may throw uncaught exceptions.
103  DisconnectAll();
104  }
105  catch (const std::exception& e)
106  {
107  // Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an
108  // exception of type std::length_error.
109  // Using stderr instead in this context as there is no point in nesting try-catch blocks here.
110  std::cerr << "WARNING: An error has occurred when disconnecting all output slots: "
111  << e.what() << std::endl;
112  }
113  }
114 
115  Layer& GetOwningLayer() const { return m_OwningLayer; }
116 
117  LayerGuid GetOwningLayerGuid() const override;
118 
119  const OutputHandler& GetOutputHandler() const { return m_OutputHandler; }
120  OutputHandler& GetOutputHandler() { return m_OutputHandler; }
121 
122  int Connect(InputSlot& destination);
123  void Disconnect(InputSlot& slot);
124 
125  const std::vector<InputSlot*>& GetConnections() const { return m_Connections; }
126  const std::vector<EdgeStrategy>& GetEdgeStrategies() const { return m_EdgeStrategies; }
127 
128  bool ValidateTensorShape(const TensorShape& shape) const;
129 
130  // Disconnect all conections.
131  void DisconnectAll();
132 
134  void MoveAllConnections(OutputSlot& destination);
135 
136  // IOutputSlot
137 
138  unsigned int GetNumConnections() const override { return boost::numeric_cast<unsigned int>(m_Connections.size()); }
139  const InputSlot* GetConnection(unsigned int index) const override;
140  InputSlot* GetConnection(unsigned int index) override;
141 
142  void SetTensorInfo(const TensorInfo& tensorInfo) override;
143  const TensorInfo& GetTensorInfo() const override;
144  bool IsTensorInfoSet() const override;
145 
146  int Connect(IInputSlot& destination) override
147  {
148  return Connect(*boost::polymorphic_downcast<InputSlot*>(&destination));
149  }
150 
151  void Disconnect(IInputSlot& slot) override
152  {
153  return Disconnect(*boost::polymorphic_downcast<InputSlot*>(&slot));
154  }
155 
156  unsigned int CalculateIndexOnOwner() const override;
157 
158  bool operator==(const OutputSlot& other) const;
159 
160  void SetTensorHandleFactory(const ITensorHandleFactory::FactoryId& id);
161  ITensorHandleFactory::FactoryId GetTensorHandleFactoryId() const;
162 
163  void SetEdgeStrategy(unsigned int connectionIndex, EdgeStrategy strategy);
164  EdgeStrategy GetEdgeStrategyForConnection(unsigned int connectionIdx) const;
165 
166 private:
167  void ValidateConnectionIndex(unsigned int index) const;
168 
169  Layer& m_OwningLayer;
170  OutputHandler& m_OutputHandler;
171  std::vector<InputSlot*> m_Connections;
172 
173  ITensorHandleFactory::FactoryId m_TensorHandleFactoryId;
174  std::vector<EdgeStrategy> m_EdgeStrategies;
175 };
176 
177 // InputSlot inlines that need OutputSlot declaration.
178 
180 {
181  if (m_Connection != nullptr)
182  {
183  try
184  {
185  // Coverity fix: Disconnect() may throw uncaught exceptions.
186  m_Connection->Disconnect(*this);
187  }
188  catch (const std::exception& e)
189  {
190  // Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an
191  // exception of type std::length_error.
192  // Using stderr instead in this context as there is no point in nesting try-catch blocks here.
193  std::cerr << "WARNING: An error has occurred when disconnecting an input slot: "
194  << e.what() << std::endl;
195  }
196  }
197 }
198 
201 
202 
204 
205 // Base layer class
206 
207 using LayerPriority = unsigned int;
208 
209 class Layer : public IConnectableLayer
210 {
211 public:
213  Layer(unsigned int numInputSlots, unsigned int numOutputSlots, LayerType type, const char* name);
214  Layer(unsigned int numInputSlots, unsigned int numOutputSlots, LayerType type, DataLayout layout, const char* name);
215 
216  const std::string& GetNameStr() const
217  {
218  return m_LayerName;
219  }
220 
221  const OutputHandler& GetOutputHandler(unsigned int i = 0) const
222  {
223  return m_OutputHandlers[i];
224  }
225 
226  OutputHandler& GetOutputHandler(unsigned int i = 0)
227  {
228  return const_cast<OutputHandler&>(const_cast<const Layer*>(this)->GetOutputHandler(i));
229  }
230 
231  const std::vector<InputSlot>& GetInputSlots() const { return m_InputSlots; }
232  const std::vector<OutputSlot>& GetOutputSlots() const { return m_OutputSlots; }
233 
234  // Allows non-const access to input slots, but don't expose vector (vector size is fixed at layer construction).
235  std::vector<InputSlot>::iterator BeginInputSlots() { return m_InputSlots.begin(); }
236  std::vector<InputSlot>::iterator EndInputSlots() { return m_InputSlots.end(); }
237 
238  // Allows non-const access to output slots, but don't expose vector (vector size is fixed at layer construction).
239  std::vector<OutputSlot>::iterator BeginOutputSlots() { return m_OutputSlots.begin(); }
240  std::vector<OutputSlot>::iterator EndOutputSlots() { return m_OutputSlots.end(); }
241 
242  // Checks whether the outputs of this layer don't have any connection.
244  {
245  unsigned int numConnections = 0;
246 
247  for (auto&& output : GetOutputSlots())
248  {
249  numConnections += output.GetNumConnections();
250  }
251 
252  return (GetNumOutputSlots() > 0) && (numConnections == 0);
253  }
254 
255  // Used for sorting.
256  void ResetPriority() const;
257  LayerPriority GetPriority() const;
258 
259  LayerType GetType() const { return m_Type; }
260 
261  DataType GetDataType() const;
262 
263  const BackendId& GetBackendId() const { return m_BackendId; }
264  void SetBackendId(const BackendId& id) { m_BackendId = id; }
265 
266  // Virtuals
267 
268  virtual std::unique_ptr<IWorkload> CreateWorkload(const IWorkloadFactory& factory) const = 0;
269 
270  virtual void CreateTensorHandles(const TensorHandleFactoryRegistry& registry,
271  const IWorkloadFactory& factory,
272  const bool IsMemoryManaged = true);
273 
276  virtual Layer* Clone(Graph& graph) const = 0;
277 
278  void VerifyLayerConnections(unsigned int expectedConnections, const CheckLocation& location) const;
279 
280  virtual void ValidateTensorShapesFromInputs() = 0;
281 
282  std::vector<TensorShape> InferOutputShapes(const std::vector<TensorShape>& inputShapes) const override;
283 
286  virtual void SerializeLayerParameters(ParameterStringifyFunction& fn) const;
287 
288  // Free up the constant source data
289  virtual void ReleaseConstantData();
290 
291  template<typename Op>
293  {
294  for (auto constant : GetConstantTensorsByRef())
295  {
296  if (constant.get())
297  {
298  op(constant);
299  }
300  }
301  };
302 
303  // IConnectableLayer
304 
305  const char* GetName() const override { return m_LayerName.c_str(); }
306 
307  unsigned int GetNumInputSlots() const override { return static_cast<unsigned int>(m_InputSlots.size()); }
308  unsigned int GetNumOutputSlots() const override { return static_cast<unsigned int>(m_OutputSlots.size()); }
309 
310  const InputSlot& GetInputSlot(unsigned int index) const override { return m_InputSlots.at(index); }
311  InputSlot& GetInputSlot(unsigned int index) override { return m_InputSlots.at(index); }
312  const OutputSlot& GetOutputSlot(unsigned int index = 0) const override { return m_OutputSlots.at(index); }
313  OutputSlot& GetOutputSlot(unsigned int index = 0) override { return m_OutputSlots.at(index); }
314 
315  void SetGuid(LayerGuid guid) { m_Guid = guid; }
316  LayerGuid GetGuid() const final { return m_Guid; }
317 
318  void AddRelatedLayerName(const std::string layerName) { m_RelatedLayerNames.emplace_back(layerName); }
319 
320  const std::list<std::string>& GetRelatedLayerNames() { return m_RelatedLayerNames; }
321 
322  virtual void Reparent(Graph& dest, std::list<Layer*>::const_iterator iterator) = 0;
323 protected:
324  // Graph needs access to the virtual destructor.
325  friend class Graph;
326  virtual ~Layer() = default;
327 
328  template <typename QueueDescriptor>
330  {
331  WorkloadDataCollector dataCollector(descriptor.m_Inputs, info.m_InputTensorInfos);
332  CollectWorkloadInputs(dataCollector);
333  }
334 
335  template <typename QueueDescriptor>
337  {
338  WorkloadDataCollector dataCollector(descriptor.m_Outputs, info.m_OutputTensorInfos);
339  CollectWorkloadOutputs(dataCollector);
340  }
341 
343  template <typename QueueDescriptor>
345  {
347  CollectQueueDescriptorInputs(descriptor, info);
348  CollectQueueDescriptorOutputs(descriptor, info);
349  return info;
350  }
351 
352  template <typename LayerType, typename ... Params>
353  LayerType* CloneBase(Graph& graph, Params&& ... params) const;
354 
355  // Retrieve the Handles to the constants
356  using ConstantTensors = std::vector<std::reference_wrapper<std::unique_ptr<ScopedCpuTensorHandle>>>;
358 
359 private:
360  void CollectWorkloadInputs(WorkloadDataCollector& dataCollector) const;
361  void CollectWorkloadOutputs(WorkloadDataCollector& dataCollector) const;
362 
363 protected:
364  std::vector<OutputHandler> m_OutputHandlers;
365 
366 private:
367  const std::string m_LayerName;
368 
369  std::vector<InputSlot> m_InputSlots;
370  std::vector<OutputSlot> m_OutputSlots;
371 
372  const LayerType m_Type;
373  BackendId m_BackendId;
374 
376  mutable LayerPriority m_Priority = 0;
377  mutable bool m_Visiting = false;
378 
379  LayerGuid m_Guid;
380 
381  std::list<std::string> m_RelatedLayerNames;
382 };
383 
384 // A layer user-provided data can be bound to (e.g. inputs, outputs).
385 class BindableLayer : public Layer
386 {
387 public:
388  BindableLayer(unsigned int numInputSlots,
389  unsigned int numOutputSlots,
390  LayerType type,
391  const char* name,
392  LayerBindingId id)
393  : Layer(numInputSlots, numOutputSlots, type, name)
394  , m_Id(id)
395  {
396  }
397 
398  LayerBindingId GetBindingId() const { return m_Id; };
399 
400 protected:
401  ~BindableLayer() = default;
402 
403 private:
404  LayerBindingId m_Id;
405 };
406 
407 }
const OutputHandler & GetOutputHandler(unsigned int i=0) const
Definition: Layer.hpp:221
unsigned int GetNumOutputSlots() const override
Definition: Layer.hpp:308
LayerGuid GetGuid() const final
Definition: Layer.hpp:316
const std::vector< EdgeStrategy > & GetEdgeStrategies() const
Definition: Layer.hpp:126
const OutputSlot * GetConnectedOutputSlot() const
Definition: Layer.hpp:55
LayerType GetType() const
Definition: Layer.hpp:259
void Disconnect(IInputSlot &slot) override
Definition: Layer.hpp:151
const char * GetName() const override
Definition: Layer.hpp:305
std::vector< InputSlot >::iterator BeginInputSlots()
Definition: Layer.hpp:235
OutputHandler & GetOutputHandler(unsigned int i=0)
Definition: Layer.hpp:226
InputSlot & GetInputSlot(unsigned int index) override
Definition: Layer.hpp:311
void CollectQueueDescriptorOutputs(QueueDescriptor &descriptor, WorkloadInfo &info) const
Definition: Layer.hpp:336
InputSlot(Layer &owner, unsigned int slotIndex)
Definition: Layer.hpp:44
std::vector< InputSlot >::iterator EndInputSlots()
Definition: Layer.hpp:236
WorkloadInfo PrepInfoAndDesc(QueueDescriptor &descriptor) const
Helper function to reduce duplication in *LayerCreateWorkload.
Definition: Layer.hpp:344
unsigned int LayerPriority
Definition: Layer.hpp:207
std::vector< TensorInfo > m_OutputTensorInfos
const std::vector< OutputSlot > & GetOutputSlots() const
Definition: Layer.hpp:232
const BackendId & GetBackendId() const
Definition: Layer.hpp:263
const std::string & GetNameStr() const
Definition: Layer.hpp:216
BindableLayer(unsigned int numInputSlots, unsigned int numOutputSlots, LayerType type, const char *name, LayerBindingId id)
Definition: Layer.hpp:388
unsigned int GetSlotIndex() const
Definition: Layer.hpp:53
OutputSlot * GetConnectedOutputSlot()
Definition: Layer.hpp:56
OutputSlot(Layer &owner, OutputHandler &outputHandler)
Definition: Layer.hpp:86
const std::vector< InputSlot > & GetInputSlots() const
Definition: Layer.hpp:231
OutputSlot & GetOutputSlot(unsigned int index=0) override
Definition: Layer.hpp:313
std::vector< std::reference_wrapper< std::unique_ptr< ScopedCpuTensorHandle > >> ConstantTensors
Definition: Layer.hpp:356
void SetGuid(LayerGuid guid)
Definition: Layer.hpp:315
unsigned int GetNumConnections() const override
Definition: Layer.hpp:138
void SetBackendId(const BackendId &id)
Definition: Layer.hpp:264
const IOutputSlot * GetConnection() const override
Definition: Layer.hpp:199
OutputHandler & GetOutputHandler()
Definition: Layer.hpp:120
bool operator==(const armnn::DataLayout &dataLayout, const DataLayoutIndexed &indexed)
const OutputHandler & GetOutputHandler() const
Definition: Layer.hpp:119
std::vector< TensorInfo > m_InputTensorInfos
An input connection slot for a layer. The input slot can be connected to an output slot of the preced...
Definition: INetwork.hpp:24
const std::vector< InputSlot * > & GetConnections() const
Definition: Layer.hpp:125
bool IsOutputUnconnected()
Definition: Layer.hpp:243
void CollectQueueDescriptorInputs(QueueDescriptor &descriptor, WorkloadInfo &info) const
Definition: Layer.hpp:329
std::vector< OutputSlot >::iterator EndOutputSlots()
Definition: Layer.hpp:240
void AddRelatedLayerName(const std::string layerName)
Definition: Layer.hpp:318
void SetConnection(OutputSlot *source)
Links the slot to an output slot or breaks an existing link if passing nullptr.
Definition: Layer.hpp:59
An output connection slot for a layer. The output slot may be connected to 1 or more input slots of s...
Definition: INetwork.hpp:37
std::vector< OutputHandler > m_OutputHandlers
Definition: Layer.hpp:364
LayerBindingId GetBindingId() const
Definition: Layer.hpp:398
void Connect(armnn::IConnectableLayer *from, armnn::IConnectableLayer *to, const armnn::TensorInfo &tensorInfo, unsigned int fromIndex, unsigned int toIndex)
Definition: TestUtils.cpp:12
DataLayout
Definition: Types.hpp:48
std::unique_ptr< armnn::IWorkload > CreateWorkload(const armnn::IWorkloadFactory &workloadFactory, const armnn::WorkloadInfo &info, const DescriptorType &descriptor)
DataType
Definition: Types.hpp:32
std::function< void(const std::string &name, const std::string &value)> ParameterStringifyFunction
int Connect(IInputSlot &destination) override
Definition: Layer.hpp:146
Interface for a layer that is connectable to other layers via InputSlots and OutputSlots.
Definition: INetwork.hpp:61
std::vector< OutputSlot >::iterator BeginOutputSlots()
Definition: Layer.hpp:239
std::vector< ITensorHandle * > m_Outputs
std::vector< ITensorHandle * > m_Inputs
void OperateOnConstantTensors(Op op)
Definition: Layer.hpp:292
unsigned int GetNumInputSlots() const override
Definition: Layer.hpp:307
void Insert(Layer &layer)
Definition: Layer.cpp:20
virtual ConstantTensors GetConstantTensorsByRef()
Definition: Layer.hpp:357
Layer & GetOwningLayer() const
Definition: Layer.hpp:115
int LayerBindingId
Type of identifiers for bindable layers (inputs, outputs).
Definition: Types.hpp:168
const OutputSlot & GetOutputSlot(unsigned int index=0) const override
Definition: Layer.hpp:312
const std::list< std::string > & GetRelatedLayerNames()
Definition: Layer.hpp:320
const TensorInfo & GetTensorInfo(const ITensorHandle *tensorHandle)
float32 helpers
Layer & GetOwningLayer() const
Definition: Layer.hpp:52
const InputSlot & GetInputSlot(unsigned int index) const override
Definition: Layer.hpp:310