ArmNN  NotReleased
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_Guid(profiling::ProfilingService::Instance().NextGuid())
197 {
198  boost::ignore_unused(layout);
199  m_InputSlots.reserve(numInputSlots);
200  for (unsigned int i = 0; i < numInputSlots; ++i)
201  {
202  m_InputSlots.emplace_back(*this, i);
203  }
204 
205  m_OutputSlots.reserve(numOutputSlots);
206  for (unsigned int i = 0; i < numOutputSlots; ++i)
207  {
208  m_OutputSlots.emplace_back(*this, m_OutputHandlers[i]);
209  }
210 }
211 
212 Layer::Layer(unsigned int numInputSlots,
213  unsigned int numOutputSlots,
214  LayerType type,
215  const char* name)
216 : Layer(numInputSlots, numOutputSlots, type, DataLayout::NCHW, name)
217 {
218 }
219 
220 void Layer::CollectWorkloadInputs(WorkloadDataCollector& dataCollector) const
221 {
222  for (auto&& inputSlot : GetInputSlots())
223  {
224  // The graph must be well-formed at this point.
225  BOOST_ASSERT(inputSlot.GetConnection());
226  const OutputHandler& outputHandler = inputSlot.GetConnectedOutputSlot()->GetOutputHandler();
227  dataCollector.Push(outputHandler.GetData(), outputHandler.GetTensorInfo());
228  }
229 }
230 
231 void Layer::CollectWorkloadOutputs(WorkloadDataCollector& dataCollector) const
232 {
233  for (auto&& outputHandler : m_OutputHandlers)
234  {
235  outputHandler.CollectWorkloadOutputs(dataCollector);
236  }
237 }
238 
240  const IWorkloadFactory& workloadFactory,
241  const bool IsMemoryManaged)
242 {
243  for (unsigned int idx=0; idx < GetNumOutputSlots(); idx++)
244  {
245 
246  OutputSlot& slot = GetOutputSlot(idx);
248 
249  OutputHandler& handler = GetOutputHandler(idx);
250  if (factoryId == ITensorHandleFactory::LegacyFactoryId)
251  {
252  handler.CreateTensorHandles(workloadFactory, IsMemoryManaged);
253  }
254  else
255  {
256  ITensorHandleFactory* handleFactory = registry.GetFactory(factoryId);
257  BOOST_ASSERT(handleFactory);
258  handler.CreateTensorHandles(*handleFactory, IsMemoryManaged);
259  }
260  }
261 }
262 
264 {
265  // Now free up the static data.
266  OperateOnConstantTensors([](std::unique_ptr<ScopedCpuTensorHandle>& handle)
267  {
268  handle.reset(nullptr);
269  });
270 }
271 
273 {
274  if (GetNumInputSlots() > 0) // Ignore the input layer.
275  {
277  }
279 }
280 
282 {
283  m_Priority = 0;
284  m_Visiting = false;
285 }
286 
288 {
289  constexpr LayerPriority inputPrio = std::numeric_limits<LayerPriority>::lowest();
290  constexpr LayerPriority outputPrio = std::numeric_limits<LayerPriority>::max();
291 
292  if (GetType() == LayerType::Input)
293  {
294  m_Priority = inputPrio;
295  }
296  else if (GetType() == LayerType::Output)
297  {
298  m_Priority = outputPrio;
299  }
300  else if (m_Priority == 0)
301  {
302  if (m_Visiting)
303  {
304  throw GraphValidationException("Graph has circular dependencies: cannot walk");
305  }
306 
307  auto maxPrio = [](const LayerPriority prio, const InputSlot& slot) -> LayerPriority
308  {
309  const OutputSlot *outputSlot = slot.GetConnectedOutputSlot();
310  if (outputSlot)
311  {
312  const Layer& input = outputSlot->GetOwningLayer();
313  return std::max(prio, input.GetPriority());
314  }
315  else
316  {
317  // unconnected input slot
318  return prio;
319  }
320  };
321 
322  m_Visiting = true;
323  LayerPriority parentPrio = std::accumulate(GetInputSlots().cbegin(), GetInputSlots().cend(), 0U, maxPrio);
324  m_Visiting = false;
325 
326  if (parentPrio >= outputPrio)
327  {
328  throw GraphValidationException("Graph has too many edges");
329  }
330 
331  m_Priority = parentPrio + 1U;
332  }
333 
334  return m_Priority;
335 }
336 
337 void Layer::VerifyLayerConnections(unsigned int expectedConnections, const CheckLocation& location) const
338 {
339  BOOST_ASSERT(GetNumInputSlots() == expectedConnections);
340 
341  for (unsigned int i=0; i<expectedConnections; ++i)
342  {
343  if (GetInputSlot(i).GetConnection() == nullptr)
344  {
346  boost::str(
347  boost::format(
348  "Input connection #%1% must be connected "
349  "for %2% layer %3% %4%")
350  % i
351  % GetLayerTypeAsCString(this->GetType())
352  % GetNameStr()
353  % location.AsString()));
354  }
355  if(! GetInputSlot(i).GetConnection()->IsTensorInfoSet())
356  {
358  boost::str(
359  boost::format(
360  "TensorInfo of Input connection #%1% must be set on connected OutputSlot for "
361  "%2% layer %3% %4%")
362  % i
363  % GetLayerTypeAsCString(this->GetType())
364  % GetNameStr()
365  % location.AsString()));
366  }
367  }
368 }
369 
370 std::vector<TensorShape> Layer::InferOutputShapes(const std::vector<TensorShape>& inputShapes) const
371 {
372  BOOST_ASSERT(GetNumInputSlots() != 0);
373  BOOST_ASSERT(GetNumOutputSlots() != 0);
374 
375  // By default we return what we got, meaning the output shape(s) are the same as the input(s).
376  // This only works if the number of inputs and outputs are the same. Since we are in the Layer
377  // base class, this means the implementation needs to be overridden in the specific layers for
378  // the other cases. So the missing implementation justifies the UnimplementedException.
379 
381  {
383  boost::str(
384  boost::format(
385  "Default implementation for InferOutputShapes can only be used for "
386  "layers with the same number of input and output slots. This doesn't "
387  "hold for %1% layer %2% (#inputs=%3% #outputs=%4%) %5%")
388  % GetLayerTypeAsCString(this->GetType())
389  % GetNameStr()
390  % GetNumInputSlots()
392  % CHECK_LOCATION().AsString()));
393  }
394  return inputShapes;
395 }
396 
398 {
399  std::string layerType = GetLayerTypeAsCString(m_Type);
400  std::string backendId = std::string(m_BackendId);
401  if(!(m_LayerName.compare("") == 0) && !m_LayerName.empty())
402  {
403  fn("LayerName",m_LayerName);
404  }
405  if(!(layerType.compare("") == 0) && !layerType.empty())
406  {
407  fn("LayerType",layerType);
408  }
409  if(!(backendId.compare("") == 0) && !backendId.empty())
410  {
411  fn("BackendID",backendId);
412  }
413 }
414 
415 } // namespace armnn
const OutputHandler & GetOutputHandler(unsigned int i=0) const
Definition: Layer.hpp:221
Layer(unsigned int numInputSlots, unsigned int numOutputSlots, LayerType type, const char *name)
Definition: Layer.cpp:212
unsigned int GetNumOutputSlots() const override
Definition: Layer.hpp:308
LayerGuid GetGuid() const final
Definition: Layer.hpp:316
const OutputSlot * GetConnectedOutputSlot() const
Definition: Layer.hpp:55
LayerType GetType() const
Definition: Layer.hpp:259
virtual void CreateTensorHandles(const TensorHandleFactoryRegistry &registry, const IWorkloadFactory &factory, const bool IsMemoryManaged=true)
Definition: Layer.cpp:239
std::vector< TensorShape > InferOutputShapes(const std::vector< TensorShape > &inputShapes) const override
Definition: Layer.cpp:370
virtual const TensorInfo & GetTensorInfo() const =0
virtual void ReleaseConstantData()
Definition: Layer.cpp:263
char const * GetLayerTypeAsCString(LayerType type)
void SetEdgeStrategy(unsigned int connectionIndex, EdgeStrategy strategy)
Definition: Layer.cpp:177
void Push(ITensorHandle *handle, const TensorInfo &info)
unsigned int LayerPriority
Definition: Layer.hpp:207
void ResetPriority() const
Definition: Layer.cpp:281
ITensorHandleFactory::FactoryId GetTensorHandleFactoryId() const
Definition: Layer.cpp:172
int Connect(InputSlot &destination)
Definition: Layer.cpp:79
const std::string & GetNameStr() const
Definition: Layer.hpp:216
LayerPriority GetPriority() const
Definition: Layer.cpp:287
#define CHECK_LOCATION()
Definition: Exceptions.hpp:169
EdgeStrategy GetEdgeStrategyForConnection(unsigned int connectionIdx) const
Definition: Layer.cpp:182
static const FactoryId LegacyFactoryId
const std::vector< InputSlot > & GetInputSlots() const
Definition: Layer.hpp:231
DataType GetDataType() const
Definition: Layer.cpp:272
ITensorHandleFactory * GetFactory(ITensorHandleFactory::FactoryId id) const
unsigned int GetNumConnections() const override
Definition: Layer.hpp:138
const IOutputSlot * GetConnection() const override
Definition: Layer.hpp:199
unsigned int CalculateIndexOnOwner() const override
Definition: Layer.cpp:125
void SetTensorInfo(const TensorInfo &tensorInfo) override
Definition: Layer.cpp:58
const InputSlot * GetConnection(unsigned int index) const override
Definition: Layer.cpp:46
void VerifyLayerConnections(unsigned int expectedConnections, const CheckLocation &location) const
Definition: Layer.cpp:337
void Disconnect(InputSlot &slot)
Definition: Layer.cpp:87
bool ValidateTensorShape(const TensorShape &shape) const
Definition: Layer.cpp:73
void MoveAllConnections(OutputSlot &destination)
Moves all connections to another OutputSlot.
Definition: Layer.cpp:112
bool operator==(const OutputSlot &other) const
Definition: Layer.cpp:138
void CreateTensorHandles(const IWorkloadFactory &factory, const bool IsMemoryManaged=true)
Creates tensor handles used by the intermediate tensors. Does not allocate memory.
void SetConnection(OutputSlot *source)
Links the slot to an output slot or breaks an existing link if passing nullptr.
Definition: Layer.hpp:59
std::vector< OutputHandler > m_OutputHandlers
Definition: Layer.hpp:364
bool IsTensorInfoSet() const override
Definition: Layer.cpp:68
DataLayout
Definition: Types.hpp:48
DataType
Definition: Types.hpp:32
void SetTensorInfo(const TensorInfo &tensorInfo)
Sets the TensorInfo used by this output handler.
std::function< void(const std::string &name, const std::string &value)> ParameterStringifyFunction
DataType GetDataType() const
Definition: Tensor.hpp:95
LayerGuid GetOwningLayerGuid() const override
Definition: Layer.cpp:162
void SetTensorHandleFactory(const ITensorHandleFactory::FactoryId &id)
Definition: Layer.cpp:167
void OperateOnConstantTensors(Op op)
Definition: Layer.hpp:292
unsigned int GetNumInputSlots() const override
Definition: Layer.hpp:307
virtual void SerializeLayerParameters(ParameterStringifyFunction &fn) const
Definition: Layer.cpp:397
void Insert(Layer &layer)
Definition: Layer.cpp:20
const TensorInfo & GetTensorInfo() const override
Definition: Layer.cpp:63
Layer & GetOwningLayer() const
Definition: Layer.hpp:115
void DisconnectAll()
Definition: Layer.cpp:103
const OutputSlot & GetOutputSlot(unsigned int index=0) const override
Definition: Layer.hpp:312
std::string AsString() const
Definition: Exceptions.hpp:29
Layer & GetOwningLayer() const
Definition: Layer.hpp:52
const InputSlot & GetInputSlot(unsigned int index) const override
Definition: Layer.hpp:310