23 #if !defined(ARMNN_DISABLE_DYNAMIC_BACKENDS)
29 #include <client/include/backends/IBackendProfiling.hpp>
31 #include <common/include/LabelsAndEventClasses.hpp>
36 using namespace armnn;
64 return pRuntimeImpl->LoadNetwork(networkIdOut, std::move(network));
69 std::string& errorMessage)
71 return pRuntimeImpl->LoadNetwork(networkIdOut, std::move(network), errorMessage);
76 std::string& errorMessage,
79 return pRuntimeImpl->LoadNetwork(networkIdOut, std::move(network), errorMessage, networkProperties);
84 return pRuntimeImpl->GetInputTensorInfo(networkId, layerId);
89 return pRuntimeImpl->GetOutputTensorInfo(networkId, layerId);
95 return pRuntimeImpl->ImportInputs(networkId, inputTensors, forceImportMemorySource);
101 return pRuntimeImpl->ImportOutputs(networkId, outputTensors, forceImportMemorySource);
107 std::vector<ImportedInputId> preImportedInputIds,
108 std::vector<ImportedOutputId> preImportedOutputIds)
110 return pRuntimeImpl->EnqueueWorkload(networkId, inputTensors, outputTensors,
111 preImportedInputIds, preImportedOutputIds);
131 return pRuntimeImpl->RegisterDebugCallback(networkId, func);
134 int RuntimeImpl::GenerateNetworkId()
136 return m_NetworkIdCounter++;
141 std::string ignoredErrorMessage;
142 return LoadNetwork(networkIdOut, std::move(inNetwork), ignoredErrorMessage);
147 std::string& errorMessage)
150 return LoadNetwork(networkIdOut, std::move(inNetwork), errorMessage, networkProperties);
155 std::string& errorMessage,
159 auto profiler = inNetwork->GetProfiler();
164 networkIdOut = GenerateNetworkId();
166 for (
auto&& context : m_BackendContexts)
168 context.second->BeforeLoadNetwork(networkIdOut);
172 std::unique_ptr<IOptimizedNetwork>(rawNetwork),
175 m_ProfilingService.get());
183 #if !defined(ARMNN_DISABLE_THREADS)
184 std::lock_guard<std::mutex> lockGuard(m_Mutex);
188 m_LoadedNetworks[networkIdOut] = std::move(loadedNetwork);
191 for (
auto&& context : m_BackendContexts)
193 context.second->AfterLoadNetwork(networkIdOut);
196 if (m_ProfilingService->IsProfilingEnabled())
198 m_ProfilingService->IncrementCounterValue(arm::pipe::NETWORK_LOADS);
206 bool unloadOk =
true;
207 for (
auto&& context : m_BackendContexts)
209 unloadOk &= context.second->BeforeUnloadNetwork(networkId);
215 "network with ID:" << networkId <<
" because BeforeUnloadNetwork failed";
219 std::unique_ptr<arm::pipe::TimelineUtilityMethods> timelineUtils =
220 arm::pipe::TimelineUtilityMethods::GetTimelineUtils(*m_ProfilingService.get());
222 #if !defined(ARMNN_DISABLE_THREADS)
223 std::lock_guard<std::mutex> lockGuard(m_Mutex);
229 auto search = m_LoadedNetworks.find(networkId);
230 if (search != m_LoadedNetworks.end())
232 arm::pipe::ProfilingGuid networkGuid = search->second->GetNetworkGuid();
233 timelineUtils->RecordEvent(networkGuid,
234 arm::pipe::LabelsAndEventClasses::ARMNN_PROFILING_EOL_EVENT_CLASS);
238 if (m_LoadedNetworks.erase(networkId) == 0)
240 ARMNN_LOG(
warning) <<
"WARNING: RuntimeImpl::UnloadNetwork(): " << networkId <<
" not found!";
244 if (m_ProfilingService->IsProfilingEnabled())
246 m_ProfilingService->IncrementCounterValue(arm::pipe::NETWORK_UNLOADS);
250 for (
auto&& context : m_BackendContexts)
252 context.second->AfterUnloadNetwork(networkId);
258 ARMNN_LOG(
debug) <<
"RuntimeImpl::UnloadNetwork(): Unloaded network with ID: " << networkId;
264 auto it = m_LoadedNetworks.find(networkId);
265 if (it != m_LoadedNetworks.end())
267 auto& loadedNetwork = it->second;
268 return loadedNetwork->GetProfiler();
276 if (profilingService.IsProfilingEnabled())
278 LoadedNetworks::iterator it = m_LoadedNetworks.begin();
279 while (it != m_LoadedNetworks.end())
281 auto& loadedNetwork = it->second;
282 loadedNetwork->SendNetworkStructure(profilingService);
296 : m_NetworkIdCounter(0)
298 m_ProfilingService = arm::pipe::IProfilingService::CreateProfilingService(
299 arm::pipe::MAX_ARMNN_COUNTER,
301 arm::pipe::ARMNN_SOFTWARE_INFO,
302 arm::pipe::ARMNN_SOFTWARE_VERSION,
303 arm::pipe::ARMNN_HARDWARE_VERSION,
310 "It is not possible to enable timeline reporting without profiling being enabled");
312 #if !defined(ARMNN_DISABLE_DYNAMIC_BACKENDS)
329 auto backend = factoryFun();
333 customAllocatorMapIterator->second ==
nullptr)
335 #if !defined(ARMNN_DISABLE_DYNAMIC_BACKENDS)
340 throw armnn::Exception(
"Allocator associated with id " +
id.Get() +
" is null");
348 BackendCapability protectedContentCapability {
"ProtectedContentAllocation",
true};
355 <<
" is not registered as does not support protected content allocation.";
363 if (customAllocatorMapIterator->second->GetMemorySourceType()
366 if (!backend->UseCustomMemoryAllocator(customAllocatorMapIterator->second, err))
370 <<
" reported an error when entering protected mode. Backend won't be"
371 <<
" used. ErrorMsg: " << err;
376 m_AllocatorsAddedByThisRuntime.emplace(
id);
380 ARMNN_LOG(
error) <<
"The CustomAllocator provided with the runtime options doesn't support "
381 "protected memory. Protected mode can't be activated. The backend "
383 <<
" is not going to be used. MemorySource must be MemorySource::DmaBufProtected";
389 ARMNN_LOG(
error) <<
"Protected mode can't be activated for backend: "
391 <<
" no custom allocator was provided to the runtime options.";
401 if (!backend->UseCustomMemoryAllocator(customAllocatorMapIterator->second, err))
405 <<
" reported an error when trying to use the provided custom allocator."
406 " Backend won't be used."
407 <<
" ErrorMsg: " << err;
412 m_AllocatorsAddedByThisRuntime.emplace(
id);
425 id, customMemoryOptimizerStrategyMapIterator->second);
428 << customMemoryOptimizerStrategyMapIterator->second->GetName()
429 <<
" set for the backend " <<
id <<
".";
435 std::string memoryOptimizerStrategyName =
"";
438 if (name ==
"MemoryOptimizerStrategy")
440 memoryOptimizerStrategyName = ParseStringBackendOption(value,
"");
443 if (memoryOptimizerStrategyName !=
"")
445 std::shared_ptr<IMemoryOptimizerStrategy> strategy =
450 ARMNN_LOG(
warning) <<
"MemoryOptimizerStrategy: " << memoryOptimizerStrategyName
451 <<
" was not found.";
463 << memoryOptimizerStrategyName <<
" set for the backend " <<
id <<
".";
469 <<
" does not have multi-axis packing capability and cannot support"
470 <<
"MemoryOptimizerStrategy: " << memoryOptimizerStrategyName <<
".";
476 auto context = backend->CreateBackendContext(options);
482 m_BackendContexts.emplace(std::make_pair(
id, std::move(context)));
484 supportedBackends.emplace(
id);
486 unique_ptr<arm::pipe::IBackendProfiling> profilingIface =
487 arm::pipe::IBackendProfiling::CreateBackendProfiling(
489 *m_ProfilingService.get(),
493 auto profilingContext = backend->CreateBackendProfilingContext(options, profilingIface);
495 if (profilingContext)
498 m_ProfilingService->AddBackendProfilingContext(
id, profilingContext);
509 m_ProfilingService->ConfigureProfilingService(
511 if (options.m_ProfilingOptions.m_EnableProfiling)
514 m_ProfilingService->WaitForProfilingServiceActivation(3000);
517 m_DeviceSpec.AddSupportedBackends(supportedBackends);
519 ARMNN_LOG(info) <<
"Initialization time: " << std::setprecision(2)
523 RuntimeImpl::~RuntimeImpl()
526 std::vector<int> networkIDs;
530 std::transform(m_LoadedNetworks.begin(), m_LoadedNetworks.end(),
531 std::back_inserter(networkIDs),
532 [](
const auto &pair) { return pair.first; });
534 catch (
const std::exception& e)
539 std::cerr <<
"WARNING: An error has occurred when getting the IDs of the networks to unload: " << e.what()
540 <<
"\nSome of the loaded networks may not be unloaded" << std::endl;
545 for (
auto networkID : networkIDs)
553 catch (
const std::exception& e)
558 std::cerr <<
"WARNING: An error has occurred when unloading network " << networkID <<
": " << e.what()
562 #if !defined(ARMNN_DISABLE_DYNAMIC_BACKENDS)
567 m_BackendContexts.clear();
573 for_each(m_AllocatorsAddedByThisRuntime.begin(), m_AllocatorsAddedByThisRuntime.end(),
574 [](
BackendId id) {BackendRegistryInstance().DeregisterAllocator(id);});
582 #if !defined(ARMNN_DISABLE_THREADS)
583 std::lock_guard<std::mutex> lockGuard(m_Mutex);
585 return m_LoadedNetworks.at(networkId).get();
601 return GetLoadedNetworkPtr(networkId)->
ImportInputs(inputTensors, forceImportMemorySource);
607 return GetLoadedNetworkPtr(networkId)->
ImportOutputs(outputTensors, forceImportMemorySource);
622 std::vector<ImportedInputId> preImportedInputIds,
623 std::vector<ImportedOutputId> preImportedOutputIds)
627 LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId);
631 ARMNN_LOG(
error) <<
"A Network with an id of " << networkId <<
" does not exist.";
638 static thread_local
NetworkId lastId = networkId;
639 if (lastId != networkId)
648 auto status = loadedNetwork->
EnqueueWorkload(inputTensors, outputTensors,
649 preImportedInputIds, preImportedOutputIds);
652 if (!preImportedInputIds.empty() || !preImportedOutputIds.empty())
655 for (
auto&& context : m_BackendContexts)
657 context.second->AfterEnqueueWorkload(networkId);
660 ARMNN_LOG(
info) <<
"Execution time: " << std::setprecision(2)
667 LoadedNetwork* loadedNetwork = GetLoadedNetworkPtr(networkId);
671 #if !defined(ARMNN_DISABLE_DYNAMIC_BACKENDS)
672 void RuntimeImpl::LoadDynamicBackends(
const std::string& overrideBackendPath)
#define ARMNN_LOG(severity)
#define ARMNN_SCOPED_PROFILING_EVENT(backendId, name)
void InitialiseProfilingService(arm::pipe::IProfilingService &profilingService) override
Very basic type safe variant.
void SetProfilingService(armnn::Optional< arm::pipe::IProfilingService & > profilingService)
void RegisterAllocator(const BackendId &id, std::shared_ptr< ICustomAllocator > alloc)
void RegisterMemoryOptimizerStrategy(const BackendId &id, std::shared_ptr< IMemoryOptimizerStrategy > strategy)
FactoryFunction GetFactory(const BackendId &id) const
Class for non-fatal exceptions raised while initialising a backend.
const BackendIdSet & GetDynamicBackends() const
void AddSupportedBackends(const BackendIdSet &backendIds, bool isDynamic=false)
void ClearDynamicBackends()
static std::vector< DynamicBackendPtr > CreateDynamicBackends(const std::vector< std::string > &sharedObjects)
static std::vector< std::string > GetSharedObjects(const std::vector< std::string > &backendPaths)
static BackendIdSet RegisterDynamicBackends(const std::vector< DynamicBackendPtr > &dynamicBackends)
static std::vector< std::string > GetBackendPaths(const std::string &overrideBackendPath="")
static void DeregisterDynamicBackends(const BackendIdSet &dynamicBackends)
Base class for all ArmNN exceptions so that users can filter to just those.
Device specific knowledge to be passed to the optimizer.
const IDeviceSpec & GetDeviceSpec() const
TensorInfo GetInputTensorInfo(NetworkId networkId, LayerBindingId layerId) const
static IRuntime * CreateRaw(const CreationOptions &options)
TensorInfo GetOutputTensorInfo(NetworkId networkId, LayerBindingId layerId) const
std::vector< ImportedOutputId > ImportOutputs(NetworkId networkId, const OutputTensors &outputTensors, MemorySource forceImportMemorySource=MemorySource::Undefined)
ImportOutputs separates the importing and mapping of OutputTensors from network execution.
std::unique_ptr< RuntimeImpl > pRuntimeImpl
void RegisterDebugCallback(NetworkId networkId, const DebugCallbackFunction &func)
Registers a callback function to debug layers performing custom computations on intermediate tensors.
static void Destroy(IRuntime *runtime)
std::vector< ImportedInputId > ImportInputs(NetworkId networkId, const InputTensors &inputTensors, MemorySource forceImportMemorySource=MemorySource::Undefined)
ImportInputs separates the importing and mapping of InputTensors from network execution.
Status EnqueueWorkload(NetworkId networkId, const InputTensors &inputTensors, const OutputTensors &outputTensors, std::vector< ImportedInputId > preImportedInputIds={}, std::vector< ImportedOutputId > preImportedOutputIds={})
Evaluates a network using input in inputTensors and outputs filled into outputTensors.
static IRuntimePtr Create(const CreationOptions &options)
Status UnloadNetwork(NetworkId networkId)
Unloads a network from the IRuntime.
const std::shared_ptr< IProfiler > GetProfiler(NetworkId networkId) const
Gets the profiler corresponding to the given network id.
Status LoadNetwork(NetworkId &networkIdOut, IOptimizedNetworkPtr network)
Loads a complete network into the IRuntime.
void RegisterDebugCallback(const DebugCallbackFunction &func)
TensorInfo GetOutputTensorInfo(LayerBindingId layerId) const
std::vector< ImportedInputId > ImportInputs(const InputTensors &inputTensors, MemorySource forceImportMemorySource=MemorySource::Undefined)
Status EnqueueWorkload(const InputTensors &inputTensors, const OutputTensors &outputTensors, std::vector< ImportedInputId > preImportedInputIds={}, std::vector< ImportedOutputId > preImportedOutputIds={})
Single thread execution of the loaded network.
void ClearImportedInputs(const std::vector< ImportedInputId > inputIds)
std::vector< ImportedOutputId > ImportOutputs(const OutputTensors &outputTensors, MemorySource forceImportMemorySource=MemorySource::Undefined)
const std::shared_ptr< IProfiler > & GetProfiler() const
void ClearImportedOutputs(const std::vector< ImportedOutputId > outputIds)
TensorInfo GetInputTensorInfo(LayerBindingId layerId) const
static std::unique_ptr< LoadedNetwork > MakeLoadedNetwork(std::unique_ptr< IOptimizedNetwork > net, std::string &errorMessage, const INetworkProperties &networkProperties, arm::pipe::IProfilingService *profilingService)
void RegisterProfiler(IProfiler *profiler)
static ProfilerManager & GetInstance()
#define ARMNN_VERSION
ARMNN_VERSION: "X.Y.Z" where: X = Major version number Y = Minor version number Z = Patch version num...
ProfilingOptions ConvertExternalProfilingOptions(const armnn::IRuntime::CreationOptions::ExternalProfilingOptions &options)
Copyright (c) 2021 ARM Limited and Contributors.
MemorySource
Define the Memory Source to reduce copies.
std::unique_ptr< IRuntime, void(*)(IRuntime *runtime)> IRuntimePtr
std::function< void(LayerGuid guid, unsigned int slotIndex, ITensorHandle *tensorHandle)> DebugCallbackFunction
Define the type of callback for the Debug layer to call.
std::unordered_set< BackendId > BackendIdSet
bool HasMatchingCapability(const BackendOptions::BackendOption &capability, const BackendCapabilities &capabilities)
Convenience function to check if a given capability matches a capability in a BackendCapabilities str...
std::chrono::duration< double, std::milli > GetTimeDuration(std::chrono::high_resolution_clock::time_point start_time)
std::unique_ptr< IOptimizedNetwork, void(*)(IOptimizedNetwork *network)> IOptimizedNetworkPtr
std::unique_ptr< IMemoryOptimizerStrategy > GetMemoryOptimizerStrategy(const std::string &strategyName)
std::vector< std::pair< LayerBindingId, class Tensor > > OutputTensors
std::vector< std::pair< LayerBindingId, class ConstTensor > > InputTensors
constexpr const char * GetMemBlockStrategyTypeName(MemBlockStrategyType memBlockStrategyType)
BackendCapability
BackendCapability class.
int LayerBindingId
Type of identifiers for bindable layers (inputs, outputs).
BackendRegistry & BackendRegistryInstance()
std::chrono::high_resolution_clock::time_point GetTimeNow()
void ParseOptions(const std::vector< BackendOptions > &options, BackendId backend, F f)
EmptyOptional is used to initialize the Optional class in case we want to have default value for an O...
bool m_EnableProfiling
Indicates whether external profiling is enabled or not.
bool m_TimelineEnabled
Indicates whether external timeline profiling is enabled or not.
ExternalProfilingOptions m_ProfilingOptions
std::map< BackendId, std::shared_ptr< IMemoryOptimizerStrategy > > m_MemoryOptimizerStrategyMap
A map to define a custom memory optimizer strategy for specific backend Ids.
std::map< BackendId, std::shared_ptr< ICustomAllocator > > m_CustomAllocatorMap
A map to define a custom memory allocator for specific backend Ids.
bool m_ProtectedMode
Setting this flag will allow the user to create the Runtime in protected mode.
std::string m_DynamicBackendsPath
Setting this value will override the paths set by the DYNAMIC_BACKEND_PATHS compiler directive Only a...
std::vector< BackendOptions > m_BackendOptions
Pass backend specific options.
RuntimeImpl(const IRuntime::CreationOptions &options)
Creates a runtime for workload execution.
void ReportStructure(arm::pipe::IProfilingService &profilingService) override
void ClearImportedOutputs(NetworkId networkId, const std::vector< ImportedOutputId > outputIds)
std::vector< ImportedOutputId > ImportOutputs(NetworkId networkId, const OutputTensors &outputTensors, MemorySource forceImportMemorySource)
armnn::TensorInfo GetOutputTensorInfo(NetworkId networkId, LayerBindingId layerId) const
void RegisterDebugCallback(NetworkId networkId, const DebugCallbackFunction &func)
Registers a callback function to debug layers performing custom computations on intermediate tensors.
std::vector< ImportedInputId > ImportInputs(NetworkId networkId, const InputTensors &inputTensors, MemorySource forceImportMemorySource)
armnn::TensorInfo GetInputTensorInfo(NetworkId networkId, LayerBindingId layerId) const
void ClearImportedInputs(NetworkId networkId, const std::vector< ImportedInputId > inputIds)
Status EnqueueWorkload(NetworkId networkId, const InputTensors &inputTensors, const OutputTensors &outputTensors, std::vector< ImportedInputId > preImportedInputIds={}, std::vector< ImportedOutputId > preImportedOutputIds={})
void InitialiseProfilingService(arm::pipe::IProfilingService &profilingService) override
Status UnloadNetwork(NetworkId networkId)
Unloads a network from the Runtime.
const std::shared_ptr< IProfiler > GetProfiler(NetworkId networkId) const
Gets the profiler corresponding to the given network id.
Status LoadNetwork(NetworkId &networkIdOut, IOptimizedNetworkPtr network)
Loads a complete network into the Runtime.