blob: b3bc5cd1e5eb320264dff13ad9f76f24384eaeb3 [file] [log] [blame]
Mike Kellyb5fdf382019-06-11 16:35:25 +01001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
5
6#include "ArmnnDriverImpl.hpp"
7#include "../ArmnnPreparedModel_1_2.hpp"
8#include "../ModelToINetworkConverter.hpp"
9#include "../SystemPropertiesUtils.hpp"
10
Sadik Armagan0a2dfab2021-10-06 16:41:44 +010011#include <armnnDeserializer/IDeserializer.hpp>
12
Mike Kellyb5fdf382019-06-11 16:35:25 +010013#include <log/log.h>
Sadik Armagan0a2dfab2021-10-06 16:41:44 +010014#include <sys/stat.h>
Mike Kellyb5fdf382019-06-11 16:35:25 +010015
16namespace
17{
18
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +010019const char *g_RelaxedFloat32toFloat16PerformanceExecTime = "ArmNN.relaxedFloat32toFloat16Performance.execTime";
FinnWilliamsArmdf655ee2019-07-24 16:04:18 +010020const char *g_RelaxedFloat32toFloat16PerformancePowerUsage = "ArmNN.relaxedFloat32toFloat16Performance.powerUsage";
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +010021
22const char *g_OperandTypeTensorFloat32PerformanceExecTime = "Armnn.operandTypeTensorFloat32Performance.execTime";
23const char *g_OperandTypeTensorFloat32PerformancePowerUsage = "Armnn.operandTypeTensorFloat32Performance.powerUsage";
24
25const char *g_OperandTypeFloat32PerformanceExecTime = "Armnn.operandTypeFloat32Performance.execTime";
26const char *g_OperandTypeFloat32PerformancePowerUsage = "Armnn.operandTypeFloat32Performance.powerUsage";
27
28const char *g_OperandTypeTensorFloat16PerformanceExecTime = "Armnn.operandTypeTensorFloat16Performance.execTime";
29const char *g_OperandTypeTensorFloat16PerformancePowerUsage = "Armnn.operandTypeTensorFloat16Performance.powerUsage";
30
31const char *g_OperandTypeFloat16PerformanceExecTime = "Armnn.operandTypeFloat16Performance.execTime";
32const char *g_OperandTypeFloat16PerformancePowerUsage = "Armnn.operandTypeFloat16Performance.powerUsage";
33
34const char *g_OperandTypeTensorQuant8AsymmPerformanceExecTime =
35 "Armnn.operandTypeTensorQuant8AsymmPerformance.execTime";
36const char *g_OperandTypeTensorQuant8AsymmPerformancePowerUsage =
37 "Armnn.operandTypeTensorQuant8AsymmPerformance.powerUsage";
38
39const char *g_OperandTypeTensorQuant16SymmPerformanceExecTime =
40 "Armnn.operandTypeTensorQuant16SymmPerformance.execTime";
41const char *g_OperandTypeTensorQuant16SymmPerformancePowerUsage =
42 "Armnn.operandTypeTensorQuant16SymmPerformance.powerUsage";
43
Pablo Tellofb45e2f2019-10-18 16:51:57 +010044const char *g_OperandTypeTensorQuant8SymmPerformanceExecTime =
45 "Armnn.operandTypeTensorQuant8SymmPerformance.execTime";
46const char *g_OperandTypeTensorQuant8SymmPerformancePowerUsage =
47 "Armnn.operandTypeTensorQuant8SymmPerformance.powerUsage";
48
Kevin May87cb7612019-11-11 17:30:35 +000049const char *g_OperandTypeTensorQuant8SymmPerChannelPerformanceExecTime =
50 "Armnn.operandTypeTensorQuant8SymmPerChannelPerformance.execTime";
51const char *g_OperandTypeTensorQuant8SymmPerChannelPerformancePowerUsage =
52 "Armnn.operandTypeTensorQuant8SymmPerChannelPerformance.powerUsage";
53
Pablo Tellofb45e2f2019-10-18 16:51:57 +010054
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +010055const char *g_OperandTypeTensorInt32PerformanceExecTime = "Armnn.operandTypeTensorInt32Performance.execTime";
56const char *g_OperandTypeTensorInt32PerformancePowerUsage = "Armnn.operandTypeTensorInt32Performance.powerUsage";
57
58const char *g_OperandTypeInt32PerformanceExecTime = "Armnn.operandTypeInt32Performance.execTime";
59const char *g_OperandTypeInt32PerformancePowerUsage = "Armnn.operandTypeInt32Performance.powerUsage";
60
61
Sadik Armagan188675f2021-02-12 17:16:42 +000062void NotifyCallbackAndCheck(const android::sp<V1_2::IPreparedModelCallback>& callback,
Kevin Mayec1e5b82020-02-26 17:00:39 +000063 V1_0::ErrorStatus errorStatus,
Sadik Armagan188675f2021-02-12 17:16:42 +000064 const android::sp<V1_2::IPreparedModel>& preparedModelPtr)
Mike Kellyb5fdf382019-06-11 16:35:25 +010065{
Ferran Balaguerb2397fd2019-07-25 12:12:39 +010066 Return<void> returned = callback->notify_1_2(errorStatus, preparedModelPtr);
Mike Kellyb5fdf382019-06-11 16:35:25 +010067 // This check is required, if the callback fails and it isn't checked it will bring down the service
68 if (!returned.isOk())
69 {
70 ALOGE("ArmnnDriverImpl::prepareModel: hidl callback failed to return properly: %s ",
71 returned.description().c_str());
72 }
73}
74
Kevin Mayec1e5b82020-02-26 17:00:39 +000075Return<V1_0::ErrorStatus> FailPrepareModel(V1_0::ErrorStatus error,
76 const std::string& message,
Sadik Armagan188675f2021-02-12 17:16:42 +000077 const android::sp<V1_2::IPreparedModelCallback>& callback)
Mike Kellyb5fdf382019-06-11 16:35:25 +010078{
79 ALOGW("ArmnnDriverImpl::prepareModel: %s", message.c_str());
80 NotifyCallbackAndCheck(callback, error, nullptr);
81 return error;
82}
83
84} // anonymous namespace
85
86namespace armnn_driver
87{
88namespace hal_1_2
89{
90
Kevin Mayec1e5b82020-02-26 17:00:39 +000091Return<V1_0::ErrorStatus> ArmnnDriverImpl::prepareArmnnModel_1_2(
92 const armnn::IRuntimePtr& runtime,
93 const armnn::IGpuAccTunedParametersPtr& clTunedParameters,
94 const DriverOptions& options,
95 const V1_2::Model& model,
Sadik Armagan0a2dfab2021-10-06 16:41:44 +010096 const android::hardware::hidl_vec<android::hardware::hidl_handle>& modelCacheHandle,
97 const android::hardware::hidl_vec<android::hardware::hidl_handle>& dataCacheHandle,
98 const HidlToken& token,
Sadik Armagan188675f2021-02-12 17:16:42 +000099 const android::sp<V1_2::IPreparedModelCallback>& cb,
Kevin Mayec1e5b82020-02-26 17:00:39 +0000100 bool float32ToFloat16)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100101{
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100102 ALOGV("ArmnnDriverImpl::prepareArmnnModel_1_2()");
Mike Kellyb5fdf382019-06-11 16:35:25 +0100103
104 if (cb.get() == nullptr)
105 {
106 ALOGW("ArmnnDriverImpl::prepareModel: Invalid callback passed to prepareModel");
Kevin Mayec1e5b82020-02-26 17:00:39 +0000107 return V1_0::ErrorStatus::INVALID_ARGUMENT;
Mike Kellyb5fdf382019-06-11 16:35:25 +0100108 }
109
110 if (!runtime)
111 {
Kevin Mayec1e5b82020-02-26 17:00:39 +0000112 return FailPrepareModel(V1_0::ErrorStatus::DEVICE_UNAVAILABLE, "Device unavailable", cb);
Mike Kellyb5fdf382019-06-11 16:35:25 +0100113 }
114
115 if (!android::nn::validateModel(model))
116 {
Kevin Mayec1e5b82020-02-26 17:00:39 +0000117 return FailPrepareModel(V1_0::ErrorStatus::INVALID_ARGUMENT, "Invalid model passed as input", cb);
Mike Kellyb5fdf382019-06-11 16:35:25 +0100118 }
119
120 // Deliberately ignore any unsupported operations requested by the options -
121 // at this point we're being asked to prepare a model that we've already declared support for
122 // and the operation indices may be different to those in getSupportedOperations anyway.
123 std::set<unsigned int> unsupportedOperations;
124 ModelToINetworkConverter<HalPolicy> modelConverter(options.GetBackends(),
125 model,
126 unsupportedOperations);
127
128 if (modelConverter.GetConversionResult() != ConversionResult::Success)
129 {
Kevin Mayec1e5b82020-02-26 17:00:39 +0000130 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "ModelToINetworkConverter failed", cb);
131 return V1_0::ErrorStatus::NONE;
Mike Kellyb5fdf382019-06-11 16:35:25 +0100132 }
133
Sadik Armaganb3021432021-01-13 15:56:51 +0000134 // Serialize the network graph to a .armnn file if an output directory
135 // has been specified in the drivers' arguments.
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100136 std::vector<uint8_t> dataCacheData;
137 bool serializeToFile = dataCacheHandle.size() < 1 ? false : true;
Sadik Armaganb3021432021-01-13 15:56:51 +0000138 auto serializedNetworkFileName =
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100139 SerializeNetwork(*modelConverter.GetINetwork(),
140 options.GetRequestInputsAndOutputsDumpDir(),
141 dataCacheData,
142 serializeToFile);
Sadik Armaganb3021432021-01-13 15:56:51 +0000143
Mike Kellyb5fdf382019-06-11 16:35:25 +0100144 // Optimize the network
145 armnn::IOptimizedNetworkPtr optNet(nullptr, nullptr);
146 armnn::OptimizerOptions OptOptions;
147 OptOptions.m_ReduceFp32ToFp16 = float32ToFloat16;
Kevin Maydaf7dd02021-10-22 11:57:30 +0100148 OptOptions.m_ProfilingEnabled = options.IsGpuProfilingEnabled();
Mike Kellyb5fdf382019-06-11 16:35:25 +0100149
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100150 int cachedFd = -1;
151 bool saveCachedNetwork = options.SaveCachedNetwork();
152
153 unsigned int numberOfCachedModelFiles = 0;
154 if (modelCacheHandle.size() > 0)
155 {
156 unsigned int index = 0;
157 for (auto& backend : options.GetBackends())
158 {
159 // modelCacheHandle size should be equal to numberOfCachedModelFiles
160 // modelCacheHandle vector should be in same order as backends
161 auto numberOfCacheFiles = GetNumberOfCacheFiles(backend);
162 if (numberOfCacheFiles > 0)
163 {
164 numberOfCachedModelFiles += numberOfCacheFiles;
165 if (modelCacheHandle[index]->numFds == 1)
166 {
167 if (backend == armnn::Compute::GpuAcc)
168 {
169 cachedFd = modelCacheHandle[index]->data[0];
170 saveCachedNetwork = true;
171 }
172 }
173 index += numberOfCachedModelFiles;
174 }
175 }
176 }
177
Mike Kelly7ed56dd2020-09-30 20:22:56 +0100178 armnn::BackendOptions gpuAcc("GpuAcc",
179 {
Sadik Armaganf36e10b2021-01-11 16:34:01 +0000180 { "FastMathEnabled", options.IsFastMathEnabled() },
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100181 { "SaveCachedNetwork", saveCachedNetwork },
Finn Williamsf5ca16c2021-02-12 14:26:23 +0000182 { "CachedNetworkFilePath", options.GetCachedNetworkFilePath() },
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100183 { "MLGOTuningFilePath", options.GetClMLGOTunedParametersFile() },
184 { "CachedFileDescriptor", cachedFd }
Mike Kelly7ed56dd2020-09-30 20:22:56 +0100185 });
Finn Williamsf5ca16c2021-02-12 14:26:23 +0000186
Mike Kelly7ed56dd2020-09-30 20:22:56 +0100187 armnn::BackendOptions cpuAcc("CpuAcc",
188 {
Matthew Sloyancd639c92021-02-11 16:57:38 +0000189 { "FastMathEnabled", options.IsFastMathEnabled() },
190 { "NumberOfThreads", options.GetNumberOfThreads() }
Mike Kelly7ed56dd2020-09-30 20:22:56 +0100191 });
192 OptOptions.m_ModelOptions.push_back(gpuAcc);
193 OptOptions.m_ModelOptions.push_back(cpuAcc);
194
Mike Kellyb5fdf382019-06-11 16:35:25 +0100195 std::vector<std::string> errMessages;
196 try
197 {
198 optNet = armnn::Optimize(*modelConverter.GetINetwork(),
199 options.GetBackends(),
200 runtime->GetDeviceSpec(),
201 OptOptions,
202 errMessages);
203 }
Derek Lambertib9cb8442019-11-28 13:34:48 +0000204 catch (std::exception &e)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100205 {
206 std::stringstream message;
Derek Lambertib9cb8442019-11-28 13:34:48 +0000207 message << "Exception (" << e.what() << ") caught from optimize.";
Kevin Mayec1e5b82020-02-26 17:00:39 +0000208 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, message.str(), cb);
209 return V1_0::ErrorStatus::NONE;
Mike Kellyb5fdf382019-06-11 16:35:25 +0100210 }
211
212 // Check that the optimized network is valid.
213 if (!optNet)
214 {
215 std::stringstream message;
216 message << "Invalid optimized network";
217 for (const std::string& msg : errMessages)
218 {
219 message << "\n" << msg;
220 }
Kevin Mayec1e5b82020-02-26 17:00:39 +0000221 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, message.str(), cb);
222 return V1_0::ErrorStatus::NONE;
Mike Kellyb5fdf382019-06-11 16:35:25 +0100223 }
224
225 // Export the optimized network graph to a dot file if an output dump directory
226 // has been specified in the drivers' arguments.
Jim Flynn829ad302019-12-13 14:43:24 +0000227 std::string dotGraphFileName = ExportNetworkGraphToDotFile(*optNet,
228 options.GetRequestInputsAndOutputsDumpDir());
Mike Kellyb5fdf382019-06-11 16:35:25 +0100229
230 // Load it into the runtime.
231 armnn::NetworkId netId = 0;
Finn Williamsd8fb5402021-05-19 20:52:00 +0100232 std::string msg;
233 armnn::INetworkProperties networkProperties(options.isAsyncModelExecutionEnabled(),
234 MemorySource::Undefined,
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100235 MemorySource::Undefined,
236 options.IsGpuProfilingEnabled());
237
238 auto numInputs = getMainModel(model).inputIndexes.size();
239 auto numOutputs = getMainModel(model).outputIndexes.size();
Mike Kellyb5fdf382019-06-11 16:35:25 +0100240 try
241 {
Finn Williamsd8fb5402021-05-19 20:52:00 +0100242 if (runtime->LoadNetwork(netId, move(optNet), msg, networkProperties) != armnn::Status::Success)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100243 {
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100244 return FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, msg, cb);
Mike Kellyb5fdf382019-06-11 16:35:25 +0100245 }
246 }
Derek Lambertib9cb8442019-11-28 13:34:48 +0000247 catch (std::exception& e)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100248 {
249 std::stringstream message;
Derek Lambertib9cb8442019-11-28 13:34:48 +0000250 message << "Exception (" << e.what()<< ") caught from LoadNetwork.";
Kevin Mayec1e5b82020-02-26 17:00:39 +0000251 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, message.str(), cb);
252 return V1_0::ErrorStatus::NONE;
Mike Kellyb5fdf382019-06-11 16:35:25 +0100253 }
254
Sadik Armaganb3021432021-01-13 15:56:51 +0000255 // Now that we have a networkId for the graph rename the exported files to use it
256 // so that we can associate the graph file and the input/output tensor exported files
257 RenameExportedFiles(serializedNetworkFileName,
258 dotGraphFileName,
259 options.GetRequestInputsAndOutputsDumpDir(),
260 netId);
Jim Flynn829ad302019-12-13 14:43:24 +0000261
Mike Kellyb5fdf382019-06-11 16:35:25 +0100262 std::unique_ptr<ArmnnPreparedModel_1_2<hal_1_2::HalPolicy>> preparedModel(
263 new ArmnnPreparedModel_1_2<hal_1_2::HalPolicy>(
264 netId,
265 runtime.get(),
266 model,
267 options.GetRequestInputsAndOutputsDumpDir(),
Finn Williamsd8fb5402021-05-19 20:52:00 +0100268 options.IsGpuProfilingEnabled(),
Finn Williamsca3a3e02021-06-11 15:04:02 +0100269 options.isAsyncModelExecutionEnabled(),
270 options.getNoOfArmnnThreads()));
Mike Kellyb5fdf382019-06-11 16:35:25 +0100271
272 // Run a single 'dummy' inference of the model. This means that CL kernels will get compiled (and tuned if
273 // this is enabled) before the first 'real' inference which removes the overhead of the first inference.
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100274 // Only run this if the GpuAcc backend has been added to options
275 if (std::find(options.GetBackends().begin(),
276 options.GetBackends().end(),
277 armnn::Compute::GpuAcc) != options.GetBackends().end())
Mike Kellyb5fdf382019-06-11 16:35:25 +0100278 {
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100279 if (!preparedModel->ExecuteWithDummyInputs(numInputs, numOutputs))
280 {
281 return FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "Network could not be executed", cb);
282 }
283
284 if (clTunedParameters &&
285 options.GetClTunedParametersMode() == armnn::IGpuAccTunedParameters::Mode::UpdateTunedParameters)
286 {
287 // Now that we've done one inference the CL kernel parameters will have been tuned,
288 // so save the updated file.
289 try
290 {
291 clTunedParameters->Save(options.GetClTunedParametersFile().c_str());
292 }
293 catch (std::exception& error)
294 {
295 ALOGE("ArmnnDriverImpl::prepareModel: Failed to save CL tuned parameters file '%s': %s",
296 options.GetClTunedParametersFile().c_str(), error.what());
297 }
298 }
Mike Kellyb5fdf382019-06-11 16:35:25 +0100299 }
300
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100301 size_t hashValue = 0;
302 // Cache the model
303 if (dataCacheHandle.size() > 0)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100304 {
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100305 // Cache the Arm NN model, should be only 1
306 if (dataCacheHandle.size() != 1)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100307 {
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100308 NotifyCallbackAndCheck(cb, V1_0::ErrorStatus::NONE, preparedModel.release());
309 return V1_0::ErrorStatus::NONE;
Mike Kellyb5fdf382019-06-11 16:35:25 +0100310 }
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100311
312 if (dataCacheHandle[0]->numFds != 1)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100313 {
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100314 ALOGW("ArmnnDriverImpl::prepareArmnnModel_1_3: Cannot cache the data, numFds != 1.");
315 NotifyCallbackAndCheck(cb, V1_0::ErrorStatus::NONE, preparedModel.release());
316 return V1_0::ErrorStatus::NONE;
Mike Kellyb5fdf382019-06-11 16:35:25 +0100317 }
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100318 int dataCacheFileAccessMode = fcntl(dataCacheHandle[0]->data[0], F_GETFL) & O_ACCMODE;
319 if (dataCacheFileAccessMode != O_RDWR)
320 {
321 ALOGW("ArmnnDriverImpl::prepareModelFromCache_1_2(): Invalid Access Mode.");
322 NotifyCallbackAndCheck(cb, V1_0::ErrorStatus::NONE, preparedModel.release());
323 return V1_0::ErrorStatus::NONE;
324 }
325
326 write(dataCacheHandle[0]->data[0], dataCacheData.data(), dataCacheData.size());
327 hashValue = CacheDataHandlerInstance().Hash(dataCacheData);
328 }
329
330 if (modelCacheHandle.size() > 0)
331 {
332 if (modelCacheHandle.size() != numberOfCachedModelFiles)
333 {
334 NotifyCallbackAndCheck(cb, V1_0::ErrorStatus::NONE, preparedModel.release());
335 return V1_0::ErrorStatus::NONE;
336 }
337 for (uint32_t i = 0; i < modelCacheHandle.size(); ++i)
338 {
339 if (modelCacheHandle[i]->numFds == 1)
340 {
341 int modelCacheFileAccessMode = fcntl(modelCacheHandle[i]->data[0], F_GETFL) & O_ACCMODE;
342 if (modelCacheFileAccessMode != O_RDONLY)
343 {
344 struct stat statBuffer;
345 if (fstat(modelCacheHandle[i]->data[0], &statBuffer) == 0)
346 {
347 long modelDataSize = statBuffer.st_size;
348 if (modelDataSize > 0)
349 {
350 std::vector <uint8_t> modelData(modelDataSize);
351 pread(modelCacheHandle[i]->data[0], modelData.data(), modelData.size(), 0);
352 hashValue ^= CacheDataHandlerInstance().Hash(modelData);
353 }
354 }
355 }
356 }
357 }
358 }
359 if (hashValue != 0)
360 {
361 CacheDataHandlerInstance().Register(token, hashValue, dataCacheData.size());
Mike Kellyb5fdf382019-06-11 16:35:25 +0100362 }
363
Kevin Mayec1e5b82020-02-26 17:00:39 +0000364 NotifyCallbackAndCheck(cb, V1_0::ErrorStatus::NONE, preparedModel.release());
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100365 return V1_0::ErrorStatus::NONE;
366}
Mike Kellyb5fdf382019-06-11 16:35:25 +0100367
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100368Return<V1_0::ErrorStatus> ArmnnDriverImpl::prepareModelFromCache(
369 const armnn::IRuntimePtr& runtime,
370 const DriverOptions& options,
371 const android::hardware::hidl_vec<android::hardware::hidl_handle>& modelCacheHandle,
372 const android::hardware::hidl_vec<android::hardware::hidl_handle>& dataCacheHandle,
373 const HidlToken& token,
374 const android::sp<V1_2::IPreparedModelCallback>& cb,
375 bool float32ToFloat16)
376{
377 ALOGV("ArmnnDriverImpl::prepareModelFromCache()");
378
379 if (cb.get() == nullptr)
380 {
381 ALOGW("ArmnnDriverImpl::prepareModelFromCache: Invalid callback passed to prepareModel");
382 return V1_0::ErrorStatus::INVALID_ARGUMENT;
383 }
384
385 if (!runtime)
386 {
387 return FailPrepareModel(V1_0::ErrorStatus::DEVICE_UNAVAILABLE, "Device unavailable", cb);
388 }
389
390 if (token.size() != ANEURALNETWORKS_BYTE_SIZE_OF_CACHE_TOKEN)
391 {
392 FailPrepareModel(V1_0::ErrorStatus::INVALID_ARGUMENT, "Invalid token passed!", cb);
393 return V1_0::ErrorStatus::INVALID_ARGUMENT;
394 }
395
396 // DataCacheHandle size should always be 1
397 // Arm NN model
398 if (dataCacheHandle.size() != 1)
399 {
400 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "No data cache!", cb);
401 return V1_0::ErrorStatus::GENERAL_FAILURE;
402 }
403
404 // Check if model files cached they match the expected value
405 unsigned int numberOfCachedModelFiles = 0;
406 for (auto& backend : options.GetBackends())
407 {
408 numberOfCachedModelFiles += GetNumberOfCacheFiles(backend);
409 }
410 if (modelCacheHandle.size() != numberOfCachedModelFiles)
411 {
412 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "Invalid model cache!", cb);
413 return V1_0::ErrorStatus::GENERAL_FAILURE;
414 }
415
416 if (dataCacheHandle[0]->numFds != 1)
417 {
418 ALOGW("ArmnnDriverImpl::prepareModelFromCache: Cannot read from the cache data, numFds != 1.");
419 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "No data cache!", cb);
420 return V1_0::ErrorStatus::GENERAL_FAILURE;
421 }
422
423 int dataCacheFileAccessMode = fcntl(dataCacheHandle[0]->data[0], F_GETFL) & O_ACCMODE;
424 if (dataCacheFileAccessMode != O_RDWR)
425 {
426 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "Invalid Access Mode!", cb);
427 return V1_0::ErrorStatus::GENERAL_FAILURE;
428 }
429
430 auto dataSize = CacheDataHandlerInstance().GetCacheSize(token);
431 if (dataSize == 0)
432 {
433 ALOGW("ArmnnDriverImpl::prepareModelFromCache: Invalid data to deserialize!");
434 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "Invalid data to deserialize!", cb);
435 return V1_0::ErrorStatus::GENERAL_FAILURE;
436 }
437
438 int offset = 0;
439 {
440 struct stat statBuffer;
441 if (fstat(dataCacheHandle[0]->data[0], &statBuffer) == 0)
442 {
443 unsigned long bufferSize = statBuffer.st_size;
444 if (bufferSize <= 0)
445 {
446 ALOGW("ArmnnDriverImpl::prepareModelFromCache: Invalid data to deserialize!");
447 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "Invalid data to deserialize!", cb);
448 return V1_0::ErrorStatus::GENERAL_FAILURE;
449 }
450 if (bufferSize > dataSize)
451 {
452 offset = bufferSize - dataSize;
453 }
454 }
455 }
456 std::vector<uint8_t> dataCacheData(dataSize);
457 pread(dataCacheHandle[0]->data[0], dataCacheData.data(), dataCacheData.size(), offset);
458 auto hashValue = CacheDataHandlerInstance().Hash(dataCacheData);
459
460 int gpuAccCachedFd = -1;
461 bool saveCachedNetwork = false;
462 if (modelCacheHandle.size() > 0)
463 {
464 unsigned int index = 0;
465 for (auto& backend : options.GetBackends())
466 {
467 // modelCacheHandle size should be equal to numberOfCachedModelFiles
468 // modelCacheHandle vector should be in same order as backends
469 auto numberOfCacheFiles = GetNumberOfCacheFiles(backend);
470 if (numberOfCacheFiles > 0)
471 {
472 if (modelCacheHandle[index]->numFds != 1)
473 {
474 ALOGW("ArmnnDriverImpl::prepareModelFromCache: Cannot read from the model cache, numFds != 1.");
475 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE,
476 "Cannot read from the model cache, numFds != 1.", cb);
477 return V1_0::ErrorStatus::GENERAL_FAILURE;
478 }
479 auto cachedFd = modelCacheHandle[index]->data[0];
480
481 int modelCacheFileAccessMode = fcntl(cachedFd, F_GETFL) & O_ACCMODE;
482 if (modelCacheFileAccessMode != O_RDWR)
483 {
484 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "Invalid Access Mode!", cb);
485 return V1_0::ErrorStatus::GENERAL_FAILURE;
486 }
487
488 struct stat statBuffer;
489 if (cachedFd != -1 && fstat(cachedFd, &statBuffer) == 0)
490 {
491 long modelDataSize = statBuffer.st_size;
492 if (modelDataSize > 0)
493 {
494 std::vector<uint8_t> modelData(modelDataSize);
495 pread(cachedFd, modelData.data(), modelData.size(), 0);
496 hashValue ^= CacheDataHandlerInstance().Hash(modelData);
497
498 // For GpuAcc numberOfCachedFiles is 1
499 if (backend == armnn::Compute::GpuAcc)
500 {
501 gpuAccCachedFd = cachedFd;
502 }
503 }
504 }
505 index += numberOfCacheFiles;
506 }
507 }
508 }
509
510 if (!CacheDataHandlerInstance().Validate(token, hashValue))
511 {
512 ALOGW("ArmnnDriverImpl::prepareModelFromCache: ValidateHash() failed!");
513 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "ValidateHash Failed!", cb);
514 return V1_0::ErrorStatus::GENERAL_FAILURE;
515 }
516
517 // Deserialize the network..
518 auto network = armnnDeserializer::IDeserializer::Create()->CreateNetworkFromBinary(dataCacheData);
519
520 // Optimize the network
521 armnn::IOptimizedNetworkPtr optNet(nullptr, nullptr);
522 armnn::OptimizerOptions OptOptions;
523 OptOptions.m_ReduceFp32ToFp16 = float32ToFloat16;
524 OptOptions.m_ProfilingEnabled = options.IsGpuProfilingEnabled();
525
526 armnn::BackendOptions gpuAcc("GpuAcc",
527 {
528 {"FastMathEnabled", options.IsFastMathEnabled()},
529 {"SaveCachedNetwork", saveCachedNetwork},
530 {"CachedNetworkFilePath", options.GetCachedNetworkFilePath()},
531 {"MLGOTuningFilePath", options.GetClMLGOTunedParametersFile()},
532 {"CachedFileDescriptor", gpuAccCachedFd}
533 });
534
535 armnn::BackendOptions cpuAcc("CpuAcc",
536 {
537 {"FastMathEnabled", options.IsFastMathEnabled()},
538 {"NumberOfThreads", options.GetNumberOfThreads()}
539 });
540 OptOptions.m_ModelOptions.push_back(gpuAcc);
541 OptOptions.m_ModelOptions.push_back(cpuAcc);
542
543 std::vector<std::string> errMessages;
544 try
545 {
546 optNet = armnn::Optimize(*network.get(),
547 options.GetBackends(),
548 runtime->GetDeviceSpec(),
549 OptOptions,
550 errMessages);
551 }
552 catch (std::exception& e)
553 {
554 std::stringstream message;
555 message << "Exception (" << e.what() << ") caught from optimize.";
556 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, message.str(), cb);
557 return V1_0::ErrorStatus::NONE;
558 }
559
560 // Check that the optimized network is valid.
561 if (!optNet)
562 {
563 std::stringstream message;
564 message << "Invalid optimized network";
565 for (const std::string& msg : errMessages)
566 {
567 message << "\n" << msg;
568 }
569 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, message.str(), cb);
570 return V1_0::ErrorStatus::NONE;
571 }
572
573 // Export the optimized network graph to a dot file if an output dump directory
574 // has been specified in the drivers' arguments.
575 std::string dotGraphFileName = ExportNetworkGraphToDotFile(*optNet,
576 options.GetRequestInputsAndOutputsDumpDir());
577
578 // Load it into the runtime.
579 armnn::NetworkId netId = 0;
580 std::string msg;
581 armnn::INetworkProperties networkProperties(options.isAsyncModelExecutionEnabled(),
582 MemorySource::Undefined,
583 MemorySource::Undefined,
584 options.IsGpuProfilingEnabled());
585
586 try
587 {
588 if (runtime->LoadNetwork(netId, move(optNet), msg, networkProperties) != armnn::Status::Success)
589 {
590 return FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, msg, cb);
591 }
592 }
593 catch (std::exception& e)
594 {
595 std::stringstream message;
596 message << "Exception (" << e.what() << ") caught from LoadNetwork.";
597 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, message.str(), cb);
598 return V1_0::ErrorStatus::NONE;
599 }
600
601 std::unique_ptr<ArmnnPreparedModel_1_2<hal_1_2::HalPolicy>> preparedModel(
602 new ArmnnPreparedModel_1_2<hal_1_2::HalPolicy>(
603 netId,
604 runtime.get(),
605 options.GetRequestInputsAndOutputsDumpDir(),
606 options.IsGpuProfilingEnabled(),
607 options.isAsyncModelExecutionEnabled(),
608 options.getNoOfArmnnThreads(),
609 true));
610
611 NotifyCallbackAndCheck(cb, V1_0::ErrorStatus::NONE, preparedModel.release());
Kevin Mayec1e5b82020-02-26 17:00:39 +0000612 return V1_0::ErrorStatus::NONE;
Mike Kellyb5fdf382019-06-11 16:35:25 +0100613}
614
615Return<void> ArmnnDriverImpl::getCapabilities_1_2(const armnn::IRuntimePtr& runtime,
616 V1_2::IDevice::getCapabilities_1_2_cb cb)
617{
618 ALOGV("hal_1_2::ArmnnDriverImpl::getCapabilities()");
619
620 V1_2::Capabilities capabilities;
621
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100622 float defaultValue = .1f;
623
Mike Kellyb5fdf382019-06-11 16:35:25 +0100624 if (runtime)
625 {
626 capabilities.relaxedFloat32toFloat16PerformanceScalar.execTime =
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100627 ParseSystemProperty(g_RelaxedFloat32toFloat16PerformanceExecTime, defaultValue);
Mike Kellyb5fdf382019-06-11 16:35:25 +0100628
Kevin May2eaa1192020-04-15 16:50:57 +0100629 capabilities.relaxedFloat32toFloat16PerformanceScalar.powerUsage =
630 ParseSystemProperty(g_RelaxedFloat32toFloat16PerformancePowerUsage, defaultValue);
631
632 capabilities.relaxedFloat32toFloat16PerformanceTensor.execTime =
633 ParseSystemProperty(g_RelaxedFloat32toFloat16PerformanceExecTime, defaultValue);
634
FinnWilliamsArmdf655ee2019-07-24 16:04:18 +0100635 capabilities.relaxedFloat32toFloat16PerformanceTensor.powerUsage =
636 ParseSystemProperty(g_RelaxedFloat32toFloat16PerformancePowerUsage, defaultValue);
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100637
638 // Set the base value for all operand types
Sadik Armagan188675f2021-02-12 17:16:42 +0000639 #if defined(ARMNN_ANDROID_R) || defined(ARMNN_ANDROID_S)
Kevin Mayec1e5b82020-02-26 17:00:39 +0000640 capabilities.operandPerformance = nonExtensionOperandPerformance<HalVersion::V1_2>({FLT_MAX, FLT_MAX});
641 #else
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100642 capabilities.operandPerformance = nonExtensionOperandPerformance({FLT_MAX, FLT_MAX});
Kevin Mayec1e5b82020-02-26 17:00:39 +0000643 #endif
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100644
645 // Load supported operand types
Kevin Mayec1e5b82020-02-26 17:00:39 +0000646 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_FLOAT32,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100647 {
648 .execTime = ParseSystemProperty(g_OperandTypeTensorFloat32PerformanceExecTime, defaultValue),
649 .powerUsage = ParseSystemProperty(g_OperandTypeTensorFloat32PerformancePowerUsage, defaultValue)
650 });
651
Kevin Mayec1e5b82020-02-26 17:00:39 +0000652 update(&capabilities.operandPerformance, V1_2::OperandType::FLOAT32,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100653 {
654 .execTime = ParseSystemProperty(g_OperandTypeFloat32PerformanceExecTime, defaultValue),
655 .powerUsage = ParseSystemProperty(g_OperandTypeFloat32PerformancePowerUsage, defaultValue)
656 });
657
Kevin Mayec1e5b82020-02-26 17:00:39 +0000658 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_FLOAT16,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100659 {
660 .execTime = ParseSystemProperty(g_OperandTypeTensorFloat16PerformanceExecTime, defaultValue),
661 .powerUsage = ParseSystemProperty(g_OperandTypeTensorFloat16PerformancePowerUsage, defaultValue)
662 });
663
Kevin Mayec1e5b82020-02-26 17:00:39 +0000664 update(&capabilities.operandPerformance, V1_2::OperandType::FLOAT16,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100665 {
666 .execTime = ParseSystemProperty(g_OperandTypeFloat16PerformanceExecTime, defaultValue),
667 .powerUsage = ParseSystemProperty(g_OperandTypeFloat16PerformancePowerUsage, defaultValue)
668 });
669
Kevin Mayec1e5b82020-02-26 17:00:39 +0000670 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_QUANT8_ASYMM,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100671 {
672 .execTime = ParseSystemProperty(g_OperandTypeTensorQuant8AsymmPerformanceExecTime, defaultValue),
673 .powerUsage = ParseSystemProperty(g_OperandTypeTensorQuant8AsymmPerformancePowerUsage, defaultValue)
674 });
675
Kevin Mayec1e5b82020-02-26 17:00:39 +0000676 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_QUANT8_SYMM,
Pablo Tellofb45e2f2019-10-18 16:51:57 +0100677 {
678 .execTime = ParseSystemProperty(g_OperandTypeTensorQuant8SymmPerformanceExecTime, defaultValue),
679 .powerUsage = ParseSystemProperty(g_OperandTypeTensorQuant8SymmPerformancePowerUsage, defaultValue)
680 });
681
Kevin Mayec1e5b82020-02-26 17:00:39 +0000682 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_QUANT16_SYMM,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100683 {
684 .execTime = ParseSystemProperty(g_OperandTypeTensorQuant16SymmPerformanceExecTime, defaultValue),
685 .powerUsage = ParseSystemProperty(g_OperandTypeTensorQuant16SymmPerformancePowerUsage, defaultValue)
686 });
687
Kevin Mayec1e5b82020-02-26 17:00:39 +0000688 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL,
Kevin May87cb7612019-11-11 17:30:35 +0000689 {
690 .execTime =
691 ParseSystemProperty(g_OperandTypeTensorQuant8SymmPerChannelPerformanceExecTime, defaultValue),
692 .powerUsage =
693 ParseSystemProperty(g_OperandTypeTensorQuant8SymmPerChannelPerformancePowerUsage, defaultValue)
694 });
695
Kevin Mayec1e5b82020-02-26 17:00:39 +0000696 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_INT32,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100697 {
698 .execTime = ParseSystemProperty(g_OperandTypeTensorInt32PerformanceExecTime, defaultValue),
699 .powerUsage = ParseSystemProperty(g_OperandTypeTensorInt32PerformancePowerUsage, defaultValue)
700 });
701
Kevin Mayec1e5b82020-02-26 17:00:39 +0000702 update(&capabilities.operandPerformance, V1_2::OperandType::INT32,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100703 {
704 .execTime = ParseSystemProperty(g_OperandTypeInt32PerformanceExecTime, defaultValue),
705 .powerUsage = ParseSystemProperty(g_OperandTypeInt32PerformancePowerUsage, defaultValue)
706 });
Mike Kellyb5fdf382019-06-11 16:35:25 +0100707
Kevin Mayec1e5b82020-02-26 17:00:39 +0000708 cb(V1_0::ErrorStatus::NONE, capabilities);
Mike Kellyb5fdf382019-06-11 16:35:25 +0100709 }
710 else
711 {
Kevin May2eaa1192020-04-15 16:50:57 +0100712 capabilities.relaxedFloat32toFloat16PerformanceScalar.execTime = 0;
713 capabilities.relaxedFloat32toFloat16PerformanceScalar.powerUsage = 0;
714 capabilities.relaxedFloat32toFloat16PerformanceTensor.execTime = 0;
715 capabilities.relaxedFloat32toFloat16PerformanceTensor.powerUsage = 0;
Mike Kellyb5fdf382019-06-11 16:35:25 +0100716
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100717 // Set the base value for all operand types
Sadik Armagan188675f2021-02-12 17:16:42 +0000718 #if defined(ARMNN_ANDROID_R) || defined(ARMNN_ANDROID_S)
Kevin Mayec1e5b82020-02-26 17:00:39 +0000719 capabilities.operandPerformance = nonExtensionOperandPerformance<HalVersion::V1_2>({0.f, 0.0f});
720 #else
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100721 capabilities.operandPerformance = nonExtensionOperandPerformance({0.f, 0.0f});
Kevin Mayec1e5b82020-02-26 17:00:39 +0000722 #endif
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100723
Kevin Mayec1e5b82020-02-26 17:00:39 +0000724 cb(V1_0::ErrorStatus::DEVICE_UNAVAILABLE, capabilities);
Mike Kellyb5fdf382019-06-11 16:35:25 +0100725 }
726
727 return Void();
728}
729
730} // namespace hal_1_2
Kevin Mayec1e5b82020-02-26 17:00:39 +0000731} // namespace armnn_driver