ArmNN
 22.02
IRuntime.hpp
Go to the documentation of this file.
1 //
2 // Copyright © 2017 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5 #pragma once
6 
7 #include "BackendOptions.hpp"
8 #include "INetwork.hpp"
9 #include "IProfiler.hpp"
10 #include "IWorkingMemHandle.hpp"
12 #include "Tensor.hpp"
13 #include "Types.hpp"
14 #include "TypesUtils.hpp"
16 
19 #include <memory>
20 #include <map>
21 
22 namespace armnn
23 {
24 
25 using NetworkId = int;
26 
28 
29 struct RuntimeImpl;
30 class IRuntime;
31 using IRuntimePtr = std::unique_ptr<IRuntime, void(*)(IRuntime* runtime)>;
32 
34 {
35  INetworkProperties(bool asyncEnabled,
36  MemorySource inputSource,
37  MemorySource outputSource,
38  bool profilingEnabled = false,
40  bool externalMemoryManagementEnabled = false)
41  : m_ImportEnabled(inputSource != MemorySource::Undefined),
42  m_ExportEnabled(outputSource != MemorySource::Undefined),
43  m_AsyncEnabled(asyncEnabled),
44  m_ProfilingEnabled(profilingEnabled),
45  m_OutputNetworkDetailsMethod(detailsMethod),
46  m_InputSource(inputSource),
47  m_OutputSource(outputSource),
48  m_ExternalMemoryManagementEnabled(externalMemoryManagementEnabled)
49  {}
50 
51  /// Deprecated and will be removed in future release.
52  const bool m_ImportEnabled;
53  /// Deprecated and will be removed in future release.
54  const bool m_ExportEnabled;
55 
56  const bool m_AsyncEnabled;
57 
58  const bool m_ProfilingEnabled;
59 
61 
64 
66 
67  virtual ~INetworkProperties() {}
68 };
69 
70 using namespace armnn::experimental;
71 
72 class IRuntime
73 {
74 public:
76  {
78  : m_GpuAccTunedParameters(nullptr)
79  , m_EnableGpuProfiling(false)
80  , m_DynamicBackendsPath("")
81  , m_ProtectedMode(false)
82  , m_CustomAllocatorMap()
83  , m_MemoryOptimizerStrategyMap()
84  {}
85 
86  /// If set, uses the GpuAcc tuned parameters from the given object when executing GPU workloads.
87  /// It will also be updated with new tuned parameters if it is configured to do so.
88  std::shared_ptr<IGpuAccTunedParameters> m_GpuAccTunedParameters;
89 
90  /// Setting this flag will allow the user to obtain GPU profiling information from the runtime.
92 
93  /// Setting this value will override the paths set by the DYNAMIC_BACKEND_PATHS compiler directive
94  /// Only a single path is allowed for the override
95  /// It defines the path to search for any [dynamic backend libraries](src/dynamic/README.md).
96  std::string m_DynamicBackendsPath;
97 
98  /// Setting this flag will allow the user to create the Runtime in protected mode.
99  /// It will run all the inferences on protected memory and will make sure that
100  /// INetworkProperties::m_ImportEnabled set to true with MemorySource::DmaBufProtected option
101  /// This requires that the backend supports Protected Memory and has an allocator capable of
102  /// allocating Protected Memory associated with it.
104 
105  /// @brief A map to define a custom memory allocator for specific backend Ids.
106  ///
107  /// @details A Custom Allocator is used for allocation of working memory in the backends.
108  /// Set this if you need to take control of how memory is allocated on a backend. Required for
109  /// Protected Mode in order to correctly allocate Protected Memory
110  ///
111  /// @note Only supported for GpuAcc
112  std::map<BackendId, std::shared_ptr<ICustomAllocator>> m_CustomAllocatorMap;
113 
114  /// @brief A map to define a custom memory optimizer strategy for specific backend Ids.
115  ///
116  /// @details A Memory Optimizer Strategy provides a solution to an abstract representation of
117  /// a network's memory requirements. This can also be used to return a pre-computed solution
118  /// for a specific network. Set this if you want to implement a Custom Memory Optimizer Strategy
119  /// for a given backend.
120  std::map<BackendId, std::shared_ptr<IMemoryOptimizerStrategy>> m_MemoryOptimizerStrategyMap;
121 
123  {
125  : m_EnableProfiling(false)
126  , m_TimelineEnabled(false)
127  , m_OutgoingCaptureFile("")
128  , m_IncomingCaptureFile("")
129  , m_FileOnly(false)
130  , m_CapturePeriod(LOWEST_CAPTURE_PERIOD)
131  , m_FileFormat("binary")
132  , m_LocalPacketHandlers()
133  {}
134 
135  /// Indicates whether external profiling is enabled or not.
137  /// Indicates whether external timeline profiling is enabled or not.
139  /// Path to a file in which outgoing timeline profiling messages will be stored.
141  /// Path to a file in which incoming timeline profiling messages will be stored.
143  /// Enable profiling output to file only.
145  /// The duration at which captured profiling messages will be flushed.
146  uint32_t m_CapturePeriod;
147  /// The format of the file used for outputting profiling data.
148  std::string m_FileFormat;
149  std::vector<armnn::profiling::ILocalPacketHandlerSharedPtr> m_LocalPacketHandlers;
150  };
152 
153  /// Pass backend specific options.
154  ///
155  /// For example, to enable GpuAcc tuning add the following
156  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.cpp
157  /// m_BackendOption.emplace_back(
158  /// BackendOptions{"GpuAcc",
159  /// {
160  /// {"TuningLevel", 2},
161  /// {"TuningFile", filename}
162  /// {"MemoryOptimizerStrategy", strategyname}
163  /// }
164  /// });
165  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
166  /// Execute representative workloads through the runtime to generate tuning data.
167  /// The tuning file is written once the runtime is destroyed
168 
169  /// To execute with the tuning data, start up with just the tuning file specified.
170  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.cpp
171  /// m_BackendOption.emplace_back(
172  /// BackendOptions{"GpuAcc",
173  /// {
174  /// {"TuningFile", filename}
175  /// }
176  /// });
177  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
178 
179  /// The following backend options are available:
180  /// AllBackends:
181  /// "MemoryOptimizerStrategy" : string [stategynameString]
182  /// (Existing Memory Optimizer Strategies: ConstantMemoryStrategy)
183  /// GpuAcc:
184  /// "TuningLevel" : int [0..3] (0=UseOnly(default) | 1=RapidTuning | 2=NormalTuning | 3=ExhaustiveTuning)
185  /// "TuningFile" : string [filenameString]
186  /// "KernelProfilingEnabled" : bool [true | false]
187  std::vector<BackendOptions> m_BackendOptions;
188  };
189 
190  static IRuntime* CreateRaw(const CreationOptions& options);
191  static IRuntimePtr Create(const CreationOptions& options);
192  static void Destroy(IRuntime* runtime);
193 
194  /// Loads a complete network into the IRuntime.
195  /// @param [out] networkIdOut - Unique identifier for the network is returned in this reference.
196  /// @param [in] network - Complete network to load into the IRuntime.
197  /// The runtime takes ownership of the network once passed in.
198  /// @return armnn::Status
199  Status LoadNetwork(NetworkId& networkIdOut, IOptimizedNetworkPtr network);
200 
201  /// Load a complete network into the IRuntime.
202  /// @param [out] networkIdOut Unique identifier for the network is returned in this reference.
203  /// @param [in] network Complete network to load into the IRuntime.
204  /// @param [out] errorMessage Error message if there were any errors.
205  /// The runtime takes ownership of the network once passed in.
206  /// @return armnn::Status
207  Status LoadNetwork(NetworkId& networkIdOut,
208  IOptimizedNetworkPtr network,
209  std::string& errorMessage);
210 
211  Status LoadNetwork(NetworkId& networkIdOut,
212  IOptimizedNetworkPtr network,
213  std::string& errorMessage,
214  const INetworkProperties& networkProperties);
215 
216  TensorInfo GetInputTensorInfo(NetworkId networkId, LayerBindingId layerId) const;
217  TensorInfo GetOutputTensorInfo(NetworkId networkId, LayerBindingId layerId) const;
218 
219  /// ImportInputs separates the importing and mapping of InputTensors from network execution.
220  /// Allowing for a set of InputTensors to be imported and mapped once, but used in execution many times.
221  /// This function is not thread safe and must not be used while other threads are calling Execute().
222  /// Only compatible with AsyncEnabled networks and aligned memory import
223  std::vector<ImportedInputId> ImportInputs(NetworkId networkId, const InputTensors& inputTensors,
224  MemorySource forceImportMemorySource = MemorySource::Undefined);
225 
226  /// ImportOutputs separates the importing and mapping of OutputTensors from network execution.
227  /// Allowing for a set of OutputTensors to be imported and mapped once, but used in execution many times.
228  /// This function is not thread safe and must not be used while other threads are calling Execute().
229  /// Only compatible with AsyncEnabled networks and aligned memory import
230  std::vector<ImportedOutputId> ImportOutputs(NetworkId networkId, const OutputTensors& outputTensors,
231  MemorySource forceImportMemorySource = MemorySource::Undefined);
232 
233  /// Un-import and delete the imported InputTensor/s
234  /// This function is not thread safe and must not be used while other threads are calling Execute().
235  /// Only compatible with AsyncEnabled networks
236  void ClearImportedInputs(NetworkId networkId, const std::vector<ImportedInputId> inputIds);
237 
238  /// Un-import and delete the imported OutputTensor/s
239  /// This function is not thread safe and must not be used while other threads are calling Execute().
240  /// Only compatible with AsyncEnabled networks
241  void ClearImportedOutputs(NetworkId networkId, const std::vector<ImportedOutputId> outputIds);
242 
243  /// Evaluates a network using input in inputTensors and outputs filled into outputTensors
244  Status EnqueueWorkload(NetworkId networkId,
245  const InputTensors& inputTensors,
246  const OutputTensors& outputTensors,
247  std::vector<ImportedInputId> preImportedInputIds = {},
248  std::vector<ImportedOutputId> preImportedOutputIds = {});
249 
250  /// This is an experimental function.
251  /// Evaluates a network using input in inputTensors and outputs filled into outputTensors.
252  /// This function performs a thread safe execution of the network. Returns once execution is complete.
253  /// Will block until this and any other thread using the same workingMem object completes.
254  Status Execute(IWorkingMemHandle& workingMemHandle,
255  const InputTensors& inputTensors,
256  const OutputTensors& outputTensors,
257  std::vector<ImportedInputId> preImportedInputs = {},
258  std::vector<ImportedOutputId> preImportedOutputs = {});
259 
260  /// Unloads a network from the IRuntime.
261  /// At the moment this only removes the network from the m_Impl->m_Network.
262  /// This might need more work in the future to be AndroidNN compliant.
263  /// @param [in] networkId - Unique identifier for the network to be unloaded. Generated in LoadNetwork().
264  /// @return armnn::Status
265  Status UnloadNetwork(NetworkId networkId);
266 
267  const IDeviceSpec& GetDeviceSpec() const;
268 
269  /// Create a new unique WorkingMemHandle object. Create multiple handles if you wish to have
270  /// overlapped Execution by calling this function from different threads.
271  std::unique_ptr<IWorkingMemHandle> CreateWorkingMemHandle(NetworkId networkId);
272 
273  /// Gets the profiler corresponding to the given network id.
274  /// @param networkId The id of the network for which to get the profile.
275  /// @return A pointer to the requested profiler, or nullptr if not found.
276  const std::shared_ptr<IProfiler> GetProfiler(NetworkId networkId) const;
277 
278  /// Registers a callback function to debug layers performing custom computations on intermediate tensors.
279  /// @param networkId The id of the network to register the callback.
280  /// @param func callback function to pass to the debug layer.
281  void RegisterDebugCallback(NetworkId networkId, const DebugCallbackFunction& func);
282 
283 protected:
284  IRuntime();
285  IRuntime(const IRuntime::CreationOptions& options);
286  ~IRuntime();
287 
288  std::unique_ptr<RuntimeImpl> pRuntimeImpl;
289 };
290 
291 
292 /// The following API is replaced by the backend options API.
293 using IGpuAccTunedParametersPtr = std::shared_ptr<IGpuAccTunedParameters>;
294 
295 /// Manages a set of GpuAcc parameters which have been tuned for maximum performance.
296 /// Passes an instance of this object to the IRuntime::Create() method (via IRuntime::CreationOptions) to use it
297 /// for all GPU workload execution.
298 ///
299 /// Can be created in two modes:
300 /// - In UseTunedParameters mode, the parameters stored in this object are used to execute GPU workloads.
301 /// - In UpdateTunedParameters mode, additionally, whenever a GPU workload is executed for the first time, the
302 /// optimum parameters will be found and stored in this object. WARNING - This tuning can be slow.
303 ///
304 /// The parameters can be loaded from and saved to a file so that you can first run a slow initial read-write
305 /// execution, save the parameters for later and then run fast read-only executions using the optimised parameters.
307 {
308 public:
309  enum class Mode
310  {
311  UseTunedParameters,
312  UpdateTunedParameters
313  };
314 
315  enum class TuningLevel
316  {
317  Rapid = 1,
318  Normal = 2,
319  Exhaustive = 3
320  };
321 
322  /// Creates an IClTunedParameters with the given mode.
323  /// @{
324  static IGpuAccTunedParameters* CreateRaw(Mode mode, TuningLevel tunerMode);
325  static IGpuAccTunedParametersPtr Create(Mode mode, TuningLevel tunerMode);
326  /// @}
327  static void Destroy(IGpuAccTunedParameters* params);
328 
329  /// Loads an existing set of tuned parameters from the given file.
330  /// If there is an error loading the file, an armnn::Exception is thrown.
331  virtual void Load(const char* filename) = 0;
332 
333  /// Saves the current set of tuned parameters to the given file.
334  /// If there is an error saving to the file, an armnn::Exception is thrown.
335  virtual void Save(const char* filename) const = 0;
336 
337 protected:
339 };
340 
341 } // namespace armnn
const MemorySource m_InputSource
Definition: IRuntime.hpp:62
const bool m_ImportEnabled
Deprecated and will be removed in future release.
Definition: IRuntime.hpp:52
std::string m_OutgoingCaptureFile
Path to a file in which outgoing timeline profiling messages will be stored.
Definition: IRuntime.hpp:140
std::unique_ptr< IRuntime, void(*)(IRuntime *runtime)> IRuntimePtr
Definition: IRuntime.hpp:31
std::vector< std::pair< LayerBindingId, class ConstTensor > > InputTensors
Definition: Tensor.hpp:392
const ProfilingDetailsMethod m_OutputNetworkDetailsMethod
Definition: IRuntime.hpp:60
std::map< BackendId, std::shared_ptr< IMemoryOptimizerStrategy > > m_MemoryOptimizerStrategyMap
A map to define a custom memory optimizer strategy for specific backend Ids.
Definition: IRuntime.hpp:120
Copyright (c) 2021 ARM Limited and Contributors.
std::string m_IncomingCaptureFile
Path to a file in which incoming timeline profiling messages will be stored.
Definition: IRuntime.hpp:142
bool m_EnableProfiling
Indicates whether external profiling is enabled or not.
Definition: IRuntime.hpp:136
bool m_FileOnly
Enable profiling output to file only.
Definition: IRuntime.hpp:144
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:371
int LayerBindingId
Type of identifiers for bindable layers (inputs, outputs).
Definition: Types.hpp:277
ProfilingDetailsMethod
Define the behaviour of the internal profiler when outputting network details.
Definition: Types.hpp:58
std::shared_ptr< IGpuAccTunedParameters > m_GpuAccTunedParameters
If set, uses the GpuAcc tuned parameters from the given object when executing GPU workloads...
Definition: IRuntime.hpp:88
std::vector< BackendOptions > m_BackendOptions
Pass backend specific options.
Definition: IRuntime.hpp:187
const bool m_ExternalMemoryManagementEnabled
Definition: IRuntime.hpp:65
std::vector< armnn::profiling::ILocalPacketHandlerSharedPtr > m_LocalPacketHandlers
Definition: IRuntime.hpp:149
int NetworkId
Definition: IRuntime.hpp:25
std::vector< std::pair< LayerBindingId, class Tensor > > OutputTensors
Definition: Tensor.hpp:393
Status
enumeration
Definition: Types.hpp:29
std::unique_ptr< IOptimizedNetwork, void(*)(IOptimizedNetwork *network)> IOptimizedNetworkPtr
Definition: INetwork.hpp:242
INetworkProperties(bool asyncEnabled, MemorySource inputSource, MemorySource outputSource, bool profilingEnabled=false, ProfilingDetailsMethod detailsMethod=ProfilingDetailsMethod::Undefined, bool externalMemoryManagementEnabled=false)
Definition: IRuntime.hpp:35
const bool m_ExportEnabled
Deprecated and will be removed in future release.
Definition: IRuntime.hpp:54
std::map< BackendId, std::shared_ptr< ICustomAllocator > > m_CustomAllocatorMap
A map to define a custom memory allocator for specific backend Ids.
Definition: IRuntime.hpp:112
std::unique_ptr< RuntimeImpl > pRuntimeImpl
Definition: IRuntime.hpp:288
Device specific knowledge to be passed to the optimizer.
Definition: Types.hpp:267
constexpr unsigned int LOWEST_CAPTURE_PERIOD
The lowest performance data capture interval we support is 10 miliseconds.
Definition: Types.hpp:21
std::shared_ptr< IGpuAccTunedParameters > IGpuAccTunedParametersPtr
The following API is replaced by the backend options API.
Definition: IRuntime.hpp:293
bool m_ProtectedMode
Setting this flag will allow the user to create the Runtime in protected mode.
Definition: IRuntime.hpp:103
std::string m_DynamicBackendsPath
Setting this value will override the paths set by the DYNAMIC_BACKEND_PATHS compiler directive Only a...
Definition: IRuntime.hpp:96
bool m_EnableGpuProfiling
Setting this flag will allow the user to obtain GPU profiling information from the runtime...
Definition: IRuntime.hpp:91
Manages a set of GpuAcc parameters which have been tuned for maximum performance. ...
Definition: IRuntime.hpp:306
MemorySource
Define the Memory Source to reduce copies.
Definition: Types.hpp:217
uint32_t m_CapturePeriod
The duration at which captured profiling messages will be flushed.
Definition: IRuntime.hpp:146
bool m_TimelineEnabled
Indicates whether external timeline profiling is enabled or not.
Definition: IRuntime.hpp:138
const MemorySource m_OutputSource
Definition: IRuntime.hpp:63
ExternalProfilingOptions m_ProfilingOptions
Definition: IRuntime.hpp:151
const bool m_ProfilingEnabled
Definition: IRuntime.hpp:58
std::string m_FileFormat
The format of the file used for outputting profiling data.
Definition: IRuntime.hpp:148
virtual ~INetworkProperties()
Definition: IRuntime.hpp:67