ArmNN
 20.08
Layer.cpp
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 #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  ARMNN_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  ARMNN_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  if (GetOwningLayer().GetShapeInferenceMethod() == ShapeInferenceMethod::InferAndValidate)
71  {
73  }
74  return GetOutputHandler().IsTensorInfoSet();
75 }
76 
78 {
79  ARMNN_ASSERT_MSG(IsTensorInfoSet(), "TensorInfo must be set in order to validate the shape.");
80  return shape == m_OutputHandler.GetTensorInfo().GetShape();
81 }
82 
83 int OutputSlot::Connect(InputSlot& destination)
84 {
85  destination.SetConnection(this);
86  m_Connections.push_back(&destination);
87  m_EdgeStrategies.push_back(EdgeStrategy::Undefined);
88  return boost::numeric_cast<int>(m_Connections.size() - 1);
89 }
90 
92 {
93  slot.SetConnection(nullptr);
94  auto it = std::find(m_Connections.begin(), m_Connections.end(), &slot);
95 
96  if (it == m_Connections.end())
97  {
98  return;
99  }
100 
101  auto idx = std::distance(m_Connections.begin(), it);
102  m_Connections.erase(std::remove(m_Connections.begin(), m_Connections.end(), &slot), m_Connections.end());
103 
104  m_EdgeStrategies.erase(m_EdgeStrategies.begin() + idx);
105 }
106 
108 {
109  while (GetNumConnections() > 0)
110  {
111  InputSlot& connection = *GetConnection(0);
112  Disconnect(connection);
113  }
114 }
115 
117 {
118  while (GetNumConnections() > 0)
119  {
120  ARMNN_ASSERT_MSG(m_EdgeStrategies[0] == EdgeStrategy::Undefined,
121  "Cannot move connections once memory strategies have be established.");
122 
123  InputSlot& connection = *GetConnection(0);
124  Disconnect(connection);
125  destination.Connect(connection);
126  destination.GetOutputHandler().SetTensorInfo(GetOutputHandler().GetTensorInfo());
127  }
128 }
129 
131 {
132  for (unsigned int i = 0; i < GetOwningLayer().GetNumOutputSlots(); i++)
133  {
134  if (GetOwningLayer().GetOutputSlot(i) == (*this))
135  {
136  return i;
137  }
138  }
139  ARMNN_ASSERT_MSG(false, "Did not find slot on owner.");
140  return 0; // Error
141 }
142 
143 bool OutputSlot::operator==(const OutputSlot& other) const
144 {
145  bool isSame = other.GetNumConnections() == GetNumConnections();
146  if (!isSame)
147  {
148  return false;
149  }
150 
151  for (unsigned int i = 0; i < GetNumConnections(); i++)
152  {
153  isSame &= other.GetConnection(i) == GetConnection(i);
154  }
155  return isSame;
156 }
157 
158 void OutputSlot::ValidateConnectionIndex(unsigned int index) const
159 {
160  if (boost::numeric_cast<std::size_t>(index) >= m_Connections.size())
161  {
163  boost::str(boost::format("GetConnection: Invalid index %1% provided") % index));
164  }
165 }
166 
168 {
169  return GetOwningLayer().GetGuid();
170 }
171 
173 {
174  m_TensorHandleFactoryId = id;
175 }
176 
178 {
179  return m_TensorHandleFactoryId;
180 }
181 
182 void OutputSlot::SetEdgeStrategy(unsigned int connectionIndex, EdgeStrategy strategy)
183 {
184  m_EdgeStrategies[connectionIndex] = strategy;
185 }
186 
188 {
189  return m_EdgeStrategies[connectionIdx];
190 }
191 
192 Layer::Layer(unsigned int numInputSlots,
193  unsigned int numOutputSlots,
194  LayerType type,
195  DataLayout layout,
196  const char* name)
197 : m_OutputHandlers(numOutputSlots)
198 , m_ShapeInferenceMethod(ShapeInferenceMethod::ValidateOnly)
199 , m_LayerName(name ? name : "")
200 , m_Type(type)
201 , m_BackendId()
202 , m_BackendHint(EmptyOptional())
203 , m_Guid(profiling::ProfilingService::GetNextGuid())
204 {
205  IgnoreUnused(layout);
206  m_InputSlots.reserve(numInputSlots);
207  for (unsigned int i = 0; i < numInputSlots; ++i)
208  {
209  m_InputSlots.emplace_back(*this, i);
210  }
211 
212  m_OutputSlots.reserve(numOutputSlots);
213  for (unsigned int i = 0; i < numOutputSlots; ++i)
214  {
215  m_OutputSlots.emplace_back(*this, m_OutputHandlers[i]);
216  }
217 }
218 
219 Layer::Layer(unsigned int numInputSlots,
220  unsigned int numOutputSlots,
221  LayerType type,
222  const char* name)
223 : Layer(numInputSlots, numOutputSlots, type, DataLayout::NCHW, name)
224 {
225 }
226 
227 void Layer::CollectWorkloadInputs(WorkloadDataCollector& dataCollector) const
228 {
229  for (auto&& inputSlot : GetInputSlots())
230  {
231  // The graph must be well-formed at this point.
232  ARMNN_ASSERT(inputSlot.GetConnection());
233  const OutputHandler& outputHandler = inputSlot.GetConnectedOutputSlot()->GetOutputHandler();
234  dataCollector.Push(outputHandler.GetData(), outputHandler.GetTensorInfo());
235  }
236 }
237 
238 void Layer::CollectWorkloadOutputs(WorkloadDataCollector& dataCollector) const
239 {
240  for (auto&& outputHandler : m_OutputHandlers)
241  {
242  outputHandler.CollectWorkloadOutputs(dataCollector);
243  }
244 }
245 
247  const IWorkloadFactory& workloadFactory,
248  const bool IsMemoryManaged)
249 {
250  for (unsigned int idx=0; idx < GetNumOutputSlots(); idx++)
251  {
252 
253  OutputSlot& slot = GetOutputSlot(idx);
255 
256  OutputHandler& handler = GetOutputHandler(idx);
257  if (factoryId == ITensorHandleFactory::LegacyFactoryId)
258  {
259  handler.CreateTensorHandles(workloadFactory, IsMemoryManaged);
260  }
261  else
262  {
263  ITensorHandleFactory* handleFactory = registry.GetFactory(factoryId);
264  ARMNN_ASSERT(handleFactory);
265  handler.CreateTensorHandles(*handleFactory, IsMemoryManaged);
266  }
267  }
268 }
269 
271 {
272  // Now free up the static data.
273  OperateOnConstantTensors([](std::unique_ptr<ScopedCpuTensorHandle>& handle)
274  {
275  handle.reset(nullptr);
276  });
277 }
278 
280 {
281  if (GetNumInputSlots() > 0) // Ignore the input layer.
282  {
284  }
286 }
287 
289 {
290  m_Priority = 0;
291  m_Visiting = false;
292 }
293 
295 {
296  constexpr LayerPriority inputPrio = std::numeric_limits<LayerPriority>::lowest();
297  constexpr LayerPriority outputPrio = std::numeric_limits<LayerPriority>::max();
298 
299  if (GetType() == LayerType::Input)
300  {
301  m_Priority = inputPrio;
302  }
303  else if (GetType() == LayerType::Output)
304  {
305  m_Priority = outputPrio;
306  }
307  else if (m_Priority == 0)
308  {
309  if (m_Visiting)
310  {
311  throw GraphValidationException("Graph has circular dependencies: cannot walk");
312  }
313 
314  auto maxPrio = [](const LayerPriority prio, const InputSlot& slot) -> LayerPriority
315  {
316  const OutputSlot *outputSlot = slot.GetConnectedOutputSlot();
317  if (outputSlot)
318  {
319  const Layer& input = outputSlot->GetOwningLayer();
320  return std::max(prio, input.GetPriority());
321  }
322  else
323  {
324  // unconnected input slot
325  return prio;
326  }
327  };
328 
329  m_Visiting = true;
330  LayerPriority parentPrio = std::accumulate(GetInputSlots().cbegin(), GetInputSlots().cend(), 0U, maxPrio);
331  m_Visiting = false;
332 
333  if (parentPrio >= outputPrio)
334  {
335  throw GraphValidationException("Graph has too many edges");
336  }
337 
338  m_Priority = parentPrio + 1U;
339  }
340 
341  return m_Priority;
342 }
343 
344 void Layer::VerifyLayerConnections(unsigned int expectedConnections, const CheckLocation& location) const
345 {
346  ARMNN_ASSERT(GetNumInputSlots() == expectedConnections);
347 
348  for (unsigned int i=0; i<expectedConnections; ++i)
349  {
350  if (GetInputSlot(i).GetConnection() == nullptr)
351  {
353  boost::str(
354  boost::format(
355  "Input connection #%1% must be connected "
356  "for %2% layer %3% %4%")
357  % i
358  % GetLayerTypeAsCString(this->GetType())
359  % GetNameStr()
360  % location.AsString()));
361  }
362  }
363 }
364 
365 std::vector<TensorShape> Layer::InferOutputShapes(const std::vector<TensorShape>& inputShapes) const
366 {
369 
370  // By default we return what we got, meaning the output shape(s) are the same as the input(s).
371  // This only works if the number of inputs and outputs are the same. Since we are in the Layer
372  // base class, this means the implementation needs to be overridden in the specific layers for
373  // the other cases. So the missing implementation justifies the UnimplementedException.
374 
376  {
378  boost::str(
379  boost::format(
380  "Default implementation for InferOutputShapes can only be used for "
381  "layers with the same number of input and output slots. This doesn't "
382  "hold for %1% layer %2% (#inputs=%3% #outputs=%4%) %5%")
383  % GetLayerTypeAsCString(this->GetType())
384  % GetNameStr()
385  % GetNumInputSlots()
387  % CHECK_LOCATION().AsString()));
388  }
389  return inputShapes;
390 }
391 
392 void Layer::ValidateAndCopyShape(const TensorShape& outputShape,
393  const TensorShape& inferredShape,
394  const ShapeInferenceMethod shapeInferenceMethod,
395  const std::string& layerName,
396  const unsigned int outputSlotIndex)
397 {
398  if (shapeInferenceMethod == ShapeInferenceMethod::ValidateOnly)
399  {
400  ConditionalThrowIfNotEqual<LayerValidationException>(
401  layerName + ": TensorShape set on OutputSlot[0] does not match the inferred shape.",
402  outputShape,
403  inferredShape);
404  return;
405  }
406 
407  if (outputShape.GetDimensionality() == Dimensionality::Specified)
408  {
409  for (unsigned int i = 0; i < outputShape.GetNumDimensions(); ++i)
410  {
411  if (outputShape.GetDimensionSpecificity(i) && outputShape[i] != inferredShape[i])
412  {
413  std::stringstream ss;
414  ss << layerName << ": TensorShape set on OutputSlot[" << outputSlotIndex <<
415  "] does not match the inferred shape at dimension index [";
416  ss << i << "] " << outputShape << " != " << inferredShape;
417  throw LayerValidationException(ss.str());
418  }
419  }
420  }
421 
422  TensorInfo info = GetOutputSlot(outputSlotIndex).GetTensorInfo();
423 
424  armnn::TensorInfo inferredTensorInfo(inferredShape,
425  info.GetDataType(),
426  info.GetQuantizationScale(),
427  info.GetQuantizationOffset());
428 
429  GetOutputSlot(outputSlotIndex).SetTensorInfo(inferredTensorInfo);
430 }
431 
432 void Layer::VerifyShapeInferenceType(const TensorShape& outputShape, ShapeInferenceMethod shapeInferenceMethod)
433 {
434  if (shapeInferenceMethod == ShapeInferenceMethod::ValidateOnly)
435  {
436  ConditionalThrow<LayerValidationException>(
438  "Dimensionality can not be NotSpecified while using ShapeInferenceMethod::ValidateOnly");
439 
440  ConditionalThrow<LayerValidationException>(
441  outputShape.AreAllDimensionsSpecified(),
442  "Unspecified dimension while using ShapeInferenceMethod::ValidateOnly");
443  }
444 }
445 
447 {
448  std::string layerType = GetLayerTypeAsCString(m_Type);
449  std::string backendId = std::string(m_BackendId);
450  if(!(m_LayerName.compare("") == 0) && !m_LayerName.empty())
451  {
452  fn("LayerName",m_LayerName);
453  }
454  if(!(layerType.compare("") == 0) && !layerType.empty())
455  {
456  fn("LayerType",layerType);
457  }
458  if(!(backendId.compare("") == 0) && !backendId.empty())
459  {
460  fn("BackendID",backendId);
461  }
462 }
463 
464 } // namespace armnn
void DisconnectAll()
Definition: Layer.cpp:107
virtual void ReleaseConstantData()
Definition: Layer.cpp:270
bool ValidateTensorShape(const TensorShape &shape) const
Definition: Layer.cpp:77
void Insert(Layer &layer)
Definition: Layer.cpp:20
void SetEdgeStrategy(unsigned int connectionIndex, EdgeStrategy strategy)
Definition: Layer.cpp:182
DataLayout
Definition: Types.hpp:49
unsigned int GetNumInputSlots() const override
Returns the number of connectable input slots.
Definition: Layer.hpp:309
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:365
bool AreAllDimensionsSpecified() const
Checks if there is at least one dimension not specified.
Definition: Tensor.cpp:242
LayerGuid GetOwningLayerGuid() const override
Definition: Layer.cpp:167
void OperateOnConstantTensors(Op op)
Definition: Layer.hpp:294
Dimensionality GetDimensionality() const
Function that returns the tensor type.
Definition: Tensor.hpp:92
Layer & GetOwningLayer() const
Definition: Layer.hpp:115
int Connect(InputSlot &destination)
Definition: Layer.cpp:83
unsigned int LayerPriority
Definition: Layer.hpp:207
EdgeStrategy GetEdgeStrategyForConnection(unsigned int connectionIdx) const
Definition: Layer.cpp:187
void VerifyShapeInferenceType(const TensorShape &outputShape, ShapeInferenceMethod shapeInferenceMethod)
Definition: Layer.cpp:432
Copyright (c) 2020 ARM Limited.
void IgnoreUnused(Ts &&...)
const std::vector< InputSlot > & GetInputSlots() const
Definition: Layer.hpp:233
const IOutputSlot * GetConnection() const override
Definition: Layer.hpp:199
unsigned int GetNumOutputSlots() const override
Returns the number of connectable output slots.
Definition: Layer.hpp:310
bool GetDimensionSpecificity(unsigned int i) const
Gets information about if the dimension size has been specified or not.
Definition: Tensor.cpp:212
void ValidateAndCopyShape(const TensorShape &outputShape, const TensorShape &inferredShape, const ShapeInferenceMethod shapeInferenceMethod, const std::string &layerName, const unsigned int outputSlotIndex=0)
Definition: Layer.cpp:392
void Disconnect(InputSlot &slot)
Definition: Layer.cpp:91
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:344
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:312
DataType
Definition: Types.hpp:32
void ResetPriority() const
Definition: Layer.cpp:288
#define ARMNN_ASSERT_MSG(COND, MSG)
Definition: Assert.hpp:15
char const * GetLayerTypeAsCString(LayerType type)
DataType GetDataType() const
Definition: Tensor.hpp:194
void Push(ITensorHandle *handle, const TensorInfo &info)
Validate all output shapes.
const std::string & GetNameStr() const
Definition: Layer.hpp:216
LayerPriority GetPriority() const
Definition: Layer.cpp:294
Layer(unsigned int numInputSlots, unsigned int numOutputSlots, LayerType type, const char *name)
Definition: Layer.cpp:219
#define ARMNN_ASSERT(COND)
Definition: Assert.hpp:14
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
virtual void ValidateTensorShapesFromInputs()=0
Layer & GetOwningLayer() const
Definition: Layer.hpp:52
#define CHECK_LOCATION()
Definition: Exceptions.hpp:197
std::vector< OutputHandler > m_OutputHandlers
Definition: Layer.hpp:386
void SetTensorInfo(const TensorInfo &tensorInfo)
Sets the TensorInfo used by this output handler.
void SetTensorHandleFactory(const ITensorHandleFactory::FactoryId &id)
Definition: Layer.cpp:172
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:143
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
unsigned int GetNumDimensions() const
Function that returns the tensor rank.
Definition: Tensor.cpp:175
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:446
DataType GetDataType() const
Definition: Layer.cpp:279
LayerType GetType() const
Definition: Layer.hpp:261
const OutputSlot & GetOutputSlot(unsigned int index=0) const override
Get the const output slot handle by slot index.
Definition: Layer.hpp:314
Infer missing output shapes and validate all output shapes.
virtual const TensorInfo & GetTensorInfo() const =0
const OutputHandler & GetOutputHandler() const
Definition: Layer.hpp:119
ITensorHandleFactory::FactoryId GetTensorHandleFactoryId() const
Definition: Layer.cpp:177
bool IsTensorInfoSet() const override
Definition: Layer.cpp:68
std::function< void(const std::string &name, const std::string &value)> ParameterStringifyFunction
const TensorInfo & GetTensorInfo(const ITensorHandle *tensorHandle)
float32 helpers
virtual void CreateTensorHandles(const TensorHandleFactoryRegistry &registry, const IWorkloadFactory &factory, const bool IsMemoryManaged=true)
Definition: Layer.cpp:246
const TensorInfo & GetTensorInfo() const override
Definition: Layer.cpp:63
ShapeInferenceMethod
The ShapeInferenceMethod modify how the output shapes are treated.
Definition: Types.hpp:161
static const FactoryId LegacyFactoryId
void MoveAllConnections(OutputSlot &destination)
Moves all connections to another OutputSlot.
Definition: Layer.cpp:116
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:318
unsigned int CalculateIndexOnOwner() const override
Definition: Layer.cpp:130