ArmNN
 20.02
Layer.cpp
Go to the documentation of this file.
1 //
2 // Copyright © 2017 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5 #include "Layer.hpp"
6 
7 #include "Graph.hpp"
8 #include <ProfilingService.hpp>
11 
12 #include <boost/cast.hpp>
13 #include <boost/format.hpp>
14 
15 #include <numeric>
16 
17 namespace armnn
18 {
19 
21 {
22  BOOST_ASSERT(layer.GetNumOutputSlots() == 1);
23 
24  OutputSlot* const prevSlot = GetConnectedOutputSlot();
25 
26  if (prevSlot != nullptr)
27  {
28  // Disconnects parent from this.
29  prevSlot->Disconnect(*this);
30 
31  // Connects inserted layer to parent.
32  BOOST_ASSERT(layer.GetNumInputSlots() == 1);
33  int idx = prevSlot->Connect(layer.GetInputSlot(0));
34  prevSlot->SetEdgeStrategy(boost::numeric_cast<unsigned int>(idx), EdgeStrategy::Undefined);
35 
36  // Sets tensor info for inserted layer.
37  const TensorInfo& tensorInfo = prevSlot->GetTensorInfo();
38  layer.GetOutputHandler().SetTensorInfo(tensorInfo);
39  }
40 
41  // Connects inserted layer to this.
42  layer.GetOutputSlot(0).Connect(*this);
44 }
45 
46 const InputSlot* OutputSlot::GetConnection(unsigned int index) const
47 {
48  ValidateConnectionIndex(index);
49  return m_Connections[index];
50 }
51 
53 {
54  ValidateConnectionIndex(index);
55  return m_Connections[index];
56 }
57 
58 void OutputSlot::SetTensorInfo(const TensorInfo& tensorInfo)
59 {
60  GetOutputHandler().SetTensorInfo(tensorInfo);
61 }
62 
64 {
65  return GetOutputHandler().GetTensorInfo();
66 }
67 
69 {
70  return GetOutputHandler().IsTensorInfoSet();
71 }
72 
74 {
75  BOOST_ASSERT_MSG(IsTensorInfoSet(), "TensorInfo must be set in order to validate the shape.");
76  return shape == m_OutputHandler.GetTensorInfo().GetShape();
77 }
78 
79 int OutputSlot::Connect(InputSlot& destination)
80 {
81  destination.SetConnection(this);
82  m_Connections.push_back(&destination);
83  m_EdgeStrategies.push_back(EdgeStrategy::Undefined);
84  return boost::numeric_cast<int>(m_Connections.size() - 1);
85 }
86 
88 {
89  slot.SetConnection(nullptr);
90  auto it = std::find(m_Connections.begin(), m_Connections.end(), &slot);
91 
92  if (it == m_Connections.end())
93  {
94  return;
95  }
96 
97  auto idx = std::distance(m_Connections.begin(), it);
98  m_Connections.erase(std::remove(m_Connections.begin(), m_Connections.end(), &slot), m_Connections.end());
99 
100  m_EdgeStrategies.erase(m_EdgeStrategies.begin() + idx);
101 }
102 
104 {
105  while (GetNumConnections() > 0)
106  {
107  InputSlot& connection = *GetConnection(0);
108  Disconnect(connection);
109  }
110 }
111 
113 {
114  while (GetNumConnections() > 0)
115  {
116  BOOST_ASSERT_MSG(m_EdgeStrategies[0] == EdgeStrategy::Undefined,
117  "Cannot move connections once memory strategies have be established.");
118 
119  InputSlot& connection = *GetConnection(0);
120  Disconnect(connection);
121  destination.Connect(connection);
122  }
123 }
124 
126 {
127  for (unsigned int i = 0; i < GetOwningLayer().GetNumOutputSlots(); i++)
128  {
129  if (GetOwningLayer().GetOutputSlot(i) == (*this))
130  {
131  return i;
132  }
133  }
134  BOOST_ASSERT_MSG(false, "Did not find slot on owner.");
135  return 0; // Error
136 }
137 
138 bool OutputSlot::operator==(const OutputSlot& other) const
139 {
140  bool isSame = other.GetNumConnections() == GetNumConnections();
141  if (!isSame)
142  {
143  return false;
144  }
145 
146  for (unsigned int i = 0; i < GetNumConnections(); i++)
147  {
148  isSame &= other.GetConnection(i) == GetConnection(i);
149  }
150  return isSame;
151 }
152 
153 void OutputSlot::ValidateConnectionIndex(unsigned int index) const
154 {
155  if (boost::numeric_cast<std::size_t>(index) >= m_Connections.size())
156  {
158  boost::str(boost::format("GetConnection: Invalid index %1% provided") % index));
159  }
160 }
161 
163 {
164  return GetOwningLayer().GetGuid();
165 }
166 
168 {
169  m_TensorHandleFactoryId = id;
170 }
171 
173 {
174  return m_TensorHandleFactoryId;
175 }
176 
177 void OutputSlot::SetEdgeStrategy(unsigned int connectionIndex, EdgeStrategy strategy)
178 {
179  m_EdgeStrategies[connectionIndex] = strategy;
180 }
181 
183 {
184  return m_EdgeStrategies[connectionIdx];
185 }
186 
187 Layer::Layer(unsigned int numInputSlots,
188  unsigned int numOutputSlots,
189  LayerType type,
190  DataLayout layout,
191  const char* name)
192 : m_OutputHandlers(numOutputSlots)
193 , m_LayerName(name ? name : "")
194 , m_Type(type)
195 , m_BackendId()
196 , m_BackendHint(EmptyOptional())
197 , m_Guid(profiling::ProfilingService::Instance().NextGuid())
198 {
199  IgnoreUnused(layout);
200  m_InputSlots.reserve(numInputSlots);
201  for (unsigned int i = 0; i < numInputSlots; ++i)
202  {
203  m_InputSlots.emplace_back(*this, i);
204  }
205 
206  m_OutputSlots.reserve(numOutputSlots);
207  for (unsigned int i = 0; i < numOutputSlots; ++i)
208  {
209  m_OutputSlots.emplace_back(*this, m_OutputHandlers[i]);
210  }
211 }
212 
213 Layer::Layer(unsigned int numInputSlots,
214  unsigned int numOutputSlots,
215  LayerType type,
216  const char* name)
217 : Layer(numInputSlots, numOutputSlots, type, DataLayout::NCHW, name)
218 {
219 }
220 
221 void Layer::CollectWorkloadInputs(WorkloadDataCollector& dataCollector) const
222 {
223  for (auto&& inputSlot : GetInputSlots())
224  {
225  // The graph must be well-formed at this point.
226  BOOST_ASSERT(inputSlot.GetConnection());
227  const OutputHandler& outputHandler = inputSlot.GetConnectedOutputSlot()->GetOutputHandler();
228  dataCollector.Push(outputHandler.GetData(), outputHandler.GetTensorInfo());
229  }
230 }
231 
232 void Layer::CollectWorkloadOutputs(WorkloadDataCollector& dataCollector) const
233 {
234  for (auto&& outputHandler : m_OutputHandlers)
235  {
236  outputHandler.CollectWorkloadOutputs(dataCollector);
237  }
238 }
239 
241  const IWorkloadFactory& workloadFactory,
242  const bool IsMemoryManaged)
243 {
244  for (unsigned int idx=0; idx < GetNumOutputSlots(); idx++)
245  {
246 
247  OutputSlot& slot = GetOutputSlot(idx);
249 
250  OutputHandler& handler = GetOutputHandler(idx);
251  if (factoryId == ITensorHandleFactory::LegacyFactoryId)
252  {
253  handler.CreateTensorHandles(workloadFactory, IsMemoryManaged);
254  }
255  else
256  {
257  ITensorHandleFactory* handleFactory = registry.GetFactory(factoryId);
258  BOOST_ASSERT(handleFactory);
259  handler.CreateTensorHandles(*handleFactory, IsMemoryManaged);
260  }
261  }
262 }
263 
265 {
266  // Now free up the static data.
267  OperateOnConstantTensors([](std::unique_ptr<ScopedCpuTensorHandle>& handle)
268  {
269  handle.reset(nullptr);
270  });
271 }
272 
274 {
275  if (GetNumInputSlots() > 0) // Ignore the input layer.
276  {
278  }
280 }
281 
283 {
284  m_Priority = 0;
285  m_Visiting = false;
286 }
287 
289 {
290  constexpr LayerPriority inputPrio = std::numeric_limits<LayerPriority>::lowest();
291  constexpr LayerPriority outputPrio = std::numeric_limits<LayerPriority>::max();
292 
293  if (GetType() == LayerType::Input)
294  {
295  m_Priority = inputPrio;
296  }
297  else if (GetType() == LayerType::Output)
298  {
299  m_Priority = outputPrio;
300  }
301  else if (m_Priority == 0)
302  {
303  if (m_Visiting)
304  {
305  throw GraphValidationException("Graph has circular dependencies: cannot walk");
306  }
307 
308  auto maxPrio = [](const LayerPriority prio, const InputSlot& slot) -> LayerPriority
309  {
310  const OutputSlot *outputSlot = slot.GetConnectedOutputSlot();
311  if (outputSlot)
312  {
313  const Layer& input = outputSlot->GetOwningLayer();
314  return std::max(prio, input.GetPriority());
315  }
316  else
317  {
318  // unconnected input slot
319  return prio;
320  }
321  };
322 
323  m_Visiting = true;
324  LayerPriority parentPrio = std::accumulate(GetInputSlots().cbegin(), GetInputSlots().cend(), 0U, maxPrio);
325  m_Visiting = false;
326 
327  if (parentPrio >= outputPrio)
328  {
329  throw GraphValidationException("Graph has too many edges");
330  }
331 
332  m_Priority = parentPrio + 1U;
333  }
334 
335  return m_Priority;
336 }
337 
338 void Layer::VerifyLayerConnections(unsigned int expectedConnections, const CheckLocation& location) const
339 {
340  BOOST_ASSERT(GetNumInputSlots() == expectedConnections);
341 
342  for (unsigned int i=0; i<expectedConnections; ++i)
343  {
344  if (GetInputSlot(i).GetConnection() == nullptr)
345  {
347  boost::str(
348  boost::format(
349  "Input connection #%1% must be connected "
350  "for %2% layer %3% %4%")
351  % i
352  % GetLayerTypeAsCString(this->GetType())
353  % GetNameStr()
354  % location.AsString()));
355  }
356  if(! GetInputSlot(i).GetConnection()->IsTensorInfoSet())
357  {
359  boost::str(
360  boost::format(
361  "TensorInfo of Input connection #%1% must be set on connected OutputSlot for "
362  "%2% layer %3% %4%")
363  % i
364  % GetLayerTypeAsCString(this->GetType())
365  % GetNameStr()
366  % location.AsString()));
367  }
368  }
369 }
370 
371 std::vector<TensorShape> Layer::InferOutputShapes(const std::vector<TensorShape>& inputShapes) const
372 {
373  BOOST_ASSERT(GetNumInputSlots() != 0);
374  BOOST_ASSERT(GetNumOutputSlots() != 0);
375 
376  // By default we return what we got, meaning the output shape(s) are the same as the input(s).
377  // This only works if the number of inputs and outputs are the same. Since we are in the Layer
378  // base class, this means the implementation needs to be overridden in the specific layers for
379  // the other cases. So the missing implementation justifies the UnimplementedException.
380 
382  {
384  boost::str(
385  boost::format(
386  "Default implementation for InferOutputShapes can only be used for "
387  "layers with the same number of input and output slots. This doesn't "
388  "hold for %1% layer %2% (#inputs=%3% #outputs=%4%) %5%")
389  % GetLayerTypeAsCString(this->GetType())
390  % GetNameStr()
391  % GetNumInputSlots()
393  % CHECK_LOCATION().AsString()));
394  }
395  return inputShapes;
396 }
397 
399 {
400  std::string layerType = GetLayerTypeAsCString(m_Type);
401  std::string backendId = std::string(m_BackendId);
402  if(!(m_LayerName.compare("") == 0) && !m_LayerName.empty())
403  {
404  fn("LayerName",m_LayerName);
405  }
406  if(!(layerType.compare("") == 0) && !layerType.empty())
407  {
408  fn("LayerType",layerType);
409  }
410  if(!(backendId.compare("") == 0) && !backendId.empty())
411  {
412  fn("BackendID",backendId);
413  }
414 }
415 
416 } // namespace armnn
void DisconnectAll()
Definition: Layer.cpp:103
virtual void ReleaseConstantData()
Definition: Layer.cpp:264
bool ValidateTensorShape(const TensorShape &shape) const
Definition: Layer.cpp:73
void Insert(Layer &layer)
Definition: Layer.cpp:20
void SetEdgeStrategy(unsigned int connectionIndex, EdgeStrategy strategy)
Definition: Layer.cpp:177
DataLayout
Definition: Types.hpp:49
unsigned int GetNumInputSlots() const override
Returns the number of connectable input slots.
Definition: Layer.hpp:307
std::string AsString() const
Definition: Exceptions.hpp:29
std::vector< TensorShape > InferOutputShapes(const std::vector< TensorShape > &inputShapes) const override
Infer the shape of the output(s) based on the provided input shape(s)
Definition: Layer.cpp:371
LayerGuid GetOwningLayerGuid() const override
Definition: Layer.cpp:162
void OperateOnConstantTensors(Op op)
Definition: Layer.hpp:292
Layer & GetOwningLayer() const
Definition: Layer.hpp:115
int Connect(InputSlot &destination)
Definition: Layer.cpp:79
unsigned int LayerPriority
Definition: Layer.hpp:207
EdgeStrategy GetEdgeStrategyForConnection(unsigned int connectionIdx) const
Definition: Layer.cpp:182
Copyright (c) 2020 ARM Limited.
void IgnoreUnused(Ts &&...)
const std::vector< InputSlot > & GetInputSlots() const
Definition: Layer.hpp:231
const IOutputSlot * GetConnection() const override
Definition: Layer.hpp:199
unsigned int GetNumOutputSlots() const override
Returns the number of connectable output slots.
Definition: Layer.hpp:308
void Disconnect(InputSlot &slot)
Definition: Layer.cpp:87
void CreateTensorHandles(const IWorkloadFactory &factory, const bool IsMemoryManaged=true)
Creates tensor handles used by the intermediate tensors.
void VerifyLayerConnections(unsigned int expectedConnections, const CheckLocation &location) const
Definition: Layer.cpp:338
unsigned int GetNumConnections() const override
Definition: Layer.hpp:138
const InputSlot & GetInputSlot(unsigned int index) const override
Get a const input slot handle by slot index.
Definition: Layer.hpp:310
DataType
Definition: Types.hpp:32
void ResetPriority() const
Definition: Layer.cpp:282
char const * GetLayerTypeAsCString(LayerType type)
DataType GetDataType() const
Definition: Tensor.hpp:95
void Push(ITensorHandle *handle, const TensorInfo &info)
const std::string & GetNameStr() const
Definition: Layer.hpp:216
LayerPriority GetPriority() const
Definition: Layer.cpp:288
Layer(unsigned int numInputSlots, unsigned int numOutputSlots, LayerType type, const char *name)
Definition: Layer.cpp:213
const OutputSlot * GetConnectedOutputSlot() const
Definition: Layer.hpp:55
std::enable_if_t< std::is_unsigned< Source >::value &&std::is_unsigned< Dest >::value, Dest > numeric_cast(Source source)
Definition: NumericCast.hpp:33
Layer & GetOwningLayer() const
Definition: Layer.hpp:52
#define CHECK_LOCATION()
Definition: Exceptions.hpp:192
std::vector< OutputHandler > m_OutputHandlers
Definition: Layer.hpp:371
void SetTensorInfo(const TensorInfo &tensorInfo)
Sets the TensorInfo used by this output handler.
void SetTensorHandleFactory(const ITensorHandleFactory::FactoryId &id)
Definition: Layer.cpp:167
EmptyOptional is used to initialize the Optional class in case we want to have default value for an O...
Definition: Optional.hpp:32
bool operator==(const OutputSlot &other) const
Definition: Layer.cpp:138
void SetConnection(OutputSlot *source)
Links the slot to an output slot or breaks an existing link if passing nullptr.
Definition: Layer.hpp:59
const OutputHandler & GetOutputHandler(unsigned int i=0) const
Definition: Layer.hpp:221
ITensorHandleFactory * GetFactory(ITensorHandleFactory::FactoryId id) const
Find a TensorHandleFactory by Id Returns nullptr if not found.
void SetTensorInfo(const TensorInfo &tensorInfo) override
Definition: Layer.cpp:58
virtual void SerializeLayerParameters(ParameterStringifyFunction &fn) const
Helper to serialize the layer parameters to string.
Definition: Layer.cpp:398
DataType GetDataType() const
Definition: Layer.cpp:273
LayerType GetType() const
Definition: Layer.hpp:259
const OutputSlot & GetOutputSlot(unsigned int index=0) const override
Get the const output slot handle by slot index.
Definition: Layer.hpp:312
virtual const TensorInfo & GetTensorInfo() const =0
ITensorHandleFactory::FactoryId GetTensorHandleFactoryId() const
Definition: Layer.cpp:172
bool IsTensorInfoSet() const override
Definition: Layer.cpp:68
std::function< void(const std::string &name, const std::string &value)> ParameterStringifyFunction
virtual void CreateTensorHandles(const TensorHandleFactoryRegistry &registry, const IWorkloadFactory &factory, const bool IsMemoryManaged=true)
Definition: Layer.cpp:240
const TensorInfo & GetTensorInfo() const override
Definition: Layer.cpp:63
static const FactoryId LegacyFactoryId
void MoveAllConnections(OutputSlot &destination)
Moves all connections to another OutputSlot.
Definition: Layer.cpp:112
const InputSlot * GetConnection(unsigned int index) const override
Definition: Layer.cpp:46
LayerGuid GetGuid() const final
Returns the unique id of the layer.
Definition: Layer.hpp:316
unsigned int CalculateIndexOnOwner() const override
Definition: Layer.cpp:125