ArmNN
 22.11
LoadedNetwork.cpp
Go to the documentation of this file.
1 //
2 // Copyright © 2022 Arm Ltd and Contributors. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5 
6 #include "LoadedNetwork.hpp"
7 #include "Layer.hpp"
8 #include "Graph.hpp"
9 #include "Profiling.hpp"
10 #include "HeapProfiling.hpp"
11 #include "WorkingMemHandle.hpp"
12 #include "ExecutionData.hpp"
13 
14 #include <armnn/BackendHelper.hpp>
16 #include <armnn/Logging.hpp>
17 
22 
24 
25 #include <armnn/utility/Assert.hpp>
26 
28 
29 #include <common/include/Processes.hpp>
30 
31 #include <fmt/format.h>
32 
33 namespace armnn
34 {
35 
36 using namespace std;
37 using namespace arm::pipe;
38 
39 namespace
40 {
41 
42 template <typename ExceptionType>
43 std::string ToErrorMessage(const char * prefix, const ExceptionType & error)
44 {
45  std::stringstream ss;
46  ss << prefix << " " << error.what();
47  return ss.str();
48 }
49 
50 void AddLayerStructure(std::unique_ptr<TimelineUtilityMethods>& timelineUtils,
51  const Layer& layer,
52  ProfilingGuid networkGuid)
53 {
54  // Add layer to the post-optimisation network structure
55  std::string layerName = layer.GetNameStr().empty() ? "<Unnamed>" : layer.GetNameStr();
56  timelineUtils->CreateNamedTypedChildEntity(layer.GetGuid(),
57  networkGuid,
58  layerName,
59  LabelsAndEventClasses::LAYER_GUID);
60  for (auto&& input : layer.GetInputSlots())
61  {
62  const IOutputSlot* source = input.GetConnectedOutputSlot();
63  ARMNN_ASSERT(source != NULL);
64  timelineUtils->CreateConnectionRelationship(ProfilingRelationshipType::RetentionLink,
65  source->GetOwningLayerGuid(),
66  layer.GetGuid());
67  }
68 }
69 
70 void AddWorkloadStructure(std::unique_ptr<TimelineUtilityMethods>& timelineUtils,
71  std::unique_ptr<IWorkload>& workload,
72  const Layer& layer)
73 {
74  // Add workload to the post-optimisation network structure
75  timelineUtils->CreateTypedEntity(workload->GetGuid(), LabelsAndEventClasses::WORKLOAD_GUID);
76  timelineUtils->MarkEntityWithLabel(workload->GetGuid(),
77  layer.GetBackendId().Get(),
78  LabelsAndEventClasses::BACKENDID_GUID);
79 
80  // Link the workload to the layer
81  timelineUtils->CreateRelationship(ProfilingRelationshipType::RetentionLink,
82  layer.GetGuid(),
83  workload->GetGuid(),
84  LabelsAndEventClasses::CHILD_GUID);
85 }
86 
87 } // anonymous
88 
89 /**
90  * This function performs a sanity check to ensure that the combination of input and output memory source matches the
91  * values for importEnabled and exportEnabled that were specified during optimization. During optimization the tensor
92  * handle factories are chosen based on whether import and export are enabled. If the user then specifies something
93  * incompatible here it can lead to problems.
94  *
95  * @param optimizedOptions
96  * @param networkProperties
97  */
98 void ValidateSourcesMatchOptimizedNetwork(std::vector<BackendOptions> optimizedOptions,
99  const INetworkProperties& networkProperties)
100 {
101  // Find the "Global" backend options. During the optimize phase the values of importEnabled and exportEnabled are
102  // added as backend options.
103  const vector<BackendOptions>::iterator& backendItr =
104  find_if(optimizedOptions.begin(), optimizedOptions.end(), [](const BackendOptions& backend) {
105  if (backend.GetBackendId().Get() == "Global")
106  {
107  return true;
108  }
109  else
110  {
111  return false;
112  }
113  });
114  bool importEnabled = false;
115  bool exportEnabled = false;
116  if (backendItr != optimizedOptions.end())
117  {
118  // Find the importEnabled and exportEnabled values.
119  for (size_t i = 0; i < backendItr->GetOptionCount(); i++)
120  {
121  const BackendOptions::BackendOption& option = backendItr->GetOption(i);
122  if (option.GetName() == "ImportEnabled")
123  {
124  importEnabled = option.GetValue().AsBool();
125  }
126  if (option.GetName() == "ExportEnabled")
127  {
128  exportEnabled = option.GetValue().AsBool();
129  }
130  }
131  }
132 
133  // Now that we have values for import and export compare them to the MemorySource variables.
134  // Any value of MemorySource that's not "Undefined" implies that we need to do an import of some kind.
135  if ((networkProperties.m_InputSource == MemorySource::Undefined && importEnabled) ||
136  (networkProperties.m_InputSource != MemorySource::Undefined && !importEnabled))
137  {
138  auto message = fmt::format("The input memory source specified, '{0}',", networkProperties.m_InputSource);
139  if (!importEnabled)
140  {
141  message.append(" requires that memory import be enabled. However, "
142  "it was disabled when this network was optimized.");
143  }
144  else
145  {
146  message.append(" requires that memory import be disabled. However, "
147  "it was enabled when this network was optimized.");
148  }
149  throw InvalidArgumentException(message);
150  }
151 
152  if ((networkProperties.m_OutputSource == MemorySource::Undefined && exportEnabled) ||
153  (networkProperties.m_OutputSource != MemorySource::Undefined && !exportEnabled))
154  {
155  auto message = fmt::format("The output memory source specified, '{0}',", networkProperties.m_OutputSource);
156  if (!exportEnabled)
157  {
158  message.append(" requires that memory export be enabled. However, "
159  "it was disabled when this network was optimized.");
160  }
161  else
162  {
163  message.append(" requires that memory export be disabled. However, "
164  "it was enabled when this network was optimized.");
165  }
166  throw InvalidArgumentException(message);
167  }
168 } // anonymous
169 
170 std::unique_ptr<LoadedNetwork> LoadedNetwork::MakeLoadedNetwork(std::unique_ptr<IOptimizedNetwork> net,
171  std::string& errorMessage,
172  const INetworkProperties& networkProperties,
173  arm::pipe::IProfilingService* profilingService)
174 {
175  std::unique_ptr<LoadedNetwork> loadedNetwork;
176 
177  auto Fail = [&](const std::exception& error) -> std::unique_ptr<LoadedNetwork>
178  {
179  errorMessage = ToErrorMessage("An error occurred when preparing the network workloads: ", error);
180  ARMNN_LOG(error) << errorMessage;
181 
182  return std::unique_ptr<LoadedNetwork>();
183  };
184 
185  try
186  {
187  loadedNetwork.reset(new LoadedNetwork(std::move(net), networkProperties, profilingService));
188  }
189  catch (const armnn::RuntimeException& error)
190  {
191  return Fail(error);
192  }
193  catch (const armnn::Exception& error)
194  {
195  return Fail(error);
196  }
197  catch (const std::runtime_error& error)
198  {
199  return Fail(error);
200  }
201 
202  return loadedNetwork;
203 }
204 
205 LoadedNetwork::LoadedNetwork(std::unique_ptr<IOptimizedNetwork> net,
206  const INetworkProperties& networkProperties,
207  arm::pipe::IProfilingService* profilingService) :
208  m_OptimizedNetwork(std::move(net)),
209  m_NetworkProperties(networkProperties),
210  m_TensorHandleFactoryRegistry(),
211  m_ProfilingService(profilingService)
212 {
214  // Get the profiler and register it for the current thread.
215  const std::shared_ptr<IProfiler>& profiler = m_OptimizedNetwork->GetProfiler();
217 
218  profiler->EnableProfiling(networkProperties.m_ProfilingEnabled);
219 
220  profiler->EnableNetworkDetailsToStdOut(networkProperties.m_OutputNetworkDetailsMethod);
221 
222  // We need to check that the memory sources match up with the values of import and export specified during the
223  // optimize phase. If they don't this will throw an exception.
224  ValidateSourcesMatchOptimizedNetwork(m_OptimizedNetwork.get()->pOptimizedNetworkImpl->GetModelOptions(),
225  m_NetworkProperties);
226 
227  //First create tensor handlers, backends and workload factories.
228  //Handlers are created before workloads are.
229  //Because workload creation can modify some of the handlers,
230  //(for example the splitter and concat layers).
231 
232  bool useExternalMemoryManager = false;
233  bool useInternalMemoryManager = false;
234  Graph& order = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph();
235  // Ensure Topological order
236  order.SetLayersOutOfOrder();
237  order.TopologicalSort();
238 
239  if (!networkProperties.m_AsyncEnabled)
240  {
241  m_IsInputImported = std::vector<bool>(order.GetNumInputs(), false);
242  m_IsOutputImported = std::vector<bool>(order.GetNumOutputs(), false);
243  }
244 
245  for (auto&& layer : order)
246  {
247  auto const& backendId = layer->GetBackendId();
248  if (m_Backends.count(backendId) == 0)
249  {
250  auto createBackend = BackendRegistryInstance().GetFactory(backendId);
251  auto it = m_Backends.emplace(std::make_pair(backendId, createBackend()));
252 
253  IBackendInternal* backend = it.first->second.get();
254 
255  // If we're doing async execution verify that the backend supports it and ExternallyManagedMemory.
256  if (networkProperties.m_AsyncEnabled)
257  {
258  if (!HasCapability(BackendOptions::BackendOption{"AsyncExecution", true}, backend->GetCapabilities()))
259  {
260  std::string er = backend->GetId();
261  er += " does not support AsyncExecution";
262  throw BackendCapabilityException(er);
263  }
264  if (!HasCapability(BackendOptions::BackendOption{"ExternallyManagedMemory", true},
265  backend->GetCapabilities()))
266  {
267  std::string er = backend->GetId();
268  er += " does not support ExternallyManagedMemory\n";
269  er += "AsyncEnabled networks require all backends to support ExternallyManagedMemory";
270  throw BackendCapabilityException(er);
271  }
272  m_SupportsExternallyManagedMemory[backend->GetId()] = true;
273  useExternalMemoryManager = true;
274  }
275  else
276  {
277  m_SupportsExternallyManagedMemory[backend->GetId()] = false;
278  useInternalMemoryManager = true;
279  }
280 
282  if (backend->SupportsTensorAllocatorAPI())
283  {
284  workloadFactory = backend->CreateWorkloadFactory(
285  m_TensorHandleFactoryRegistry,
286  m_OptimizedNetwork->pOptimizedNetworkImpl->GetModelOptions(),
287  static_cast<MemorySourceFlags>(m_NetworkProperties.m_InputSource),
288  static_cast<MemorySourceFlags>(m_NetworkProperties.m_OutputSource));
289  }
290  else
291  {
292  m_BackendMemoryMangers.emplace_back(backend->CreateMemoryManager());
293  workloadFactory = backend->CreateWorkloadFactory(
294  m_BackendMemoryMangers.back(), m_OptimizedNetwork->pOptimizedNetworkImpl->GetModelOptions());
295  }
296  m_WorkloadFactories[backendId ] = std::move(workloadFactory);
297  }
298  }
299 
300  if (!networkProperties.m_AsyncEnabled)
301  {
302  for (auto&& layer : order)
303  {
304  auto& workloadFactory = GetWorkloadFactory(*layer);
305  bool supportsExternalManager = m_SupportsExternallyManagedMemory[layer->GetBackendId()];
306 
307  switch (layer->GetType())
308  {
309  case LayerType::Input:
311  {
312  // If IsImportEnabled is true then we need to set IsMemoryManaged
313  // to false when creating TensorHandles
314  layer->CreateTensorHandles(m_TensorHandleFactoryRegistry,
315  workloadFactory,
316  !supportsExternalManager && !m_NetworkProperties.m_ImportEnabled);
317  break;
318  }
319  case LayerType::Constant:
320  {
321  layer->CreateTensorHandles(m_TensorHandleFactoryRegistry, workloadFactory, true);
322  break;
323  }
324  default:
325  {
326  // Look for a layer with 1 OutputSlot which has 1 connection and that connection is an Output Layer
327  // If Export is enabled disable memory management so we can export, otherwise we do a copy
328  if ((layer->GetNumOutputSlots() == 1) &&
329  (layer->GetOutputSlots()[0].GetNumConnections() == 1) &&
330  (layer->GetOutputSlots()[0].GetConnection(0)->GetOwningLayer().GetType() == LayerType::Output))
331  {
332  layer->CreateTensorHandles(m_TensorHandleFactoryRegistry,
333  workloadFactory,
334  !supportsExternalManager && !m_NetworkProperties.m_ExportEnabled);
335  }
336  else
337  {
338  layer->CreateTensorHandles(m_TensorHandleFactoryRegistry,
339  workloadFactory,
340  !supportsExternalManager);
341  }
342  }
343  }
344  }
345  }
346 
347  ProfilingGuid networkGuid = m_OptimizedNetwork->GetGuid();
348  std::unique_ptr<TimelineUtilityMethods> timelineUtils =
349  TimelineUtilityMethods::GetTimelineUtils(*m_ProfilingService);
350  if (timelineUtils)
351  {
352  timelineUtils->CreateTypedEntity(networkGuid, LabelsAndEventClasses::NETWORK_GUID);
353  // Mark the network with a start of life event
354  timelineUtils->RecordEvent(networkGuid, LabelsAndEventClasses::ARMNN_PROFILING_SOL_EVENT_CLASS);
355  // and with the process ID
356  int processID = arm::pipe::GetCurrentProcessId();
357  std::stringstream ss;
358  ss << processID;
359  timelineUtils->MarkEntityWithLabel(networkGuid, ss.str(), LabelsAndEventClasses::PROCESS_ID_GUID);
360  }
361 
362  std::vector<IWorkload*> ConstWorkloads;
363 
364  //Then create workloads.
365  {
366  ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "LoadNetwork_CreateWorkloads");
367  for (auto&& layer: order)
368  {
369  if (timelineUtils)
370  {
371  // Add layer to the post-optimisation network structure
372  AddLayerStructure(timelineUtils, *layer, networkGuid);
373  }
374 
375  const IWorkloadFactory& workloadFactory = GetWorkloadFactory(*layer);
376 
377  switch (layer->GetType())
378  {
379  case LayerType::Input:
380  case LayerType::Output:
381  {
382  // Inputs and outputs are treated in a special way - see EnqueueInput() and EnqueueOutput().
383  break;
384  }
385  default:
386  {
387  auto workload = layer->CreateWorkload(workloadFactory);
388 
389  if (!workload)
390  {
391  const char* const layerName =
392  layer->GetNameStr().length() != 0 ? layer->GetName() : "<Unnamed>";
394  fmt::format("No workload created for layer (name: '{0}' type: '{1}') (compute '{2}')",
395  layerName, static_cast<int>(layer->GetType()), layer->GetBackendId().Get()
396  ));
397  }
398 
399  if (timelineUtils)
400  {
401  // Add workload to the post-optimisation network structure
402  AddWorkloadStructure(timelineUtils, workload, *layer);
403  }
404 
405  // For async networks ConstantWorkloads are managed exclusively by LoadedNetwork
406  // and are separated out from the other workloads
407  if((networkProperties.m_AsyncEnabled || useExternalMemoryManager) &&
408  layer->GetType() == LayerType::Constant)
409  {
410  m_ConstantTensorHandles[layer->GetGuid()] =
411  layer->GetOutputSlot(0).GetOutputHandler().GetData();
412  m_ConstantWorkloads[layer->GetGuid()] = std::move(workload);
413  }
414  else
415  {
416  m_WorkloadQueue.push_back(std::move(workload));
417 
418  if (layer->GetType() == LayerType::Constant)
419  {
420  // Place the Constant Workloads into a queue so that they can be executed first
421  ConstWorkloads.push_back(m_WorkloadQueue.back().get());
422  }
423  }
424  // release the constant data in the layer..
425  layer->ReleaseConstantData();
426  break;
427  }
428  }
429  }
430  }
431 
432  // Gather information about workloads for inputs & outputs
433  if (!networkProperties.m_AsyncEnabled && m_WorkloadQueue.size() != 0)
434  {
435  const int noOfInputs = armnn::numeric_cast<int>(order.GetNumInputs());
436 
437  // Get indices of all workloads connected to each input and
438  // check if they support tensor handle replacement
439  for (const BindableLayer* layer: order.GetInputLayers())
440  {
441  const auto bindingId = layer->GetBindingId();
442 
443  bool supportsReplacement = true;
444 
445  for (const auto inputSlot: layer->GetOutputSlot(0).GetConnections())
446  {
447  auto workloadIndex = std::distance(order.begin(), order.GetPosInGraph(inputSlot->GetOwningLayer()));
448  workloadIndex -= noOfInputs;
449 
450  m_InputWorkloadSlotPairs[bindingId].emplace_back(WorkloadIndices{
451  armnn::numeric_cast<unsigned int>(workloadIndex), inputSlot->GetSlotIndex()});
452 
453  auto workload = m_WorkloadQueue[m_InputWorkloadSlotPairs[bindingId].back().m_WorkloadIndex].get();
454  supportsReplacement &= workload->SupportsTensorHandleReplacement();
455  }
456 
457  ITensorHandleFactory::FactoryId factoryId = layer->GetOutputSlot(0).GetTensorHandleFactoryId();
458  // Get matching import factory Id
459  ITensorHandleFactory::FactoryId importFactoryId =
460  m_TensorHandleFactoryRegistry.GetMatchingImportFactoryId(factoryId);
461 
462  ITensorHandleFactory *importFactory = m_TensorHandleFactoryRegistry.GetFactory(importFactoryId);
463 
464  if (supportsReplacement && importFactory)
465  {
466  m_PreImportedInputHandles.emplace_back(
467  bindingId, importFactory->CreateTensorHandle(layer->GetOutputSlot(0).GetTensorInfo(), false));
468  }
469  else
470  {
471  m_PreImportedInputHandles.emplace_back(bindingId, nullptr);
472  }
473  }
474 
475  // Get indices of all workloads connected to each output and
476  // check if they support tensor handle replacement
477  for (const BindableLayer* layer: order.GetOutputLayers())
478  {
479  const auto bindingId = layer->GetBindingId();
480 
481  const auto outputSlot = layer->GetInputSlot(0).GetConnectedOutputSlot();
482  auto& indices = m_OutputWorkloadSlotPairs[bindingId];
483 
484  auto workloadIndex = std::distance(order.begin(), order.GetPosInGraph(outputSlot->GetOwningLayer()));
485  workloadIndex -= noOfInputs;
486 
487  indices.m_OutputSlotIndices = WorkloadIndices{numeric_cast<unsigned int>(workloadIndex),
488  outputSlot->CalculateIndexOnOwner()};
489 
490  bool supportsReplacement = true;
491  auto outputWorkload = m_WorkloadQueue[indices.m_OutputSlotIndices.m_WorkloadIndex].get();
492  supportsReplacement &= outputWorkload->SupportsTensorHandleReplacement();
493 
494  for (auto &inputSlot: outputSlot->GetConnections())
495  {
496  if(inputSlot->GetOwningLayer().GetType() != LayerType::Output)
497  {
498  auto inWorkloadIndex = std::distance(order.begin(),
499  order.GetPosInGraph(inputSlot->GetOwningLayer()));
500  inWorkloadIndex -= noOfInputs;
501  indices.m_InputSlotIndices.emplace_back(WorkloadIndices{numeric_cast<unsigned int>(inWorkloadIndex),
502  inputSlot->GetSlotIndex()});
503  auto inputWorkload = m_WorkloadQueue[indices.m_InputSlotIndices.back().m_WorkloadIndex].get();
504  supportsReplacement &= inputWorkload->SupportsTensorHandleReplacement();
505  }
506  }
507 
508  ITensorHandleFactory::FactoryId factoryId = outputSlot->GetTensorHandleFactoryId();
509  // Get matching import factory Id
510  ITensorHandleFactory::FactoryId importFactoryId =
511  m_TensorHandleFactoryRegistry.GetMatchingImportFactoryId(factoryId);
512  ITensorHandleFactory *importFactory = m_TensorHandleFactoryRegistry.GetFactory(importFactoryId);
513 
514  if (supportsReplacement && importFactory)
515  {
516  m_PreImportedOutputHandles.emplace_back(
517  bindingId, importFactory->CreateTensorHandle(outputSlot->GetTensorInfo(), false));
518  }
519  else
520  {
521  m_PreImportedOutputHandles.emplace_back(bindingId, nullptr);
522  }
523  }
524  }
525 
526  for (auto&& workloadFactory : m_WorkloadFactories)
527  {
528  workloadFactory.second->AfterWorkloadsCreated();
529  }
530 
531  if (timelineUtils)
532  {
533  // Commit to send the post-optimisation network structure
534  timelineUtils->Commit();
535  }
536 
537  if (useExternalMemoryManager)
538  {
539  if (networkProperties.m_AsyncEnabled)
540  {
541  CreateMemoryProfileAsync();
542  }
543  else
544  {
545  CreateMemoryProfile();
546  }
547 
548  auto backendStrategyMap = BackendRegistryInstance().GetMemoryOptimizerStrategies();
549  for (auto& backendMemoryProfile : m_MemBlockMap)
550  {
551  const BackendId& backendId = backendMemoryProfile.first;
552  if (backendStrategyMap.find(backendId) != backendStrategyMap.end())
553  {
554  m_MemBinMap[backendId] = backendStrategyMap[backendId]->Optimize(backendMemoryProfile.second);
555  }
556  else
557  {
558  m_MemBinMap[backendId] = m_ConstantStrategy->Optimize(backendMemoryProfile.second);
559  }
560  }
561 
562  if (!networkProperties.m_AsyncEnabled)
563  {
564  m_ExternalMemoryManager = CreateExternalMemoryManger(m_TensorMemory);
565 
566  // Sort m_TensorMemory, so it's order matches m_Tensorhandles
567  std::sort(m_TensorMemory.begin(), m_TensorMemory.end(),
568  [](const std::pair<std::shared_ptr<TensorMemory>, MemorySource>& lhs,
569  const std::pair<std::shared_ptr<TensorMemory>, MemorySource>& rhs)
570  {
571  return lhs.first->m_OutputSlotId < rhs.first->m_OutputSlotId;
572  });
573  }
574  }
575 
576  // Now that the intermediate tensor memory has been set-up,
577  // do any post allocation configuration for each workload.
578  if (!networkProperties.m_AsyncEnabled)
579  {
580  if (useInternalMemoryManager)
581  {
582  // Set up memory.
583  m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().AllocateDynamicBuffers();
584  }
585 
586  for (auto &workload : m_WorkloadQueue)
587  {
588  workload->PostAllocationConfigure();
589  }
590  }
591 
592  if (useExternalMemoryManager)
593  {
594  if (!networkProperties.m_AsyncEnabled)
595  {
596  AllocateAndExecuteConstantWorkloads();
597  }
598  else
599  {
600  AllocateAndExecuteConstantWorkloadsAsync();
601  }
602  }
603  // If synchronous, execute all constant layer workloads
604  if (!networkProperties.m_AsyncEnabled)
605  {
606  for (auto workload: ConstWorkloads)
607  {
608  workload->Execute();
609  }
610  }
611 }
612 
613 void LoadedNetwork::AllocateAndExecuteConstantWorkloads()
614 {
615  ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "LoadNetwork_AllocateAndExecuteConstants");
616  for (auto& pair : m_ConstantWorkloads)
617  {
618  auto tensorHandle = m_ConstantTensorHandles[pair.first];
619  tensorHandle->Allocate();
620  pair.second->Execute();
621  }
622 }
623 
624 void LoadedNetwork::AllocateAndExecuteConstantWorkloadsAsync()
625 {
626  ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "LoadNetwork_AllocateAndExecuteConstants");
627  Graph& order = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph();
628  for (auto&& layer : order)
629  {
630  if (layer->GetType() == LayerType::Constant)
631  {
632  const auto& outSlot = layer->GetOutputSlots()[0];
633  const auto factoryId = outSlot.GetTensorHandleFactoryId();
635  auto& workloadFactory = GetWorkloadFactory(*layer);
636 
637  layer->CreateTensorHandles(m_TensorHandleFactoryRegistry, workloadFactory);
638  ITensorHandle* tensorHandle = outSlot.GetOutputHandler().GetData();
639 
640  m_ConstantTensorHandles[layer->GetGuid()] = tensorHandle;
641  tensorHandle->Allocate();
642 
643  auto& backend = m_Backends.at(layer->GetBackendId());
644 
645  WorkingMemDescriptor memDesc;
646  memDesc.m_Outputs.push_back(tensorHandle);
647 
648  ExecutionData executionData = backend->CreateExecutionData(memDesc);
649  m_ConstantWorkloads[layer->GetGuid()]->ExecuteAsync(executionData);
650  }
651  }
652 }
653 
654 void LoadedNetwork::SendNetworkStructure(arm::pipe::IProfilingService& profilingService)
655 {
656  ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "LoadNetwork_SendNetworkStructure");
657  Graph& order = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().TopologicalSort();
658  ProfilingGuid networkGuid = m_OptimizedNetwork->GetGuid();
659 
660  std::unique_ptr<TimelineUtilityMethods> timelineUtils =
661  TimelineUtilityMethods::GetTimelineUtils(profilingService);
662 
663  timelineUtils->CreateTypedEntity(networkGuid, LabelsAndEventClasses::NETWORK_GUID);
664 
665  for (auto&& layer : order)
666  {
667  // Add layer to the post-optimisation network structure
668  AddLayerStructure(timelineUtils, *layer, networkGuid);
669  switch (layer->GetType())
670  {
671  case LayerType::Input:
672  case LayerType::Output:
673  {
674  // Inputs and outputs are treated in a special way - see EnqueueInput() and EnqueueOutput().
675  break;
676  }
677  default:
678  {
679  for (auto& workload : m_WorkloadQueue)
680  {
681  // Add workload to the post-optimisation network structure
682  AddWorkloadStructure(timelineUtils, workload, *layer);
683  }
684  break;
685  }
686  }
687  }
688  // Commit to send the post-optimisation network structure
689  timelineUtils->Commit();
690 }
691 
693 {
694  return m_OptimizedNetwork->GetGuid();
695 }
696 
698 {
699  for (auto&& inputLayer : m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().GetInputLayers())
700  {
701  ARMNN_ASSERT_MSG(inputLayer->GetNumOutputSlots() == 1, "Input layer should have exactly 1 output slot");
702  if (inputLayer->GetBindingId() == layerId)
703  {
704  return inputLayer->GetOutputSlot(0).GetTensorInfo();
705  }
706  }
707 
708  throw InvalidArgumentException(fmt::format("No input layer is associated with id {}", layerId));
709 }
710 
712 {
713  for (auto&& outputLayer : m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().GetOutputLayers())
714  {
715  ARMNN_ASSERT_MSG(outputLayer->GetNumInputSlots() == 1, "Output layer should have exactly 1 input slot");
716  ARMNN_ASSERT_MSG(outputLayer->GetInputSlot(0).GetConnection(), "Input slot on Output layer must be connected");
717  if (outputLayer->GetBindingId() == layerId)
718  {
719  return outputLayer->GetInputSlot(0).GetConnection()->GetTensorInfo();
720  }
721  }
722 
723  throw InvalidArgumentException(fmt::format("No output layer is associated with id {}", layerId));
724 }
725 
726 const IWorkloadFactory& LoadedNetwork::GetWorkloadFactory(const Layer& layer) const
727 {
728  const IWorkloadFactory* workloadFactory = nullptr;
729 
730  auto it = m_WorkloadFactories.find(layer.GetBackendId());
731  if (it == m_WorkloadFactories.end())
732  {
733  throw RuntimeException(fmt::format("No workload factory for {0} to be used for layer: {1}",
734  layer.GetBackendId().Get(),
735  layer.GetNameStr()),
736  CHECK_LOCATION());
737  }
738 
739  workloadFactory = it->second.get();
740 
741  ARMNN_ASSERT_MSG(workloadFactory, "No workload factory");
742 
743  return *workloadFactory;
744 }
745 
746 namespace {
747 
748 // Non-copyable class owning accelerator-specific tensor data.
749 class TensorPin
750 {
751 public:
752  TensorPin(std::unique_ptr<ITensorHandle> handle, const TensorInfo& info, LayerBindingId id)
753  : m_TensorHandle(std::move(handle))
754  , m_TensorInfo(info)
755  , m_Id(id)
756  {
757  }
758 
759  ITensorHandle* GetTensorHandle() const { return m_TensorHandle.get(); }
760  const TensorInfo& GetTensorInfo() const { return m_TensorInfo; }
761  LayerBindingId GetBindingId() const { return m_Id; }
762 
763 private:
764  std::unique_ptr<ITensorHandle> m_TensorHandle;
765  TensorInfo m_TensorInfo;
766  LayerBindingId m_Id;
767 };
768 
769 static const TensorPin& GetTensorPin(LayerBindingId id,
770  const std::vector<TensorPin>& pins,
771  char const* bindingPointDesc)
772 {
773  auto it = std::find_if(pins.begin(), pins.end(),
774  [id](const TensorPin& pin)
775  {
776  return pin.GetBindingId() == id;
777  });
778 
779  if (it != pins.end())
780  {
781  return *it;
782  }
783  else
784  {
785  throw InvalidArgumentException(fmt::format("No tensor supplied for {0} {1}", bindingPointDesc, id));
786  }
787 }
788 
789 // Stores data that needs to be kept accessible for the entire execution of a workload.
790 class WorkloadData
791 {
792 public:
793  WorkloadData(const InputTensors& inputTensors, const OutputTensors& outputTensors)
794  {
795  m_InputTensorPins.reserve(inputTensors.size());
796  m_OutputTensorPins.reserve(outputTensors.size());
797 
798  for (auto inputTensorPair : inputTensors)
799  {
800  auto inputTensor = inputTensorPair.second;
801 
802  std::unique_ptr<ITensorHandle> tensorHandle =
803  std::make_unique<ConstPassthroughTensorHandle>(inputTensor.GetInfo(),inputTensor.GetMemoryArea());
804  LayerBindingId layerId = inputTensorPair.first;
805 
806  m_InputTensorPins.emplace_back(std::move(tensorHandle), inputTensor.GetInfo(), layerId);
807  }
808 
809  for (auto outputTensorPair : outputTensors)
810  {
811  auto outputTensor = outputTensorPair.second;
812 
813  std::unique_ptr<ITensorHandle> tensorHandle =
814  std::make_unique<PassthroughTensorHandle>(outputTensor.GetInfo(), outputTensor.GetMemoryArea());
815  LayerBindingId layerId = outputTensorPair.first;
816 
817  m_OutputTensorPins.emplace_back(std::move(tensorHandle), outputTensor.GetInfo(), layerId);
818  }
819  }
820 
821  const TensorPin& GetInputTensorPin(LayerBindingId id) const
822  {
823  return GetTensorPin(id, m_InputTensorPins, "input");
824  }
825 
826  const TensorPin& GetOutputTensorPin(LayerBindingId id) const
827  {
828  return GetTensorPin(id, m_OutputTensorPins, "output");
829  }
830 
831 private:
832 
833  std::vector<TensorPin> m_InputTensorPins;
834  std::vector<TensorPin> m_OutputTensorPins;
835 };
836 
837 }
838 
840  const OutputTensors& outputTensors,
841  std::vector<ImportedInputId> preImportedInputIds,
842  std::vector<ImportedOutputId> preImportedOutputIds)
843 {
844  const Graph& graph = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph();
845 
846  // Walk graph to determine the order of execution.
847  if (graph.GetNumLayers() < 2)
848  {
849  ARMNN_LOG(warning) << "IRuntime::EnqueueWorkload()::Less than two nodes in graph";
850  return Status::Failure;
851  }
852 
853  // Data that must be kept alive for the entire execution of the workload.
854  WorkloadData workloadData(inputTensors, outputTensors);
855 
856  // Input tensors can be provided as parameters or pre imported. Either way the number of
857  // tensors should match the number of inputs.
858  if (graph.GetNumInputs() != (inputTensors.size() + preImportedInputIds.size()))
859  {
860  throw InvalidArgumentException("Number of inputs provided does not match network.");
861  }
862 
863  // For each input to the network, call EnqueueInput with the data passed by the user.
864  {
866  m_InputQueue.clear();
867  m_InputQueue.reserve(graph.GetNumInputs());
868 
869  unsigned int inputIndex = 0;
870  unsigned int importedInputIdIndex = 0;
871  std::sort(preImportedInputIds.begin(), preImportedInputIds.end());
872  for (const BindableLayer* inputLayer : graph.GetInputLayers())
873  {
874  if (importedInputIdIndex < preImportedInputIds.size() &&
875  inputIndex == preImportedInputIds[importedInputIdIndex])
876  {
877  // Only replace tensorhandles if they have not already been replaced
878  if (!m_IsInputImported[inputIndex])
879  {
880  auto outputTensorHandle = m_PreImportedInputHandles[inputIndex].m_TensorHandle.get();
881 
882  for (const auto& workloadInfo: m_InputWorkloadSlotPairs[inputLayer->GetBindingId()])
883  {
884  auto workload = m_WorkloadQueue[workloadInfo.m_WorkloadIndex].get();
885  workload->ReplaceInputTensorHandle(outputTensorHandle, workloadInfo.m_SlotIndex);
886  }
887  m_IsInputImported[inputIndex] = true;
888  }
889  importedInputIdIndex++;
890  }
891  else
892  {
893  if (m_IsInputImported[inputIndex])
894  {
895  OutputHandler& handler = const_cast<OutputHandler&>(inputLayer->GetOutputHandler(0));
896 
897  for (const auto& workloadInfo: m_InputWorkloadSlotPairs[inputLayer->GetBindingId()])
898  {
899  auto workload = m_WorkloadQueue[workloadInfo.m_WorkloadIndex].get();
900  workload->ReplaceInputTensorHandle(handler.GetData(), workloadInfo.m_SlotIndex);
901  }
902 
903  m_IsInputImported[inputIndex] = false;
904  }
905 
906  // InputTensorHandle is not imported yet, process to enqueue input
907  const TensorPin& pin = workloadData.GetInputTensorPin(inputLayer->GetBindingId());
908  EnqueueInput(*inputLayer, pin.GetTensorHandle(), pin.GetTensorInfo());
909  }
910  inputIndex++;
911  }
912  }
913  // For each output to the network, call EnqueueOutput with the data passed by the user.
914  {
916  m_OutputQueue.clear();
917  m_OutputQueue.reserve(graph.GetNumOutputs());
918 
919  if (preImportedOutputIds.size() > graph.GetNumOutputs())
920  {
921  throw InvalidArgumentException("Invalid number of preImportedOutputIds");
922  }
923 
924  unsigned int outputIndex = 0;
925  unsigned int importedOutputIdIndex = 0;
926  std::sort(preImportedOutputIds.begin(), preImportedOutputIds.end());
927  for (const BindableLayer* outputLayer : graph.GetOutputLayers())
928  {
929  if (importedOutputIdIndex < preImportedOutputIds.size() &&
930  outputIndex == preImportedOutputIds[importedOutputIdIndex])
931  {
932  // Only replace tensorhandles if they have not already been replaced
933  ITensorHandle* inputTensorHandle = m_PreImportedOutputHandles[outputIndex].m_TensorHandle.get();
934 
935  if (!m_IsOutputImported[outputIndex])
936  {
937  const auto bindingId = outputLayer->GetBindingId();
938  const auto& indices = m_OutputWorkloadSlotPairs[bindingId];
939 
940  auto outputWorkload = m_WorkloadQueue[indices.m_OutputSlotIndices.m_WorkloadIndex].get();
941 
942  outputWorkload->ReplaceOutputTensorHandle(inputTensorHandle,
943  indices.m_OutputSlotIndices.m_SlotIndex);
944 
945  for (const auto& workloadInfo: indices.m_InputSlotIndices)
946  {
947  auto inputWorkload = m_WorkloadQueue[workloadInfo.m_WorkloadIndex].get();
948  inputWorkload->ReplaceInputTensorHandle(inputTensorHandle, workloadInfo.m_SlotIndex);
949  }
950  m_IsOutputImported[outputIndex] = true;
951  }
952 
953  ARMNN_ASSERT_MSG(inputTensorHandle != nullptr, "Data should have been allocated.");
954  MemSyncQueueDescriptor syncDesc;
955  syncDesc.m_Inputs.push_back(inputTensorHandle);
957  info.m_InputTensorInfos.push_back(
958  outputLayer->GetInputSlot(0).GetConnectedOutputSlot()->GetTensorInfo());
959  auto syncWorkload = std::make_unique<SyncMemGenericWorkload>(syncDesc, info);
960  ARMNN_ASSERT_MSG(syncWorkload, "No sync workload created");
961  m_OutputQueue.push_back(move(syncWorkload));
962  importedOutputIdIndex++;
963  }
964  else
965  {
966  if (m_IsOutputImported[outputIndex])
967  {
968  const auto bindingId = outputLayer->GetBindingId();
969  const auto& indices = m_OutputWorkloadSlotPairs[bindingId];
970 
971  auto outputWorkload = m_WorkloadQueue[indices.m_OutputSlotIndices.m_WorkloadIndex].get();
972  const OutputHandler& outputHandler =
973  outputLayer->GetInputSlot(0).GetConnectedOutputSlot()->GetOutputHandler();
974 
975  outputWorkload->ReplaceOutputTensorHandle(
976  outputHandler.GetData(), indices.m_OutputSlotIndices.m_SlotIndex);
977 
978  for (const auto& workloadInfo: indices.m_InputSlotIndices)
979  {
980  auto inputWorkload = m_WorkloadQueue[workloadInfo.m_WorkloadIndex].get();
981  inputWorkload->ReplaceInputTensorHandle(outputHandler.GetData(), workloadInfo.m_SlotIndex);
982  }
983  m_IsOutputImported[outputIndex] = false;
984  }
985 
986  const TensorPin& pin = workloadData.GetOutputTensorPin(outputLayer->GetBindingId());
987  // OutputTensorHandle is not imported yet, process to enqueue Output
988  EnqueueOutput(*outputLayer, pin.GetTensorHandle(), pin.GetTensorInfo());
989  }
990  outputIndex++;
991  }
992  }
993 
994  std::unique_ptr<TimelineUtilityMethods> timelineUtils =
995  TimelineUtilityMethods::GetTimelineUtils(*m_ProfilingService);
996  ProfilingGuid inferenceGuid = m_ProfilingService->GetNextGuid();
997  if (timelineUtils)
998  {
999  // Add inference timeline trace if profiling is enabled.
1000  ProfilingGuid networkGuid = m_OptimizedNetwork->GetGuid();
1001  timelineUtils->CreateTypedEntity(inferenceGuid, LabelsAndEventClasses::INFERENCE_GUID);
1002  timelineUtils->CreateRelationship(ProfilingRelationshipType::RetentionLink,
1003  networkGuid,
1004  inferenceGuid,
1005  LabelsAndEventClasses::EXECUTION_OF_GUID);
1006  timelineUtils->RecordEvent(inferenceGuid, LabelsAndEventClasses::ARMNN_PROFILING_SOL_EVENT_CLASS);
1007  }
1008 
1009  bool executionSucceeded = true;
1010 
1011  {
1012  if (m_ProfilingService->IsProfilingEnabled())
1013  {
1014  m_ProfilingService->IncrementCounterValue(INFERENCES_RUN);
1015  }
1017  ARMNN_SCOPED_HEAP_PROFILING("Executing");
1018  executionSucceeded = Execute(timelineUtils, inferenceGuid);
1019  }
1020 
1021  if (timelineUtils)
1022  {
1023  // Add end of life of the inference timeline if profiling is enabled.
1024  timelineUtils->RecordEvent(inferenceGuid, LabelsAndEventClasses::ARMNN_PROFILING_EOL_EVENT_CLASS);
1025  timelineUtils->Commit();
1026  }
1027 
1028  return executionSucceeded ? Status::Success : Status::Failure;
1029 }
1030 
1031 void LoadedNetwork::EnqueueInput(const BindableLayer& layer, ITensorHandle* tensorHandle, const TensorInfo& tensorInfo)
1032 {
1033  if (layer.GetType() != LayerType::Input)
1034  {
1035  throw InvalidArgumentException("EnqueueInput: given layer not an InputLayer");
1036  }
1037 
1038  if (tensorHandle == nullptr)
1039  {
1040  throw InvalidArgumentException("EnqueueInput: tensorHandle must not be NULL");
1041  }
1042 
1043  InputQueueDescriptor inputQueueDescriptor;
1045 
1046  inputQueueDescriptor.m_Inputs.push_back(tensorHandle);
1047  info.m_InputTensorInfos.push_back(tensorInfo);
1048 
1049  ARMNN_ASSERT_MSG(layer.GetNumOutputSlots() == 1, "Can only handle Input Layer with one output");
1050  const OutputHandler& handler = layer.GetOutputHandler();
1051  const TensorInfo& outputTensorInfo = handler.GetTensorInfo();
1052  ITensorHandle* outputTensorHandle = handler.GetData();
1053  ARMNN_ASSERT_MSG(outputTensorHandle != nullptr,
1054  "Data should have been allocated.");
1055  inputQueueDescriptor.m_Outputs.push_back(outputTensorHandle);
1056  info.m_OutputTensorInfos.push_back(outputTensorInfo);
1057 
1058  MemorySourceFlags importFlags = outputTensorHandle->GetImportFlags();
1059  bool needMemCopy = true;
1060  if (m_NetworkProperties.m_ImportEnabled) // Try import the input tensor
1061  {
1062  if(CheckFlag(importFlags, m_NetworkProperties.m_InputSource))
1063  {
1064  needMemCopy = false;
1065  // This assumes a CPU Tensor handle
1066  void* mem = tensorHandle->Map(false);
1067  if (outputTensorHandle->Import(mem, m_NetworkProperties.m_InputSource))
1068  {
1069  tensorHandle->Unmap();
1070  return; // No need for a workload since the import has been done.
1071  }
1072  tensorHandle->Unmap();
1073  throw MemoryImportException("EnqueueInput: Memory Import failed");
1074  }
1075  }
1076  if (needMemCopy)
1077  {
1078  // Create a mem copy workload for input since we did not import
1079  std::unique_ptr<IWorkload> inputWorkload = std::make_unique<CopyMemGenericWorkload>(inputQueueDescriptor, info);
1080 
1081  ARMNN_ASSERT_MSG(inputWorkload, "No input workload created");
1082 
1083  std::unique_ptr<TimelineUtilityMethods> timelineUtils =
1084  TimelineUtilityMethods::GetTimelineUtils(*m_ProfilingService);
1085  if (timelineUtils)
1086  {
1087  // Add Input Workload to the post-optimisation network structure
1088  AddWorkloadStructure(timelineUtils, inputWorkload, layer);
1089  timelineUtils->Commit();
1090  }
1091 
1092  m_InputQueue.push_back(move(inputWorkload));
1093  }
1094 }
1095 
1096 void LoadedNetwork::EnqueueOutput(const BindableLayer& layer, ITensorHandle* tensorHandle, const TensorInfo& tensorInfo)
1097 {
1098  if (layer.GetType() != LayerType::Output)
1099  {
1100  throw InvalidArgumentException("EnqueueOutput: given layer not an OutputLayer");
1101  }
1102 
1103  if (tensorHandle == nullptr)
1104  {
1105  throw InvalidArgumentException("EnqueueOutput: tensorHandle must not be NULL");
1106  }
1107 
1108  OutputQueueDescriptor outputQueueDescriptor;
1110 
1111  outputQueueDescriptor.m_Outputs.push_back(tensorHandle);
1112  info.m_OutputTensorInfos.push_back(tensorInfo);
1113 
1114  ARMNN_ASSERT_MSG(layer.GetNumInputSlots() == 1, "Output Layer should have exactly one input.");
1115 
1116  // Gets the output handler from the previous node.
1117  const OutputHandler& outputHandler = layer.GetInputSlots()[0].GetConnectedOutputSlot()->GetOutputHandler();
1118 
1119  const TensorInfo& inputTensorInfo = outputHandler.GetTensorInfo();
1120  ITensorHandle* inputTensorHandle = outputHandler.GetData();
1121  ARMNN_ASSERT_MSG(inputTensorHandle != nullptr, "Data should have been allocated.");
1122 
1123  // Try import the output tensor.
1124  // Note: We can only import the output pointer if all of the following hold true:
1125  // a) The imported pointer is aligned sufficiently
1126  // b) The tensor has zero padding
1127  // c) There is only one connection to the OutputSlot and it is to an OutputLayer.
1128  // d) The output pointer is allocated via malloc. (Other types will be supported in a later release)
1129  // e) m_IsExportEnabled must be set to true
1130  bool needMemCopy = true;
1131  if (m_NetworkProperties.m_ExportEnabled &&
1132  (layer.GetInputSlots()[0].GetConnectedOutputSlot()->GetNumConnections() == 1))
1133  {
1134  if(layer.GetInputSlots()[0].GetConnectedOutputSlot()->GetOwningLayer().GetType() != LayerType::Input)
1135  {
1136  MemorySourceFlags importFlags = inputTensorHandle->GetImportFlags();
1137  if (CheckFlag(importFlags, m_NetworkProperties.m_OutputSource))
1138  {
1139  needMemCopy = false;
1140  void *mem = tensorHandle->Map(false);
1141  bool importOk = inputTensorHandle->Import(mem, m_NetworkProperties.m_OutputSource);
1142  tensorHandle->Unmap();
1143 
1144  if (importOk)
1145  {
1146  // Insert synchronization workload
1147  MemSyncQueueDescriptor syncDesc;
1148  syncDesc.m_Inputs.push_back(inputTensorHandle);
1149  info.m_InputTensorInfos.push_back(inputTensorInfo);
1150  auto syncWorkload = std::make_unique<SyncMemGenericWorkload>(syncDesc, info);
1151  ARMNN_ASSERT_MSG(syncWorkload, "No sync workload created");
1152  m_OutputQueue.push_back(move(syncWorkload));
1153  }
1154  else
1155  {
1156  throw MemoryExportException("EnqueueOutput: Memory Export failed");
1157  }
1158  }
1159  }
1160  }
1161  if (needMemCopy)
1162  {
1163  // If we got here then we didn't export the memory, so add an output workload which performs a memcopy.
1164  outputQueueDescriptor.m_Inputs.push_back(inputTensorHandle);
1165  info.m_InputTensorInfos.push_back(inputTensorInfo);
1166 
1167  std::unique_ptr<IWorkload> outputWorkload =
1168  std::make_unique<CopyMemGenericWorkload>(outputQueueDescriptor, info);
1169  ARMNN_ASSERT_MSG(outputWorkload, "No output workload created");
1170 
1171  std::unique_ptr<TimelineUtilityMethods> timelineUtils =
1172  TimelineUtilityMethods::GetTimelineUtils(*m_ProfilingService);
1173  if (timelineUtils)
1174  {
1175  // Add Output Workload to the post-optimisation network structure
1176  AddWorkloadStructure(timelineUtils, outputWorkload, layer);
1177  timelineUtils->Commit();
1178  }
1179 
1180  m_OutputQueue.push_back(move(outputWorkload));
1181  }
1182 }
1183 
1184 void LoadedNetwork::AllocateWorkingMemory(
1185 #if !defined(ARMNN_DISABLE_THREADS)
1186  std::lock_guard<std::mutex>& lock
1187 #endif
1188  )
1189 {
1190  ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "Working Memory Allocation");
1191 
1192 #if !defined(ARMNN_DISABLE_THREADS)
1193  // this unused parameter makes sure we can only call this function with a valid lock
1194  IgnoreUnused(lock);
1195 #endif
1196  if (m_IsWorkingMemAllocated)
1197  {
1198  return;
1199  }
1200 
1201  if (m_ExternalMemoryManager)
1202  {
1203  m_ExternalMemoryManager->Allocate();
1204 
1205  for (unsigned int i = 0; i < m_TensorMemory.size(); ++i)
1206  {
1207  m_Tensorhandles[i]->Import(m_TensorMemory[i].first->m_Data, m_TensorMemory[i].second);
1208  }
1209  }
1210 
1211  for (auto&& memoryManager : m_BackendMemoryMangers)
1212  {
1213  if (memoryManager)
1214  {
1215  memoryManager->Acquire();
1216  }
1217  }
1218  m_TensorHandleFactoryRegistry.AquireMemory();
1219  m_IsWorkingMemAllocated = true;
1220 }
1221 
1223 {
1224 #if !defined(ARMNN_DISABLE_THREADS)
1225  std::lock_guard<std::mutex> lockGuard(m_WorkingMemMutex);
1226 #endif
1227 
1228  if (!m_IsWorkingMemAllocated)
1229  {
1230  return;
1231  }
1232 
1233  if (m_ExternalMemoryManager)
1234  {
1235  m_ExternalMemoryManager->Deallocate();
1236  }
1237 
1238  // Informs the memory managers to release memory in its respective memory group
1239  for (auto&& memoryManager : m_BackendMemoryMangers)
1240  {
1241  if (memoryManager)
1242  {
1243  memoryManager->Release();
1244  }
1245  }
1246  m_TensorHandleFactoryRegistry.ReleaseMemory();
1247  m_IsWorkingMemAllocated = false;
1248 }
1249 
1250 bool LoadedNetwork::Execute(std::unique_ptr<TimelineUtilityMethods>& timelineUtils,
1251  ProfilingGuid inferenceGuid)
1252 {
1253  bool success = true;
1254 
1255  auto Fail = [&](const std::exception& error)
1256  {
1257  ARMNN_LOG(error) << "An error occurred attempting to execute a workload: " << error.what();
1258  success = false;
1259  };
1260 
1261  try
1262  {
1263 #if !defined(ARMNN_DISABLE_THREADS)
1264  std::lock_guard<std::mutex> lockGuard(m_WorkingMemMutex);
1265  AllocateWorkingMemory(lockGuard);
1266 #else
1267  AllocateWorkingMemory();
1268 #endif
1269 
1270  ProfilingDynamicGuid workloadInferenceID(0);
1271  auto ExecuteQueue = [&timelineUtils, &workloadInferenceID, &inferenceGuid](WorkloadQueue& queue)
1272  {
1273  for (auto& workload : queue)
1274  {
1275  if(timelineUtils)
1276  {
1277  workloadInferenceID = timelineUtils->RecordWorkloadInferenceAndStartOfLifeEvent(workload->GetGuid(),
1278  inferenceGuid);
1279  }
1280  workload->Execute();
1281  if(timelineUtils)
1282  {
1283  timelineUtils->RecordEndOfLifeEvent(workloadInferenceID);
1284  }
1285  }
1286  };
1287 
1288  ExecuteQueue(m_InputQueue);
1289  ExecuteQueue(m_WorkloadQueue);
1290  ExecuteQueue(m_OutputQueue);
1291  }
1292  catch (const RuntimeException& error)
1293  {
1294  Fail(error);
1295  }
1296  catch (const std::runtime_error& error)
1297  {
1298  Fail(error);
1299  }
1300 
1301  return success;
1302 }
1303 
1304 void LoadedNetwork::EnqueueInput(const ConstTensor& inputTensor, ITensorHandle* inputTensorHandle)
1305 {
1306  if (m_NetworkProperties.m_ImportEnabled) // Try import the input tensor
1307  {
1308  MemorySourceFlags importFlags = inputTensorHandle->GetImportFlags();
1309  if (CheckFlag(importFlags, m_NetworkProperties.m_InputSource) )
1310  {
1311  std::unique_ptr<ITensorHandle> tensorHandle =
1312  std::make_unique<ConstPassthroughTensorHandle>(inputTensor.GetInfo(),
1313  inputTensor.GetMemoryArea());
1314  void* mem = tensorHandle->Map(false);
1315 
1316  if (inputTensorHandle->Import(mem, m_NetworkProperties.m_InputSource))
1317  {
1318  tensorHandle->Unmap();
1319  return;
1320  }
1321  tensorHandle->Unmap();
1322  throw MemoryImportException("EnqueueInput: Memory Import failed");
1323  }
1324  else
1325  {
1326  throw MemoryImportException("EnqueueInput: Memory Import failed, backend does not support Import");
1327  }
1328  }
1329  else
1330  {
1331  std::unique_ptr<ITensorHandle> tensorHandle =
1332  std::make_unique<ConstPassthroughTensorHandle>(inputTensor.GetInfo(), inputTensor.GetMemoryArea());
1333 
1334  auto copyFunc = [](void* dst, const void* src, size_t size)
1335  {
1336  memcpy(dst, src, size);
1337  };
1338 
1339  CopyTensorContentsGeneric(tensorHandle.get(), inputTensorHandle, copyFunc);
1340  }
1341 }
1342 
1343 // Note: We can only import the output pointer if all of the following hold true:
1344 // a) The imported pointer is aligned sufficiently
1345 // b) The tensor has zero padding
1346 // c) There is only one connection to the OutputSlot and it is to an OutputLayer.
1347 // d) The output pointer is allocated via malloc. (Other types will be supported in a later release)
1348 // e) m_IsExportEnabled must be set to true
1349 void LoadedNetwork::ImportOutputTensor(const Tensor& outputTensor, ITensorHandle* outputTensorHandle)
1350 {
1351  ARMNN_ASSERT_MSG(outputTensorHandle != nullptr, "Data should have been allocated.");
1352  MemorySourceFlags importFlags = outputTensorHandle->GetImportFlags();
1353  if (CheckFlag(importFlags, m_NetworkProperties.m_OutputSource))
1354  {
1355  std::unique_ptr<ITensorHandle> tensorHandle =
1356  std::make_unique<PassthroughTensorHandle>(outputTensor.GetInfo(),
1357  outputTensor.GetMemoryArea());
1358 
1359  void* mem = tensorHandle->Map(false);
1360  bool importOk = outputTensorHandle->Import(mem, m_NetworkProperties.m_OutputSource);
1361  tensorHandle->Unmap();
1362 
1363  if (!importOk)
1364  {
1365  throw MemoryExportException("ImportOutputTensor: Memory Export failed");
1366  }
1367  }
1368  else
1369  {
1370  throw MemoryExportException("ImportOutputTensor: Memory Export failed, attempting to export Input Layer");
1371  }
1372 
1373 }
1374 
1375 void CopyToOutputTensor(const Tensor& outputTensor, ITensorHandle* outputTensorHandle)
1376 {
1377  auto copyFunc = [](void* dst, const void* src, size_t size)
1378  {
1379  memcpy(dst, src, size);
1380  };
1381 
1382  std::unique_ptr<ITensorHandle> tensorHandle =
1383  std::make_unique<PassthroughTensorHandle>(outputTensor.GetInfo(),
1384  outputTensor.GetMemoryArea());
1385 
1386  CopyTensorContentsGeneric(outputTensorHandle, tensorHandle.get(), copyFunc);
1387 }
1388 
1389 
1390 const armnn::ConstTensor GetInputTensor(const LayerBindingId layerId, const InputTensors& inputTensors)
1391 {
1392  for (auto inputTensorPair : inputTensors)
1393  {
1394  LayerBindingId id = inputTensorPair.first;
1395  if (id == layerId)
1396  {
1397  return inputTensorPair.second;
1398  }
1399  }
1400  throw InvalidArgumentException("Input does not exist.");
1401 }
1402 
1403 const armnn::Tensor GetOutputTensor(const LayerBindingId layerId, const OutputTensors& outputTensors)
1404 {
1405  for (auto outputTensorPair : outputTensors)
1406  {
1407  LayerBindingId id = outputTensorPair.first;
1408  if (id == layerId)
1409  {
1410  return outputTensorPair.second;
1411  }
1412  }
1413  throw InvalidArgumentException("Output does not exist.");
1414 }
1415 
1416 std::vector<ImportedInputId> LoadedNetwork::ImportInputs(const InputTensors& inputTensors,
1417  MemorySource forceImportMemorySource)
1418 {
1419  if (!m_NetworkProperties.m_AsyncEnabled)
1420  {
1421  // Cannot import if import is not enabled and forceImportMemorySource is undefined
1422  if (forceImportMemorySource == MemorySource::Undefined)
1423  {
1424  throw MemoryImportException("ImportInputs: Memory Import failed, NetworkProperties.m_ImportEnabled");
1425  }
1426  // The number of pre imported tensors should not exceed the number of inputs.
1427  if (inputTensors.size() > m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().GetNumInputs())
1428  {
1429  throw MemoryImportException("ImportInputs: The number of tensors provided exceeds the number of inputs.");
1430  }
1431 
1432  std::vector<ImportedInputId> importedInputs;
1433  Graph& graph = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().TopologicalSort();
1434  unsigned int inputIndex = 0;
1435  for (const BindableLayer* inputLayer : graph.GetInputLayers())
1436  {
1437  auto outputTensorHandle = m_PreImportedInputHandles[inputIndex].m_TensorHandle.get();
1438 
1439  if (!outputTensorHandle)
1440  {
1441  inputIndex++;
1442  continue;
1443  }
1444 
1445  auto layerBindingId = inputLayer->GetBindingId();
1446  auto it = std::find_if(inputTensors.begin(), inputTensors.end(), [=](const auto& inputTensor)
1447  {
1448  return inputTensor.first == layerBindingId;
1449  });
1450 
1451  if (it == inputTensors.end())
1452  {
1453  inputIndex++;
1454  continue;
1455  }
1456 
1457  const auto& inputTensor = *it;
1458  std::unique_ptr<ITensorHandle> passThroughTensorHandle =
1459  std::make_unique<ConstPassthroughTensorHandle>(inputTensor.second.GetInfo(),
1460  inputTensor.second.GetMemoryArea());
1461 
1462  try
1463  {
1464  if (outputTensorHandle->CanBeImported(passThroughTensorHandle->Map(), forceImportMemorySource)
1465  && (outputTensorHandle->Import(passThroughTensorHandle->Map(), forceImportMemorySource)))
1466  {
1467  importedInputs.push_back(inputIndex);
1468  }
1469  passThroughTensorHandle->Unmap();
1470  }
1471  catch(const MemoryImportException& exception)
1472  {
1473  ARMNN_LOG(error) << "An error occurred attempting to import input_"
1474  << inputIndex << " : " << exception.what();
1475  passThroughTensorHandle->Unmap();
1476  }
1477  inputIndex++;
1478  }
1479 
1480  return importedInputs;
1481  }
1482  else
1483  {
1484  // Import when the import of network properties is enabled
1485  std::vector<ImportedInputId> importedInputs;
1486  Graph& graph = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().TopologicalSort();
1487 
1488  for (auto inputTensor : inputTensors)
1489  {
1490  auto layerBindingId = inputTensor.first;
1491  auto it = std::find_if(graph.GetInputLayers().begin(), graph.GetInputLayers().end(), [=](auto* layer)
1492  {
1493  return layer->GetBindingId() == layerBindingId;
1494  });
1495 
1496  if (it == graph.GetInputLayers().end())
1497  {
1498  throw MemoryImportException(fmt::format(
1499  "ImportInputs: Memory Import failed, unknown LayerBindingId: {}", layerBindingId));
1500  }
1501 
1502  const Layer* layer = *it;
1503  if (layer->GetType() != LayerType::Input)
1504  {
1505  throw InvalidArgumentException("ImportInputs: given layer not an InputLayer");
1506  }
1507 
1508  auto& backend = m_Backends.at(layer->GetBackendId());
1509  if (!HasCapability(BackendOptions::BackendOption{"PreImportIOTensors", true}, backend->GetCapabilities()))
1510  {
1511  std::string er = backend->GetId();
1512  er += " does not have PreImportIOTensors capability";
1513  throw BackendCapabilityException(er);
1514  }
1515 
1516  const OutputSlot& outputSlot = layer->GetOutputSlots()[0];
1517 
1519  const TensorInfo& tensorInfo = outputSlot.GetTensorInfo();
1520 
1521  ITensorHandleFactory* handleFactory = m_TensorHandleFactoryRegistry.GetFactory(factoryId);
1522  ARMNN_ASSERT(handleFactory);
1523 
1524  ImportedTensorHandlePin importedTensorHandlePin{layerBindingId,
1525  handleFactory->CreateTensorHandle(tensorInfo, false)};
1526 
1527  ITensorHandle* tensorHandle = importedTensorHandlePin.m_TensorHandle.get();
1528 
1529  if (!CheckFlag(tensorHandle->GetImportFlags(), forceImportMemorySource))
1530  {
1531  throw MemoryImportException(
1532  fmt::format("ImportInputs: Memory Import failed, backend: "
1533  "{} does not support importing from source {}"
1534  , factoryId, m_NetworkProperties.m_InputSource));
1535  }
1536 
1537  std::unique_ptr<ITensorHandle> passThroughTensorHandle =
1538  std::make_unique<ConstPassthroughTensorHandle>(inputTensor.second.GetInfo(),
1539  inputTensor.second.GetMemoryArea());
1540 
1541  if (tensorHandle->Import(passThroughTensorHandle->Map(), forceImportMemorySource))
1542  {
1543  importedInputs.push_back(m_CurImportedInputId++);
1544  passThroughTensorHandle->Unmap();
1545  }
1546  else
1547  {
1548  passThroughTensorHandle->Unmap();
1549  throw MemoryImportException("ImportInputs: Memory Import failed");
1550  }
1551 
1552  m_PreImportedInputHandles.push_back(std::move(importedTensorHandlePin));
1553  }
1554  return importedInputs;
1555  }
1556 }
1557 
1558 std::vector<ImportedOutputId> LoadedNetwork::ImportOutputs(const OutputTensors& outputTensors,
1559  MemorySource forceImportMemorySource)
1560 {
1561  if (!m_NetworkProperties.m_AsyncEnabled)
1562  {
1563  // Cannot import if import is not enabled and forceImportMemorySource is undefined
1564  if (forceImportMemorySource == MemorySource::Undefined)
1565  {
1566  throw MemoryImportException("ImportOutputs: Memory Import failed, NetworkProperties.m_ImportEnabled");
1567  }
1568  // If forceImportMemorySource is defined, try import if memory is aligned
1569  if (outputTensors.size() != m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().GetNumOutputs())
1570  {
1571  throw MemoryImportException("ImportOutputs: Force Import failed, incorrect number of tensors");
1572  }
1573  std::vector<ImportedOutputId> importedOutputs;
1574  Graph& graph = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().TopologicalSort();
1575 
1576  unsigned int outputIndex = 0;
1577  for (const BindableLayer* const outputLayer : graph.GetOutputLayers())
1578  {
1579  auto inputTensorHandle = m_PreImportedOutputHandles[outputIndex].m_TensorHandle.get();
1580  if (!inputTensorHandle)
1581  {
1582  outputIndex++;
1583  continue;
1584  }
1585 
1586  auto layerBindingId = outputLayer->GetBindingId();
1587  auto it = std::find_if(outputTensors.begin(), outputTensors.end(), [=] (const auto& outputTensor)
1588  {
1589  return outputTensor.first == layerBindingId;
1590  });
1591 
1592  if (it == outputTensors.end())
1593  {
1594  outputIndex++;
1595  continue;
1596  }
1597 
1598  const auto outputTensor = *it;
1599  try
1600  {
1601  // Check if the output memory can be imported
1602  if (inputTensorHandle->CanBeImported(outputTensor.second.GetMemoryArea(), forceImportMemorySource)
1603  && inputTensorHandle->Import(outputTensor.second.GetMemoryArea(), forceImportMemorySource))
1604  {
1605  importedOutputs.push_back(outputIndex);
1606  }
1607  }
1608  catch(const MemoryImportException& exception)
1609  {
1610  ARMNN_LOG(error) << "An error occurred attempting to import output_"
1611  << outputIndex << " : " << exception.what();
1612  }
1613  outputIndex++;
1614  }
1615  return importedOutputs;
1616  }
1617 
1618  std::vector<ImportedOutputId> importedOutputs;
1619  Graph& graph = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().TopologicalSort();
1620 
1621  for (const auto& outputTensor : outputTensors)
1622  {
1623  auto layerBindingId = outputTensor.first;
1624  auto it = std::find_if(graph.GetOutputLayers().begin(), graph.GetOutputLayers().end(), [=](auto* layer)
1625  {
1626  return layer->GetBindingId() == layerBindingId;
1627  });
1628 
1629  if (it == graph.GetOutputLayers().end())
1630  {
1631  throw MemoryImportException(fmt::format("ImportOutputs: Memory Import failed, unknown LayerBindingId: {}",
1632  layerBindingId));
1633  }
1634 
1635  const Layer* layer = *it;
1636  if (layer->GetType() != LayerType::Output)
1637  {
1638  throw InvalidArgumentException("ImportOutputs: given layer not an OutputLayer");
1639  }
1640 
1641  auto& backend = m_Backends.at(layer->GetBackendId());
1642  if (!HasCapability(BackendOptions::BackendOption{"PreImportIOTensors", true}, backend->GetCapabilities()))
1643  {
1644  std::string er = backend->GetId();
1645  er += " does not have PreImportIOTensors capability";
1646  throw BackendCapabilityException(er);
1647  }
1648 
1649  const InputSlot& inputSlot = layer->GetInputSlots()[0];
1651  const TensorInfo& tensorInfo = inputSlot.GetConnectedOutputSlot()->GetTensorInfo();
1652 
1653  ITensorHandleFactory* handleFactory = m_TensorHandleFactoryRegistry.GetFactory(factoryId);
1654  ARMNN_ASSERT(handleFactory);
1655 
1656  ImportedTensorHandlePin importedTensorHandlePin{layerBindingId,
1657  handleFactory->CreateTensorHandle(tensorInfo, false)};
1658 
1659  ITensorHandle* tensorHandle = importedTensorHandlePin.m_TensorHandle.get();
1660 
1661  if (!CheckFlag(tensorHandle->GetImportFlags(), forceImportMemorySource))
1662  {
1663  throw MemoryImportException(fmt::format("ImportInputs: Memory Import failed, backend: "
1664  "{} does not support importing from source {}"
1665  , factoryId, forceImportMemorySource));
1666  }
1667 
1668  if (tensorHandle->Import(outputTensor.second.GetMemoryArea(), forceImportMemorySource))
1669  {
1670  importedOutputs.push_back(m_CurImportedOutputId++);
1671  }
1672  else
1673  {
1674  throw MemoryImportException("ImportInputs: Memory Import failed");
1675  }
1676 
1677  m_PreImportedOutputHandles.push_back(std::move(importedTensorHandlePin));
1678  }
1679 
1680  return importedOutputs;
1681 }
1682 
1683 void LoadedNetwork::ClearImportedInputs(const std::vector<ImportedInputId> inputIds)
1684 {
1685  for (auto id : inputIds)
1686  {
1687  if (id > m_PreImportedInputHandles.size())
1688  {
1689  throw InvalidArgumentException(fmt::format("ClearImportedInputs::Unknown ImportedInputId: {}", id));
1690  }
1691 
1692  auto& importedTensorHandle = m_PreImportedInputHandles[id].m_TensorHandle;
1693  if (!importedTensorHandle)
1694  {
1696  fmt::format("ClearImportedInputs::ImportedInput with id: {} has already been deleted", id));
1697  }
1698  // Call Unimport then destroy the tensorHandle
1699  importedTensorHandle->Unimport();
1700  importedTensorHandle = {};
1701  }
1702 }
1703 
1704 void LoadedNetwork::ClearImportedOutputs(const std::vector<ImportedOutputId> outputIds)
1705 {
1706  for (auto id : outputIds)
1707  {
1708  if (id > m_PreImportedOutputHandles.size())
1709  {
1710  throw InvalidArgumentException(fmt::format("ClearImportedOutputs::Unknown ImportedOutputId: {}", id));
1711  }
1712 
1713  auto& importedTensorHandle = m_PreImportedOutputHandles[id].m_TensorHandle;
1714  if (!importedTensorHandle)
1715  {
1717  fmt::format("ClearImportedOutputs::ImportedOutput with id: {} has already been deleted", id));
1718  }
1719  // Call Unimport then destroy the tensorHandle
1720  importedTensorHandle->Unimport();
1721  importedTensorHandle = {};
1722  }
1723 }
1724 
1726  const OutputTensors& outputTensors,
1727  IWorkingMemHandle& iWorkingMemHandle,
1728  std::vector<ImportedInputId> preImportedInputs,
1729  std::vector<ImportedOutputId> preImportedOutputs)
1730 {
1731  const Graph& graph = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph();
1732 
1733  if (inputTensors.size() + preImportedInputs.size() != graph.GetNumInputs())
1734  {
1735  if (preImportedInputs.empty())
1736  {
1737  throw InvalidArgumentException("LoadedNetwork::Execute: Number of inputs provided does not match network.");
1738  }
1739  else
1740  {
1741  throw InvalidArgumentException("LoadedNetwork::Execute: "
1742  "Number of inputs + preImportedInputs provided does not match network.");
1743  }
1744  }
1745 
1746  if (outputTensors.size() + preImportedOutputs.size() != graph.GetNumOutputs())
1747  {
1748  if (preImportedOutputs.empty())
1749  {
1750  throw InvalidArgumentException("LoadedNetwork::Execute: "
1751  "Number of outputs provided does not match network.");
1752  }
1753  else
1754  {
1755  throw InvalidArgumentException("LoadedNetwork::Execute: "
1756  "Number of outputs + preImportedOutputs provided does not match network.");
1757  }
1758  }
1759 
1760  WorkingMemHandle& workingMemHandle = dynamic_cast<WorkingMemHandle&>(iWorkingMemHandle);
1761  // Collect all the given LayerBindingIds and check them for duplicates and unknowns.
1762  std::vector<LayerBindingId>& bindingIds = workingMemHandle.GetBindingIdVector();
1763  unsigned int index = 0;
1764  for (auto pair : inputTensors)
1765  {
1766  bindingIds[index++] = pair.first;
1767  }
1768  for (ImportedInputId id : preImportedInputs)
1769  {
1770  bindingIds[index++] = ValidateImportedInputID(id);
1771  }
1772  for (auto pair : outputTensors)
1773  {
1774  bindingIds[index++] = pair.first;
1775  }
1776  for (ImportedOutputId id : preImportedOutputs)
1777  {
1778  bindingIds[index++] = ValidateImportedOutputID(id);
1779  }
1780 
1781  workingMemHandle.ValidateBindingIds();
1782 
1783  auto resetMemHandle = [&]()
1784  {
1785  for (ImportedInputId id: preImportedInputs)
1786  {
1787  const LayerBindingId layerBindingId = m_PreImportedInputHandles[id].m_LayerBindingId;
1788 
1789  auto inputHandle = workingMemHandle.GetInputHandle(layerBindingId);
1790  auto inputConnections = workingMemHandle.GetInputConnections(layerBindingId);
1791  for (auto it : inputConnections)
1792  {
1793  *it = inputHandle;
1794  }
1795  }
1796 
1797  for (ImportedOutputId id: preImportedOutputs)
1798  {
1799  const LayerBindingId layerBindingId = m_PreImportedOutputHandles[id].m_LayerBindingId;
1800 
1801  auto outputHandle = workingMemHandle.GetOutputHandle(layerBindingId);
1802  auto outputConnections = workingMemHandle.GetOutputConnection(layerBindingId);
1803 
1804  for (auto it : outputConnections)
1805  {
1806  *it = outputHandle;
1807  }
1808  }
1809  };
1810 
1811  std::unique_ptr<TimelineUtilityMethods> timelineUtils =
1812  TimelineUtilityMethods::GetTimelineUtils(*m_ProfilingService);
1813  ProfilingGuid inferenceGuid = m_ProfilingService->GetNextGuid();
1814  if (timelineUtils)
1815  {
1816  // Add inference timeline trace if profiling is enabled.
1817  ProfilingGuid networkGuid = m_OptimizedNetwork->GetGuid();
1818  timelineUtils->CreateTypedEntity(inferenceGuid,LabelsAndEventClasses::INFERENCE_GUID);
1819  timelineUtils->CreateRelationship(ProfilingRelationshipType::RetentionLink,
1820  networkGuid,
1821  inferenceGuid,
1822  LabelsAndEventClasses::EXECUTION_OF_GUID);
1823  timelineUtils->RecordEvent(inferenceGuid,LabelsAndEventClasses::ARMNN_PROFILING_SOL_EVENT_CLASS);
1824  }
1825 
1826  bool executionSucceeded = true;
1827 
1828  if (timelineUtils)
1829  {
1830  // Add end of life of the inference timeline if profiling is enabled.
1831  timelineUtils->RecordEvent(inferenceGuid,LabelsAndEventClasses::ARMNN_PROFILING_EOL_EVENT_CLASS);
1832  timelineUtils->Commit();
1833  }
1834 
1835  if (!workingMemHandle.IsAllocated())
1836  {
1837  workingMemHandle.Allocate();
1838  }
1839 
1840  {
1842  for (auto pair : inputTensors)
1843  {
1844  EnqueueInput(pair.second, workingMemHandle.GetInputHandle(pair.first));
1845  }
1846 
1847  // Swap in the pre-imported inputs if any
1848  for (ImportedInputId id : preImportedInputs)
1849  {
1850  const ImportedTensorHandlePin& importedInputPin = m_PreImportedInputHandles[id];
1851  const LayerBindingId layerBindingId = m_PreImportedInputHandles[id].m_LayerBindingId;
1852  const auto& preimportedHandle = importedInputPin.m_TensorHandle;
1853 
1854  auto inputConnections = workingMemHandle.GetInputConnections(layerBindingId);
1855  for (auto it : inputConnections)
1856  {
1857  *it = preimportedHandle.get();
1858  }
1859  }
1860  }
1861  {
1863  if (m_NetworkProperties.m_ExportEnabled)
1864  {
1865  for (auto pair: outputTensors)
1866  {
1867  ImportOutputTensor(pair.second, workingMemHandle.GetOutputHandle(pair.first));
1868  }
1869  }
1870 
1871  for (ImportedOutputId id : preImportedOutputs)
1872  {
1873  const ImportedTensorHandlePin& importedOutputPin = m_PreImportedOutputHandles[id];
1874  const LayerBindingId layerBindingId = m_PreImportedOutputHandles[id].m_LayerBindingId;
1875  const auto& preimportedHandle = importedOutputPin.m_TensorHandle;
1876 
1877  auto outputConnections = workingMemHandle.GetOutputConnection(layerBindingId);
1878  for (auto it : outputConnections)
1879  {
1880  *it = preimportedHandle.get();
1881  }
1882  }
1883  }
1884 
1885  auto Fail = [&](const std::exception& error)
1886  {
1887  ARMNN_LOG(error) << "An error occurred attempting to execute a workload: " << error.what();
1888  executionSucceeded = false;
1889  };
1890  ProfilingDynamicGuid workloadInferenceID(0);
1891 
1892  try
1893  {
1894  for (unsigned int i = 0; i < m_WorkloadQueue.size(); ++i)
1895  {
1896  auto& workload = m_WorkloadQueue[i];
1897  if (timelineUtils)
1898  {
1899  workloadInferenceID = timelineUtils->RecordWorkloadInferenceAndStartOfLifeEvent(workload->GetGuid(),
1900  inferenceGuid);
1901  }
1902 
1903  workload->ExecuteAsync(workingMemHandle.GetExecutionDataAt(i).second);
1904 
1905  if (timelineUtils)
1906  {
1907  timelineUtils->RecordEndOfLifeEvent(workloadInferenceID);
1908  }
1909  }
1910  }
1911  catch (const RuntimeException& error)
1912  {
1913  resetMemHandle();
1914  Fail(error);
1915  }
1916  catch (const std::runtime_error& error)
1917  {
1918  resetMemHandle();
1919  Fail(error);
1920  }
1921  catch (...)
1922  {
1923  resetMemHandle();
1924  throw;
1925  }
1926 
1927  if (!m_NetworkProperties.m_ExportEnabled)
1928  {
1929  for (auto pair: outputTensors)
1930  {
1931  CopyToOutputTensor(pair.second, workingMemHandle.GetOutputHandle(pair.first));
1932  }
1933  }
1934  else
1935  {
1936  ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, "SyncMemGeneric_Execute");
1937  workingMemHandle.MemSyncOutputs();
1938  }
1939 
1940  resetMemHandle();
1941 
1942  return executionSucceeded ? Status::Success : Status::Failure;
1943 }
1944 
1945 /// Create a new unique WorkingMemHandle object. Create multiple handles if you wish to have
1946 /// overlapped Execution by calling this function from different threads.
1947 std::unique_ptr<IWorkingMemHandle> LoadedNetwork::CreateWorkingMemHandle(NetworkId networkId)
1948 {
1949  Graph& order = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph();
1950 
1951  // Tensors that will need to be allocated internally within armnn
1952  std::vector<std::unique_ptr<ITensorHandle>> managedTensorHandles;
1953  // Tensors that will be allocated externally by the user
1954  std::vector<std::unique_ptr<ITensorHandle>> unmanagedTensorHandles;
1955 
1956  std::vector<WorkingMemDescriptor> workingMemDescriptors;
1957  std::vector<std::pair<BackendId, ExecutionData>> executionDataVec;
1958 
1959  auto GetTensorHandle = [&](Layer* layer, const OutputSlot& outputSlot)
1960  {
1961  ITensorHandleFactory::FactoryId factoryId = outputSlot.GetTensorHandleFactoryId();
1962  const TensorInfo& tensorInfo = outputSlot.GetTensorInfo();
1963 
1964  if (factoryId == ITensorHandleFactory::LegacyFactoryId)
1965  {
1966  BackendId id = layer->GetBackendId();
1968  return m_WorkloadFactories.at(id)->CreateTensorHandle(tensorInfo, false);
1970  }
1971  else
1972  {
1973  ITensorHandleFactory* handleFactory = m_TensorHandleFactoryRegistry.GetFactory(factoryId);
1974  ARMNN_ASSERT(handleFactory);
1975  return handleFactory->CreateTensorHandle(tensorInfo, false);
1976  }
1977  };
1978 
1979  struct HandleInfo
1980  {
1981  ITensorHandle* m_TensorHandle;
1982 
1983  bool m_IsInputLayerHandle = false;
1984  bool m_IsOutputLayerHandle = false;
1985 
1986  WorkingMemHandle::InputMemDescriptorCoords m_InputMemDescriptorCoords;
1987  WorkingMemHandle::OutputMemDescriptorCoords m_OutputMemDescriptorCoords;
1988  };
1989 
1990  std::unordered_map<const OutputSlot*, HandleInfo> outputToHandleInfoMap;
1991 
1992  unsigned int layerIndex = 0;
1993  for (auto&& layer : order)
1994  {
1995  // Constant layers execution and management is handled during loaded network construction
1996  if (layer->GetType() == LayerType::Constant)
1997  {
1998  continue;
1999  }
2000 
2001  WorkingMemDescriptor workingMemDescriptor;
2002 
2003  bool isMemoryManaged = true;
2004  bool isInputLayer = false;
2005  bool isOutputLayer = false;
2006  bool isConnectedToOutputLayer = false;
2007 
2008  if (layer->GetType() == LayerType::Input || layer->GetType() == LayerType::MemImport)
2009  {
2010  // Input layers/workloads will not be executed so the descriptor is not added to workingMemDescriptors
2011  // However we will still need to manage the tensorHandle
2012  isInputLayer = true;
2013  isMemoryManaged = !m_NetworkProperties.m_ImportEnabled;
2014  }
2015  else if (layer->GetType() == LayerType::Output)
2016  {
2017  isOutputLayer = true;
2018  }
2019 
2020  unsigned int slotIndex = 0;
2021  // Create a tensor handle for each output slot of a layer
2022  // Once we create it, we start managing its lifetime
2023  for (auto& slot : layer->GetOutputSlots())
2024  {
2025  for (unsigned int i = 0; i < slot.GetNumConnections(); ++i)
2026  {
2027  if ((slot.GetConnection(i)->GetOwningLayer().GetType() == LayerType::Output))
2028  {
2029  if (!isConnectedToOutputLayer)
2030  {
2031  isConnectedToOutputLayer = true;
2032  // If Export is enabled disable memory management, so we can export, otherwise we do a copy
2033  isMemoryManaged = !m_NetworkProperties.m_ExportEnabled;
2034  }
2035  else
2036  {
2037  // Importing in this case would likely cause unexpected behaviour, so we disallow it.
2038  ARMNN_LOG(warning) <<
2039  fmt::format("Layer name: '{0}' guid: '{1}' has two or more OutputLayers connected to it. "
2040  "This will prevent importing on the connected OutputLayers.",
2041  layer->GetName(), layer->GetGuid());
2042  isMemoryManaged = true;
2043  }
2044  }
2045  }
2046 
2047  ITensorHandle* tensorHandle;
2048  if (isMemoryManaged)
2049  {
2050  managedTensorHandles.emplace_back(GetTensorHandle(layer, slot));
2051  tensorHandle = managedTensorHandles.back().get();
2052  }
2053  else
2054  {
2055  unmanagedTensorHandles.emplace_back(GetTensorHandle(layer, slot));
2056  tensorHandle = unmanagedTensorHandles.back().get();
2057  }
2058 
2059  workingMemDescriptor.m_Outputs.push_back(tensorHandle);
2060 
2061  HandleInfo& handleInfo = outputToHandleInfoMap[&slot];
2062  handleInfo.m_TensorHandle = tensorHandle;
2063 
2064  // Store the coordinates of the current layer's OutputSlot that is connected to the OutputLayer
2065  if (isConnectedToOutputLayer)
2066  {
2067  handleInfo.m_IsOutputLayerHandle = true;
2068  handleInfo.m_OutputMemDescriptorCoords.m_OutputSlotCoords = {layerIndex, slotIndex};
2069  }
2070  // Store the LayerBindingId of the InputLayer
2071  if (isInputLayer)
2072  {
2073  handleInfo.m_IsInputLayerHandle = true;
2074  LayerBindingId bindingId = static_cast<BindableLayer*>(layer)->GetBindingId();
2075  handleInfo.m_InputMemDescriptorCoords.m_LayerBindingId = bindingId;
2076  }
2077  slotIndex++;
2078  }
2079  // Loop through the input slots in the same layer and decrement the reference counter associated
2080  // to each tensor handle we encounter.
2081  // Once it reaches zero, the lifetime of the tensor handle has ended, and we mark its memory as available
2082  // so that the next tensor handle with a non overlapping lifetime can share its memory.
2083  for (auto& slot : layer->GetInputSlots())
2084  {
2085  ARMNN_ASSERT(slot.GetConnection());
2086  auto outputSlot = slot.GetConnectedOutputSlot();
2087  auto key = outputSlot->GetOwningLayer().GetGuid();
2088 
2089  // Constant layers execution and management is handled during loaded network construction
2090  auto found = m_ConstantTensorHandles.find(key);
2091  if (found != m_ConstantTensorHandles.end())
2092  {
2093  ITensorHandle* tensorHandle = found->second;
2094  workingMemDescriptor.m_Inputs.push_back(tensorHandle);
2095 
2096  // Odd case where a constant layer is connected to an output layer
2097  // We will need to create a HandleInfo to track it
2098  if (isOutputLayer)
2099  {
2100  LayerBindingId bindingId = static_cast<BindableLayer*>(layer)->GetBindingId();
2101 
2102  HandleInfo& handleInfo = outputToHandleInfoMap[outputSlot];
2103  handleInfo.m_TensorHandle = tensorHandle;
2104  handleInfo.m_IsOutputLayerHandle = true;
2105  handleInfo.m_OutputMemDescriptorCoords.m_LayerBindingIds.push_back(bindingId);
2106  handleInfo.m_OutputMemDescriptorCoords.m_InputSlotCoords.push_back({layerIndex, 0});
2107  }
2108  continue;
2109  }
2110 
2111  HandleInfo& handleInfo = outputToHandleInfoMap.at(outputSlot);
2112 
2113  ITensorHandle* inputTensorHandle = handleInfo.m_TensorHandle;
2114  workingMemDescriptor.m_Inputs.push_back(inputTensorHandle);
2115 
2116  // Store the LayerBindingId of the OutputLayer
2117  if (isOutputLayer)
2118  {
2119  LayerBindingId bindingId = static_cast<BindableLayer*>(layer)->GetBindingId();
2120  handleInfo.m_OutputMemDescriptorCoords.m_LayerBindingIds.push_back(bindingId);
2121  handleInfo.m_OutputMemDescriptorCoords.m_InputSlotCoords.push_back({layerIndex, 0});
2122  }
2123  // In this case the layer is not an Output Layer but shares its input tensorhandle with an OutputLayer
2124  // It will need to be updated as well, if we swap out the tensorhandle
2125  else if (handleInfo.m_IsOutputLayerHandle)
2126  {
2127  handleInfo.m_OutputMemDescriptorCoords.m_InputSlotCoords.push_back({layerIndex, slot.GetSlotIndex()});
2128  }
2129 
2130  // Store the coordinates of the InputSlots connected to the InputLayer
2131  // There can be more than one InputSlot connected to an InputLayer, so we use a vector
2132  if (handleInfo.m_IsInputLayerHandle)
2133  {
2134  std::pair<LayerGuid, unsigned int> connectionLocation{layerIndex, slot.GetSlotIndex()};
2135  handleInfo.m_InputMemDescriptorCoords.m_InputSlotCoords.emplace_back(connectionLocation);
2136  }
2137  }
2138 
2139  // Input/Output layers/workloads will not be executed, so the descriptor is not added to workingMemDescriptors
2140  // However we will still need to manage the tensorHandle
2141  if (!isInputLayer)
2142  {
2143  // Simply auto initialise ExecutionData here, so it's added only for the layer that require execution.
2144  // The memory and data will be allocated/assigned for the void* in WorkingMemHandle::Allocate.
2145  std::pair<BackendId, ExecutionData> dataPair;
2146  dataPair.first = layer->GetBackendId();
2147 
2148  executionDataVec.push_back(dataPair);
2149  workingMemDescriptors.push_back(workingMemDescriptor);
2150 
2151  layerIndex++;
2152  }
2153  }
2154 
2155  std::vector<std::pair<std::shared_ptr<TensorMemory>, MemorySource>> tensorMemory;
2156 
2157  auto externalMemoryManager = CreateExternalMemoryManger(tensorMemory);
2158 
2159  // Sort m_TensorMemory, so it's order matches the outputSlot order
2160  std::sort(tensorMemory.begin(), tensorMemory.end(),
2161  [](const std::pair<std::shared_ptr<TensorMemory>, MemorySource>& lhs,
2162  const std::pair<std::shared_ptr<TensorMemory>, MemorySource>& rhs)
2163  {
2164  return lhs.first->m_OutputSlotId < rhs.first->m_OutputSlotId;
2165  });
2166 
2167  std::vector<WorkingMemHandle::InputMemDescriptorCoords> inputConnectionsInfo;
2168  std::vector<WorkingMemHandle::OutputMemDescriptorCoords> outputConnectionsInfo;
2169 
2170  for (const auto& handleInfo: outputToHandleInfoMap)
2171  {
2172  if (handleInfo.second.m_IsOutputLayerHandle)
2173  {
2174  outputConnectionsInfo.emplace_back(handleInfo.second.m_OutputMemDescriptorCoords);
2175  }
2176 
2177  if (handleInfo.second.m_IsInputLayerHandle)
2178  {
2179  inputConnectionsInfo.emplace_back(handleInfo.second.m_InputMemDescriptorCoords);
2180  }
2181  }
2182 
2183  return std::make_unique<WorkingMemHandle>(networkId,
2184  inputConnectionsInfo,
2185  outputConnectionsInfo,
2186  workingMemDescriptors,
2187  std::move(externalMemoryManager),
2188  std::move(tensorMemory),
2189  std::move(managedTensorHandles),
2190  std::move(unmanagedTensorHandles),
2191  executionDataVec,
2192  &m_Backends);
2193 }
2194 
2196 {
2197  for (auto&& workloadPtr: m_WorkloadQueue)
2198  {
2199  workloadPtr.get()->RegisterDebugCallback(func);
2200  }
2201 }
2202 
2203 
2204 void LoadedNetwork::CreateMemoryProfileAsync()
2205 {
2206  struct PartialBlock
2207  {
2208  unsigned int m_StartOfLife;
2209  unsigned int m_Lifetime;
2210 
2211  size_t m_MemSize;
2212  unsigned int m_Index;
2213 
2214  BackendId m_BackendId;
2215  };
2216 
2217  auto align = [](size_t numToAlign)
2218  {
2219  const size_t alignment = sizeof(float);
2220  return ((numToAlign + alignment - 1) / alignment) * alignment;
2221  };
2222 
2223  std::unordered_map<const OutputSlot*, PartialBlock> memBlockTrackerMap;
2224 
2225  const bool inputImportingEnabled = m_NetworkProperties.m_InputSource != MemorySource::Undefined;
2226  const bool outputImportingEnabled = m_NetworkProperties.m_OutputSource != MemorySource::Undefined;
2227 
2228  unsigned int timestep = 0;
2229  unsigned int outputIndex = 0;
2230  Graph& order = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().TopologicalSort();
2231 
2232  for (auto&& layer : order)
2233  {
2234  const LayerType& layerType = layer->GetType();
2235  // Don't manage memory if importing.
2236  if (layerType == LayerType::Input && inputImportingEnabled)
2237  {
2238  continue;
2239  }
2240  // Don't manage memory if importing.
2241  if (layerType == LayerType::Output && outputImportingEnabled
2242  && layer->GetInputSlot(0).GetConnectedOutputSlot()->GetNumConnections() == 1)
2243  {
2244  continue;
2245  }
2246  // Because Constant Layer memory can not be shared, the memory must persist for the lifetime of execution,
2247  // management is done separately.
2248  if (layerType == LayerType::Constant)
2249  {
2250  continue;
2251  }
2252 
2253  BackendId backendId = layer->GetBackendId();
2254  for (auto& outputSlot : layer->GetOutputSlots())
2255  {
2256  if (!m_SupportsExternallyManagedMemory[backendId])
2257  {
2258  continue;
2259  }
2260 
2261  PartialBlock partialBlock;
2262 
2263  partialBlock.m_StartOfLife = timestep;
2264 
2265  size_t alignedSize = align(outputSlot.GetOutputHandler().GetTensorInfo().GetNumBytes());
2266  partialBlock.m_MemSize = alignedSize;
2267  partialBlock.m_Index = outputIndex++;
2268  partialBlock.m_Lifetime = outputSlot.GetNumConnections();
2269  partialBlock.m_BackendId = backendId;
2270 
2271  if (partialBlock.m_Lifetime == 0)
2272  {
2273  m_MemBlockMap[partialBlock.m_BackendId].emplace_back(partialBlock.m_StartOfLife,
2274  partialBlock.m_StartOfLife,
2275  partialBlock.m_MemSize,
2276  0,
2277  partialBlock.m_Index);
2278  }
2279  else
2280  {
2281  memBlockTrackerMap[&outputSlot] = partialBlock;
2282  }
2283  }
2284 
2285  for (auto& inputSlot : layer->GetInputSlots())
2286  {
2287  const Layer& connectedInputLayer = inputSlot.GetConnectedOutputSlot()->GetOwningLayer();
2288  const LayerType& owningLayerType = connectedInputLayer.GetType();
2289 
2290  if (owningLayerType == LayerType::Constant)
2291  {
2292  continue;
2293  }
2294  if (inputImportingEnabled && owningLayerType == LayerType::Input)
2295  {
2296  continue;
2297  }
2298 
2299  auto outputSlot = inputSlot.GetConnectedOutputSlot();
2300 
2301  PartialBlock& partialBlock = memBlockTrackerMap.at(outputSlot);
2302 
2303  auto& lifetime = partialBlock.m_Lifetime;
2304  --lifetime;
2305 
2306  if (lifetime == 0)
2307  {
2308  m_MemBlockMap[partialBlock.m_BackendId].emplace_back(partialBlock.m_StartOfLife,
2309  timestep,
2310  partialBlock.m_MemSize,
2311  0,
2312  partialBlock.m_Index);
2313  }
2314  }
2315  ++timestep;
2316  }
2317 }
2318 
2319 void LoadedNetwork::CreateMemoryProfile()
2320 {
2321  // Finds the first TensorHandle ancestor of a SubTensorHandle. If the ITensorHandle provided
2322  // is a TensorHandle, the function just returns it
2323  auto TraceSubTensorHandleAncestry = [](ITensorHandle* const subTensorHandle)
2324  {
2325  ITensorHandle* ancestor = subTensorHandle;
2326  while (ancestor && ancestor->GetParent())
2327  {
2328  ancestor = ancestor->GetParent();
2329  }
2330  return ancestor;
2331  };
2332 
2333  struct PartialBlock
2334  {
2335  unsigned int m_StartOfLife;
2336  unsigned int m_Lifetime;
2337 
2338  size_t m_MemSize;
2339  unsigned int m_Index;
2340 
2341  BackendId m_BackendId;
2342  };
2343 
2344  auto align = [](size_t numToAlign)
2345  {
2346  const size_t alignment = sizeof(float);
2347  return ((numToAlign + alignment - 1) / alignment) * alignment;
2348  };
2349 
2350  std::unordered_map<ITensorHandle*, PartialBlock> memBlockTrackerMap;
2351 
2352  const bool inputImportingEnabled = m_NetworkProperties.m_InputSource != MemorySource::Undefined;
2353  const bool outputImportingEnabled = m_NetworkProperties.m_OutputSource != MemorySource::Undefined;
2354 
2355  unsigned int timestep = 0;
2356  unsigned int outputIndex = 0;
2357  Graph& order = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().TopologicalSort();
2358 
2359  for (auto&& layer : order)
2360  {
2361  const LayerType& layerType = layer->GetType();
2362  // Don't manage memory if importing.
2363  if (layerType == LayerType::Input && inputImportingEnabled)
2364  {
2365  continue;
2366  }
2367  // Don't manage memory if importing.
2368  if (layerType == LayerType::Output && outputImportingEnabled
2369  && layer->GetInputSlot(0).GetConnectedOutputSlot()->GetNumConnections() == 1)
2370  {
2371  continue;
2372  }
2373  // Because Constant Layer memory can not be shared, the memory must persist for the lifetime of execution,
2374  // management is done separately.
2375  if (layerType == LayerType::Constant)
2376  {
2377  continue;
2378  }
2379 
2380  BackendId backendId = layer->GetBackendId();
2381  for (auto& outputSlot : layer->GetOutputSlots())
2382  {
2383  if (!m_SupportsExternallyManagedMemory[backendId])
2384  {
2385  continue;
2386  }
2387 
2388  ITensorHandle* tensorHandle = outputSlot.GetOutputHandler().GetData();
2389  tensorHandle = TraceSubTensorHandleAncestry(tensorHandle);
2390 
2391  if (memBlockTrackerMap.find(tensorHandle) == memBlockTrackerMap.end())
2392  {
2393  PartialBlock partialBlock;
2394 
2395  partialBlock.m_StartOfLife = timestep;
2396 
2397  size_t alignedSize = align(outputSlot.GetOutputHandler().GetTensorInfo().GetNumBytes());
2398  partialBlock.m_MemSize = alignedSize;
2399  partialBlock.m_Index = outputIndex++;
2400  partialBlock.m_Lifetime = outputSlot.GetNumConnections();
2401  partialBlock.m_BackendId = backendId;
2402 
2403  if (partialBlock.m_Lifetime == 0)
2404  {
2405  m_MemBlockMap[partialBlock.m_BackendId].emplace_back(partialBlock.m_StartOfLife,
2406  partialBlock.m_StartOfLife,
2407  partialBlock.m_MemSize,
2408  0,
2409  partialBlock.m_Index);
2410  }
2411  else
2412  {
2413  memBlockTrackerMap[tensorHandle] = partialBlock;
2414  }
2415  m_Tensorhandles.push_back(tensorHandle);
2416 
2417  }
2418  else
2419  {
2420  memBlockTrackerMap.at(tensorHandle).m_Lifetime += outputSlot.GetNumConnections();
2421  }
2422  }
2423 
2424  for (auto& inputSlot : layer->GetInputSlots())
2425  {
2426  const Layer& connectedInputLayer = inputSlot.GetConnectedOutputSlot()->GetOwningLayer();
2427  const LayerType& owningLayerType = connectedInputLayer.GetType();
2428 
2429  if (owningLayerType == LayerType::Constant)
2430  {
2431  continue;
2432  }
2433  if (inputImportingEnabled && owningLayerType == LayerType::Input)
2434  {
2435  continue;
2436  }
2437  if (!m_SupportsExternallyManagedMemory[connectedInputLayer.GetBackendId()])
2438  {
2439  continue;
2440  }
2441 
2442  auto outputSlot = inputSlot.GetConnectedOutputSlot();
2443 
2444  ITensorHandle* tensorHandle = outputSlot->GetOutputHandler().GetData();
2445  tensorHandle = TraceSubTensorHandleAncestry(tensorHandle);
2446 
2447  PartialBlock& partialBlock = memBlockTrackerMap.at(tensorHandle);
2448 
2449  auto& lifetime = partialBlock.m_Lifetime;
2450  --lifetime;
2451 
2452  if (lifetime == 0)
2453  {
2454  m_MemBlockMap[partialBlock.m_BackendId].emplace_back(partialBlock.m_StartOfLife,
2455  timestep,
2456  partialBlock.m_MemSize,
2457  0,
2458  partialBlock.m_Index);
2459  }
2460  }
2461  ++timestep;
2462  }
2463 
2464 }
2465 
2466 std::unique_ptr<MemoryManager> LoadedNetwork::CreateExternalMemoryManger(
2467  std::vector<std::pair<std::shared_ptr<TensorMemory>, MemorySource>>& tensorMemoryVec)
2468 {
2469  std::unique_ptr<MemoryManager> memoryManager = std::make_unique<MemoryManager>();
2470  auto allocatorMap = BackendRegistryInstance().GetAllocators();
2471 
2472  for (auto& backend : m_MemBinMap)
2473  {
2474  std::vector<BufferStorage> bufferStorageVec;
2475 
2476  std::shared_ptr<ICustomAllocator> backendAllocator;
2477  if (allocatorMap.find(backend.first) != allocatorMap.end())
2478  {
2479  backendAllocator = allocatorMap[backend.first];
2480  }
2481  else
2482  {
2483  backendAllocator = m_Backends[backend.first]->GetDefaultAllocator();
2484  }
2485 
2486  for (auto& memBin : backend.second)
2487  {
2488  BufferStorage bufferStorage;
2489  bufferStorage.m_BufferSize = memBin.m_MemSize;
2490  bufferStorage.m_TensorMemoryVector.reserve(memBin.m_MemBlocks.size());
2491 
2492  for (auto& memBlock : memBin.m_MemBlocks)
2493  {
2494  auto tensorMemory = std::make_shared<TensorMemory>(TensorMemory{memBlock.m_Offset, memBlock.m_Index});
2495 
2496  tensorMemoryVec.emplace_back(tensorMemory, backendAllocator->GetMemorySourceType());
2497  bufferStorage.m_TensorMemoryVector.emplace_back(tensorMemory);
2498  }
2499 
2500  bufferStorageVec.emplace_back(std::move(bufferStorage));
2501  }
2502 
2503  memoryManager->StoreMemToAllocate(bufferStorageVec, backendAllocator, 4);
2504  }
2505 
2506  return memoryManager;
2507 }
2508 
2509 LayerBindingId LoadedNetwork::ValidateImportedInputID(ImportedInputId id)
2510 {
2511  try
2512  {
2513  const auto& importedTensorHandlePin = m_PreImportedInputHandles.at(id);
2514  if (!importedTensorHandlePin.m_TensorHandle)
2515  {
2516  throw InvalidArgumentException(fmt::format("LoadedNetwork::Execute:"
2517  "PreImportedInput: {} has been deleted", id));
2518  }
2519  return importedTensorHandlePin.m_LayerBindingId;
2520  }
2521  catch (const std::out_of_range&)
2522  {
2523  throw InvalidArgumentException(fmt::format("LoadedNetwork::Execute: Unknown ImportedInputId: {}", id));
2524  }
2525 }
2526 
2527 LayerBindingId LoadedNetwork::ValidateImportedOutputID(ImportedOutputId id)
2528 {
2529  try
2530  {
2531  const auto& importedTensorHandlePin = m_PreImportedOutputHandles.at(id);
2532  if (!importedTensorHandlePin.m_TensorHandle)
2533  {
2534  throw InvalidArgumentException(fmt::format("LoadedNetwork::Execute: "
2535  "PreImportedOutput: {} has been deleted", id));
2536  }
2537  return importedTensorHandlePin.m_LayerBindingId;
2538  }
2539  catch (const std::out_of_range&)
2540  {
2541  throw InvalidArgumentException(fmt::format("LoadedNetwork::Execute: Unknown ImportedOutputId: {}", id));
2542  }
2543 }
2544 
2545 }
Status Execute(const InputTensors &inputTensors, const OutputTensors &outputTensors, IWorkingMemHandle &workingMemHandle, std::vector< ImportedInputId > preImportedInputs={}, std::vector< ImportedOutputId > preImportedOutputs={})
Thread safe execution of the loaded network.
std::vector< std::shared_ptr< TensorMemory > > m_TensorMemoryVector
Vector of pointer to .
std::unique_ptr< IWorkingMemHandle > CreateWorkingMemHandle(NetworkId networkId)
Create a new unique WorkingMemHandle object.
bool HasCapability(const std::string &name, const BackendCapabilities &capabilities)
Convenience function to check if a capability exists in a BackendCapabilites struct.
const MemorySource m_InputSource
Definition: IRuntime.hpp:72
virtual bool Import(void *memory, MemorySource source)
Import externally allocated memory.
FactoryFunction GetFactory(const BackendId &id) const
ConstIteratorInputs begin() const
Definition: Graph.hpp:65
std::unique_ptr< IWorkloadFactory > IWorkloadFactoryPtr
unsigned int GetNumInputSlots() const override
Returns the number of connectable input slots.
Definition: Layer.hpp:321
static ProfilerManager & GetInstance()
Definition: Profiling.cpp:593
#define ARMNN_NO_DEPRECATE_WARN_BEGIN
Definition: Deprecated.hpp:33
virtual IMemoryManagerUniquePtr CreateMemoryManager() const
LayerBindingId GetBindingId() const
Definition: Layer.hpp:465
virtual unsigned int GetImportFlags() const
Get flags describing supported import sources.
const armnn::Tensor GetOutputTensor(const LayerBindingId layerId, const OutputTensors &outputTensors)
MemoryOptimizerStrategiesMapRef GetMemoryOptimizerStrategies()
unsigned int ImportedOutputId
Definition: Types.hpp:292
std::pair< BackendId, ExecutionData > & GetExecutionDataAt(unsigned int id) override
Get the ExecutionData at an index.
size_t m_Offset
Number of bytes the value is away from the .m_Buffer.
virtual void Allocate()=0
Indicate to the memory manager that this resource is no longer active.
virtual const char * what() const noexcept override
Definition: Exceptions.cpp:32
TensorInfo GetInputTensorInfo(LayerBindingId layerId) const
#define ARMNN_LOG(severity)
Definition: Logging.hpp:205
size_t m_BufferSize
Total size of the buffer.
ITensorHandle * GetOutputHandle(LayerBindingId layerBindingId) const
BackendRegistry & BackendRegistryInstance()
std::vector< std::pair< LayerBindingId, class ConstTensor > > InputTensors
Definition: Tensor.hpp:392
const ProfilingDetailsMethod m_OutputNetworkDetailsMethod
Definition: IRuntime.hpp:70
unsigned int MemorySourceFlags
MemoryType GetMemoryArea() const
Definition: Tensor.hpp:305
size_t GetNumOutputs() const
Definition: Graph.hpp:188
void CopyToOutputTensor(const Tensor &outputTensor, ITensorHandle *outputTensorHandle)
TensorInfo GetOutputTensorInfo(LayerBindingId layerId) const
Copyright (c) 2021 ARM Limited and Contributors.
void IgnoreUnused(Ts &&...)
const std::vector< InputSlot > & GetInputSlots() const
Definition: Layer.hpp:245
std::vector< ImportedInputId > ImportInputs(const InputTensors &inputTensors, MemorySource forceImportMemorySource=MemorySource::Undefined)
std::function< void(LayerGuid guid, unsigned int slotIndex, ITensorHandle *tensorHandle)> DebugCallbackFunction
Define the type of callback for the Debug layer to call.
Definition: Types.hpp:379
unsigned int GetNumOutputSlots() const override
Returns the number of connectable output slots.
Definition: Layer.hpp:322
int LayerBindingId
Type of identifiers for bindable layers (inputs, outputs).
Definition: Types.hpp:290
#define ARMNN_SCOPED_PROFILING_EVENT(backendId, name)
Definition: Profiling.hpp:220
virtual const BackendId & GetId() const =0
ConstIteratorOutputs begin() const
Definition: Graph.hpp:84
A tensor defined by a TensorInfo (shape and data type) and a mutable backing store.
Definition: Tensor.hpp:319
virtual IWorkloadFactoryPtr CreateWorkloadFactory(const IMemoryManagerSharedPtr &memoryManager=nullptr) const =0
unsigned int GetNumConnections() const override
Definition: Layer.hpp:145
const InputSlot & GetInputSlot(unsigned int index) const override
Get a const input slot handle by slot index.
Definition: Layer.hpp:324
std::vector< TensorInfo > m_InputTensorInfos
const std::vector< std::vector< ITensorHandle * >::iterator > & GetOutputConnection(LayerBindingId layerBindingId) const
#define ARMNN_NO_DEPRECATE_WARN_END
Definition: Deprecated.hpp:34
#define ARMNN_ASSERT_MSG(COND, MSG)
Definition: Assert.hpp:15
bool SupportsTensorAllocatorAPI() const
#define ARMNN_SCOPED_HEAP_PROFILING(TAG)
int NetworkId
Definition: IRuntime.hpp:35
A tensor defined by a TensorInfo (shape and data type) and an immutable backing store.
Definition: Tensor.hpp:327
virtual ITensorHandle * GetParent() const =0
Get the parent tensor if this is a subtensor.
std::vector< std::pair< LayerBindingId, class Tensor > > OutputTensors
Definition: Tensor.hpp:393
const std::string & GetNameStr() const
Definition: Layer.hpp:227
LayerType GetType() const override
Returns the armnn::LayerType of this layer.
Definition: Layer.hpp:273
Status
enumeration
Definition: Types.hpp:42
void SendNetworkStructure(arm::pipe::IProfilingService &profilingService)
const std::vector< std::vector< ITensorHandle * >::iterator > & GetInputConnections(LayerBindingId layerBindingId) const
#define ARMNN_ASSERT(COND)
Definition: Assert.hpp:14
const OutputSlot * GetConnectedOutputSlot() const
Definition: Layer.hpp:56
void ClearImportedInputs(const std::vector< ImportedInputId > inputIds)
std::vector< TensorInfo > m_OutputTensorInfos
void SetLayersOutOfOrder()
Definition: Graph.cpp:655
ITensorHandle * GetData() const
Gets the allocated tensor memory.
std::vector< std::unique_ptr< IWorkload > > WorkloadQueue
const TensorInfo & GetInfo() const
Definition: Tensor.hpp:295
#define CHECK_LOCATION()
Definition: Exceptions.hpp:203
const BackendId & GetBackendId() const
Definition: Layer.hpp:277
void Allocate() override
Allocate the backing memory required for execution.
void ValidateSourcesMatchOptimizedNetwork(std::vector< BackendOptions > optimizedOptions, const INetworkProperties &networkProperties)
This function performs a sanity check to ensure that the combination of input and output memory sourc...
arm::pipe::ProfilingGuid GetNetworkGuid()
const std::vector< OutputSlot > & GetOutputSlots() const
Definition: Layer.hpp:246
virtual bool CanBeImported(void *memory, MemorySource source)
Implementations must determine if this memory block can be imported.
OutputLayersAccessor GetOutputLayers() const
Returns a wrapper object with begin(), end() methods to iterate over the output layers in a range-bas...
Definition: Graph.hpp:196
unsigned int ImportedInputId
Definition: Types.hpp:291
Struct for the users to pass backend specific options.
Status EnqueueWorkload(const InputTensors &inputTensors, const OutputTensors &outputTensors, std::vector< ImportedInputId > preImportedInputIds={}, std::vector< ImportedOutputId > preImportedOutputIds={})
Single thread execution of the loaded network.
void RegisterProfiler(IProfiler *profiler)
Definition: Profiling.cpp:600
virtual const void * Map(bool blocking=true) const =0
Map the tensor data for access.
std::vector< LayerBindingId > & GetBindingIdVector()
std::unordered_map< BackendId, std::shared_ptr< ICustomAllocator > > GetAllocators()
virtual BackendCapabilities GetCapabilities() const
Returns a BackendCapability if the backend lists the capability The BackendCapability must then be in...
virtual void Unmap() const =0
Unmap the tensor data.
bool AsBool() const
Value getters.
bool IsAllocated() override
IsAllocated returns true if the backing memory is currently allocated.
std::vector< ITensorHandle * > m_Outputs
Base class for all ArmNN exceptions so that users can filter to just those.
Definition: Exceptions.hpp:46
const OutputHandler & GetOutputHandler(unsigned int i=0) const
Definition: Layer.hpp:232
std::vector< ImportedOutputId > ImportOutputs(const OutputTensors &outputTensors, MemorySource forceImportMemorySource=MemorySource::Undefined)
MemorySource
Define the Memory Source to reduce copies.
Definition: Types.hpp:230
const std::string & Get() const
Definition: BackendId.hpp:138
void RegisterDebugCallback(const DebugCallbackFunction &func)
ConstIteratorOutputs end() const
Definition: Graph.hpp:90
std::enable_if_t< std::is_unsigned< Source >::value &&std::is_unsigned< Dest >::value, Dest > numeric_cast(Source source)
Definition: NumericCast.hpp:35
const MemorySource m_OutputSource
Definition: IRuntime.hpp:73
Contains information about TensorInfos of a layer.
const char * GetName() const override
Returns the name of the layer.
Definition: Layer.hpp:319
ITensorHandleFactory::FactoryId GetTensorHandleFactoryId() const
Definition: Layer.cpp:205
bool CheckFlag(MemorySourceFlags flags, MemorySource source)
void CopyTensorContentsGeneric(const ITensorHandle *srcTensor, ITensorHandle *dstTensor, CopyFunc copy)
Graph & TopologicalSort()
Sorts layers in topological order and return this.
Definition: Graph.hpp:184
InputLayersAccessor GetInputLayers() const
Returns a wrapper object with begin(), end() methods to iterate over the input layers in a range-base...
Definition: Graph.hpp:192
std::vector< ITensorHandle * > m_Inputs
size_t GetNumLayers() const
Definition: Graph.hpp:198
ConstIteratorInputs end() const
Definition: Graph.hpp:70
const armnn::ConstTensor GetInputTensor(const LayerBindingId layerId, const InputTensors &inputTensors)
const TensorInfo & GetTensorInfo() const override
Definition: Layer.cpp:92
static std::unique_ptr< LoadedNetwork > MakeLoadedNetwork(std::unique_ptr< IOptimizedNetwork > net, std::string &errorMessage, const INetworkProperties &networkProperties, arm::pipe::IProfilingService *profilingService)
ITensorHandle * GetInputHandle(LayerBindingId layerBindingId) const
size_t GetNumInputs() const
Definition: Graph.hpp:187
virtual std::unique_ptr< ITensorHandle > CreateTensorHandle(const TensorInfo &tensorInfo) const =0
static const FactoryId LegacyFactoryId
const bool m_ProfilingEnabled
Definition: IRuntime.hpp:68
void ClearImportedOutputs(const std::vector< ImportedOutputId > outputIds)
const TensorInfo & GetTensorInfo(const ITensorHandle *tensorHandle)
float32 helpers
LayerType
When adding a new layer, adapt also the LastLayer enum value in the enum class LayerType below...
Definition: Types.hpp:468
LayerGuid GetGuid() const final
Returns the unique id of the layer.
Definition: Layer.hpp:330