blob: 3274a8abc226a32720e8ea6707a93b1bfe145bec [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 Armaganee6818b2021-11-05 14:41:52 +0000318
319 if (dataCacheHandle[0]->data[0] < 0)
320 {
321 ALOGW("ArmnnDriverImpl::prepareArmnnModel_1_3: Cannot cache the data, fd < 0");
322 NotifyCallbackAndCheck(cb, V1_0::ErrorStatus::NONE, preparedModel.release());
323 return V1_0::ErrorStatus::NONE;
324 }
325
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100326 int dataCacheFileAccessMode = fcntl(dataCacheHandle[0]->data[0], F_GETFL) & O_ACCMODE;
327 if (dataCacheFileAccessMode != O_RDWR)
328 {
329 ALOGW("ArmnnDriverImpl::prepareModelFromCache_1_2(): Invalid Access Mode.");
330 NotifyCallbackAndCheck(cb, V1_0::ErrorStatus::NONE, preparedModel.release());
331 return V1_0::ErrorStatus::NONE;
332 }
333
334 write(dataCacheHandle[0]->data[0], dataCacheData.data(), dataCacheData.size());
335 hashValue = CacheDataHandlerInstance().Hash(dataCacheData);
336 }
337
338 if (modelCacheHandle.size() > 0)
339 {
340 if (modelCacheHandle.size() != numberOfCachedModelFiles)
341 {
342 NotifyCallbackAndCheck(cb, V1_0::ErrorStatus::NONE, preparedModel.release());
343 return V1_0::ErrorStatus::NONE;
344 }
345 for (uint32_t i = 0; i < modelCacheHandle.size(); ++i)
346 {
347 if (modelCacheHandle[i]->numFds == 1)
348 {
349 int modelCacheFileAccessMode = fcntl(modelCacheHandle[i]->data[0], F_GETFL) & O_ACCMODE;
350 if (modelCacheFileAccessMode != O_RDONLY)
351 {
352 struct stat statBuffer;
353 if (fstat(modelCacheHandle[i]->data[0], &statBuffer) == 0)
354 {
355 long modelDataSize = statBuffer.st_size;
356 if (modelDataSize > 0)
357 {
358 std::vector <uint8_t> modelData(modelDataSize);
359 pread(modelCacheHandle[i]->data[0], modelData.data(), modelData.size(), 0);
360 hashValue ^= CacheDataHandlerInstance().Hash(modelData);
361 }
362 }
363 }
364 }
365 }
366 }
367 if (hashValue != 0)
368 {
369 CacheDataHandlerInstance().Register(token, hashValue, dataCacheData.size());
Mike Kellyb5fdf382019-06-11 16:35:25 +0100370 }
371
Kevin Mayec1e5b82020-02-26 17:00:39 +0000372 NotifyCallbackAndCheck(cb, V1_0::ErrorStatus::NONE, preparedModel.release());
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100373 return V1_0::ErrorStatus::NONE;
374}
Mike Kellyb5fdf382019-06-11 16:35:25 +0100375
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100376Return<V1_0::ErrorStatus> ArmnnDriverImpl::prepareModelFromCache(
377 const armnn::IRuntimePtr& runtime,
378 const DriverOptions& options,
379 const android::hardware::hidl_vec<android::hardware::hidl_handle>& modelCacheHandle,
380 const android::hardware::hidl_vec<android::hardware::hidl_handle>& dataCacheHandle,
381 const HidlToken& token,
382 const android::sp<V1_2::IPreparedModelCallback>& cb,
383 bool float32ToFloat16)
384{
385 ALOGV("ArmnnDriverImpl::prepareModelFromCache()");
386
387 if (cb.get() == nullptr)
388 {
389 ALOGW("ArmnnDriverImpl::prepareModelFromCache: Invalid callback passed to prepareModel");
390 return V1_0::ErrorStatus::INVALID_ARGUMENT;
391 }
392
393 if (!runtime)
394 {
395 return FailPrepareModel(V1_0::ErrorStatus::DEVICE_UNAVAILABLE, "Device unavailable", cb);
396 }
397
398 if (token.size() != ANEURALNETWORKS_BYTE_SIZE_OF_CACHE_TOKEN)
399 {
400 FailPrepareModel(V1_0::ErrorStatus::INVALID_ARGUMENT, "Invalid token passed!", cb);
401 return V1_0::ErrorStatus::INVALID_ARGUMENT;
402 }
403
404 // DataCacheHandle size should always be 1
405 // Arm NN model
406 if (dataCacheHandle.size() != 1)
407 {
408 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "No data cache!", cb);
409 return V1_0::ErrorStatus::GENERAL_FAILURE;
410 }
411
412 // Check if model files cached they match the expected value
413 unsigned int numberOfCachedModelFiles = 0;
414 for (auto& backend : options.GetBackends())
415 {
416 numberOfCachedModelFiles += GetNumberOfCacheFiles(backend);
417 }
418 if (modelCacheHandle.size() != numberOfCachedModelFiles)
419 {
420 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "Invalid model cache!", cb);
421 return V1_0::ErrorStatus::GENERAL_FAILURE;
422 }
423
424 if (dataCacheHandle[0]->numFds != 1)
425 {
426 ALOGW("ArmnnDriverImpl::prepareModelFromCache: Cannot read from the cache data, numFds != 1.");
427 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "No data cache!", cb);
428 return V1_0::ErrorStatus::GENERAL_FAILURE;
429 }
430
Sadik Armaganee6818b2021-11-05 14:41:52 +0000431 if (dataCacheHandle[0]->data[0] < 0)
432 {
433 ALOGW("ArmnnDriverImpl::prepareModelFromCache: Cannot read from the cache data, fd < 0");
434 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "No data cache!", cb);
435 return V1_0::ErrorStatus::GENERAL_FAILURE;
436 }
437
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100438 int dataCacheFileAccessMode = fcntl(dataCacheHandle[0]->data[0], F_GETFL) & O_ACCMODE;
439 if (dataCacheFileAccessMode != O_RDWR)
440 {
441 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "Invalid Access Mode!", cb);
442 return V1_0::ErrorStatus::GENERAL_FAILURE;
443 }
444
445 auto dataSize = CacheDataHandlerInstance().GetCacheSize(token);
446 if (dataSize == 0)
447 {
448 ALOGW("ArmnnDriverImpl::prepareModelFromCache: Invalid data to deserialize!");
449 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "Invalid data to deserialize!", cb);
450 return V1_0::ErrorStatus::GENERAL_FAILURE;
451 }
452
453 int offset = 0;
454 {
455 struct stat statBuffer;
456 if (fstat(dataCacheHandle[0]->data[0], &statBuffer) == 0)
457 {
458 unsigned long bufferSize = statBuffer.st_size;
Sadik Armaganee6818b2021-11-05 14:41:52 +0000459 if (bufferSize != dataSize)
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100460 {
461 ALOGW("ArmnnDriverImpl::prepareModelFromCache: Invalid data to deserialize!");
462 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "Invalid data to deserialize!", cb);
463 return V1_0::ErrorStatus::GENERAL_FAILURE;
464 }
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100465 }
466 }
467 std::vector<uint8_t> dataCacheData(dataSize);
468 pread(dataCacheHandle[0]->data[0], dataCacheData.data(), dataCacheData.size(), offset);
469 auto hashValue = CacheDataHandlerInstance().Hash(dataCacheData);
470
471 int gpuAccCachedFd = -1;
472 bool saveCachedNetwork = false;
473 if (modelCacheHandle.size() > 0)
474 {
475 unsigned int index = 0;
476 for (auto& backend : options.GetBackends())
477 {
478 // modelCacheHandle size should be equal to numberOfCachedModelFiles
479 // modelCacheHandle vector should be in same order as backends
480 auto numberOfCacheFiles = GetNumberOfCacheFiles(backend);
481 if (numberOfCacheFiles > 0)
482 {
483 if (modelCacheHandle[index]->numFds != 1)
484 {
485 ALOGW("ArmnnDriverImpl::prepareModelFromCache: Cannot read from the model cache, numFds != 1.");
486 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE,
487 "Cannot read from the model cache, numFds != 1.", cb);
488 return V1_0::ErrorStatus::GENERAL_FAILURE;
489 }
490 auto cachedFd = modelCacheHandle[index]->data[0];
491
492 int modelCacheFileAccessMode = fcntl(cachedFd, F_GETFL) & O_ACCMODE;
493 if (modelCacheFileAccessMode != O_RDWR)
494 {
495 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "Invalid Access Mode!", cb);
496 return V1_0::ErrorStatus::GENERAL_FAILURE;
497 }
498
499 struct stat statBuffer;
500 if (cachedFd != -1 && fstat(cachedFd, &statBuffer) == 0)
501 {
502 long modelDataSize = statBuffer.st_size;
Sadik Armaganee6818b2021-11-05 14:41:52 +0000503 if (modelDataSize <= 0)
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100504 {
Sadik Armaganee6818b2021-11-05 14:41:52 +0000505 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "Wrong cached model size!", cb);
506 return V1_0::ErrorStatus::NONE;
507 }
508 std::vector<uint8_t> modelData(modelDataSize);
509 pread(cachedFd, modelData.data(), modelData.size(), 0);
510 hashValue ^= CacheDataHandlerInstance().Hash(modelData);
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100511
Sadik Armaganee6818b2021-11-05 14:41:52 +0000512 // For GpuAcc numberOfCachedFiles is 1
513 if (backend == armnn::Compute::GpuAcc)
514 {
515 gpuAccCachedFd = cachedFd;
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100516 }
517 }
518 index += numberOfCacheFiles;
519 }
520 }
521 }
522
Sadik Armaganee6818b2021-11-05 14:41:52 +0000523 if (!CacheDataHandlerInstance().Validate(token, hashValue, dataCacheData.size()))
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100524 {
525 ALOGW("ArmnnDriverImpl::prepareModelFromCache: ValidateHash() failed!");
526 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, "ValidateHash Failed!", cb);
527 return V1_0::ErrorStatus::GENERAL_FAILURE;
528 }
529
530 // Deserialize the network..
Sadik Armaganee6818b2021-11-05 14:41:52 +0000531 armnn::INetworkPtr network = armnn::INetworkPtr(nullptr, [](armnn::INetwork*){});
532 try
533 {
534 network = armnnDeserializer::IDeserializer::Create()->CreateNetworkFromBinary(dataCacheData);
535 }
536 catch (std::exception& e)
537 {
538 std::stringstream message;
539 message << "Exception (" << e.what() << ") caught from Deserializer.";
540 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, message.str(), cb);
541 return V1_0::ErrorStatus::GENERAL_FAILURE;
542 }
Sadik Armagan0a2dfab2021-10-06 16:41:44 +0100543
544 // Optimize the network
545 armnn::IOptimizedNetworkPtr optNet(nullptr, nullptr);
546 armnn::OptimizerOptions OptOptions;
547 OptOptions.m_ReduceFp32ToFp16 = float32ToFloat16;
548 OptOptions.m_ProfilingEnabled = options.IsGpuProfilingEnabled();
549
550 armnn::BackendOptions gpuAcc("GpuAcc",
551 {
552 {"FastMathEnabled", options.IsFastMathEnabled()},
553 {"SaveCachedNetwork", saveCachedNetwork},
554 {"CachedNetworkFilePath", options.GetCachedNetworkFilePath()},
555 {"MLGOTuningFilePath", options.GetClMLGOTunedParametersFile()},
556 {"CachedFileDescriptor", gpuAccCachedFd}
557 });
558
559 armnn::BackendOptions cpuAcc("CpuAcc",
560 {
561 {"FastMathEnabled", options.IsFastMathEnabled()},
562 {"NumberOfThreads", options.GetNumberOfThreads()}
563 });
564 OptOptions.m_ModelOptions.push_back(gpuAcc);
565 OptOptions.m_ModelOptions.push_back(cpuAcc);
566
567 std::vector<std::string> errMessages;
568 try
569 {
570 optNet = armnn::Optimize(*network.get(),
571 options.GetBackends(),
572 runtime->GetDeviceSpec(),
573 OptOptions,
574 errMessages);
575 }
576 catch (std::exception& e)
577 {
578 std::stringstream message;
579 message << "Exception (" << e.what() << ") caught from optimize.";
580 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, message.str(), cb);
581 return V1_0::ErrorStatus::NONE;
582 }
583
584 // Check that the optimized network is valid.
585 if (!optNet)
586 {
587 std::stringstream message;
588 message << "Invalid optimized network";
589 for (const std::string& msg : errMessages)
590 {
591 message << "\n" << msg;
592 }
593 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, message.str(), cb);
594 return V1_0::ErrorStatus::NONE;
595 }
596
597 // Export the optimized network graph to a dot file if an output dump directory
598 // has been specified in the drivers' arguments.
599 std::string dotGraphFileName = ExportNetworkGraphToDotFile(*optNet,
600 options.GetRequestInputsAndOutputsDumpDir());
601
602 // Load it into the runtime.
603 armnn::NetworkId netId = 0;
604 std::string msg;
605 armnn::INetworkProperties networkProperties(options.isAsyncModelExecutionEnabled(),
606 MemorySource::Undefined,
607 MemorySource::Undefined,
608 options.IsGpuProfilingEnabled());
609
610 try
611 {
612 if (runtime->LoadNetwork(netId, move(optNet), msg, networkProperties) != armnn::Status::Success)
613 {
614 return FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, msg, cb);
615 }
616 }
617 catch (std::exception& e)
618 {
619 std::stringstream message;
620 message << "Exception (" << e.what() << ") caught from LoadNetwork.";
621 FailPrepareModel(V1_0::ErrorStatus::GENERAL_FAILURE, message.str(), cb);
622 return V1_0::ErrorStatus::NONE;
623 }
624
625 std::unique_ptr<ArmnnPreparedModel_1_2<hal_1_2::HalPolicy>> preparedModel(
626 new ArmnnPreparedModel_1_2<hal_1_2::HalPolicy>(
627 netId,
628 runtime.get(),
629 options.GetRequestInputsAndOutputsDumpDir(),
630 options.IsGpuProfilingEnabled(),
631 options.isAsyncModelExecutionEnabled(),
632 options.getNoOfArmnnThreads(),
633 true));
634
635 NotifyCallbackAndCheck(cb, V1_0::ErrorStatus::NONE, preparedModel.release());
Kevin Mayec1e5b82020-02-26 17:00:39 +0000636 return V1_0::ErrorStatus::NONE;
Mike Kellyb5fdf382019-06-11 16:35:25 +0100637}
638
639Return<void> ArmnnDriverImpl::getCapabilities_1_2(const armnn::IRuntimePtr& runtime,
640 V1_2::IDevice::getCapabilities_1_2_cb cb)
641{
642 ALOGV("hal_1_2::ArmnnDriverImpl::getCapabilities()");
643
644 V1_2::Capabilities capabilities;
645
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100646 float defaultValue = .1f;
647
Mike Kellyb5fdf382019-06-11 16:35:25 +0100648 if (runtime)
649 {
650 capabilities.relaxedFloat32toFloat16PerformanceScalar.execTime =
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100651 ParseSystemProperty(g_RelaxedFloat32toFloat16PerformanceExecTime, defaultValue);
Mike Kellyb5fdf382019-06-11 16:35:25 +0100652
Kevin May2eaa1192020-04-15 16:50:57 +0100653 capabilities.relaxedFloat32toFloat16PerformanceScalar.powerUsage =
654 ParseSystemProperty(g_RelaxedFloat32toFloat16PerformancePowerUsage, defaultValue);
655
656 capabilities.relaxedFloat32toFloat16PerformanceTensor.execTime =
657 ParseSystemProperty(g_RelaxedFloat32toFloat16PerformanceExecTime, defaultValue);
658
FinnWilliamsArmdf655ee2019-07-24 16:04:18 +0100659 capabilities.relaxedFloat32toFloat16PerformanceTensor.powerUsage =
660 ParseSystemProperty(g_RelaxedFloat32toFloat16PerformancePowerUsage, defaultValue);
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100661
662 // Set the base value for all operand types
Sadik Armagan188675f2021-02-12 17:16:42 +0000663 #if defined(ARMNN_ANDROID_R) || defined(ARMNN_ANDROID_S)
Kevin Mayec1e5b82020-02-26 17:00:39 +0000664 capabilities.operandPerformance = nonExtensionOperandPerformance<HalVersion::V1_2>({FLT_MAX, FLT_MAX});
665 #else
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100666 capabilities.operandPerformance = nonExtensionOperandPerformance({FLT_MAX, FLT_MAX});
Kevin Mayec1e5b82020-02-26 17:00:39 +0000667 #endif
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100668
669 // Load supported operand types
Kevin Mayec1e5b82020-02-26 17:00:39 +0000670 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_FLOAT32,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100671 {
672 .execTime = ParseSystemProperty(g_OperandTypeTensorFloat32PerformanceExecTime, defaultValue),
673 .powerUsage = ParseSystemProperty(g_OperandTypeTensorFloat32PerformancePowerUsage, defaultValue)
674 });
675
Kevin Mayec1e5b82020-02-26 17:00:39 +0000676 update(&capabilities.operandPerformance, V1_2::OperandType::FLOAT32,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100677 {
678 .execTime = ParseSystemProperty(g_OperandTypeFloat32PerformanceExecTime, defaultValue),
679 .powerUsage = ParseSystemProperty(g_OperandTypeFloat32PerformancePowerUsage, defaultValue)
680 });
681
Kevin Mayec1e5b82020-02-26 17:00:39 +0000682 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_FLOAT16,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100683 {
684 .execTime = ParseSystemProperty(g_OperandTypeTensorFloat16PerformanceExecTime, defaultValue),
685 .powerUsage = ParseSystemProperty(g_OperandTypeTensorFloat16PerformancePowerUsage, defaultValue)
686 });
687
Kevin Mayec1e5b82020-02-26 17:00:39 +0000688 update(&capabilities.operandPerformance, V1_2::OperandType::FLOAT16,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100689 {
690 .execTime = ParseSystemProperty(g_OperandTypeFloat16PerformanceExecTime, defaultValue),
691 .powerUsage = ParseSystemProperty(g_OperandTypeFloat16PerformancePowerUsage, defaultValue)
692 });
693
Kevin Mayec1e5b82020-02-26 17:00:39 +0000694 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_QUANT8_ASYMM,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100695 {
696 .execTime = ParseSystemProperty(g_OperandTypeTensorQuant8AsymmPerformanceExecTime, defaultValue),
697 .powerUsage = ParseSystemProperty(g_OperandTypeTensorQuant8AsymmPerformancePowerUsage, defaultValue)
698 });
699
Kevin Mayec1e5b82020-02-26 17:00:39 +0000700 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_QUANT8_SYMM,
Pablo Tellofb45e2f2019-10-18 16:51:57 +0100701 {
702 .execTime = ParseSystemProperty(g_OperandTypeTensorQuant8SymmPerformanceExecTime, defaultValue),
703 .powerUsage = ParseSystemProperty(g_OperandTypeTensorQuant8SymmPerformancePowerUsage, defaultValue)
704 });
705
Kevin Mayec1e5b82020-02-26 17:00:39 +0000706 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_QUANT16_SYMM,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100707 {
708 .execTime = ParseSystemProperty(g_OperandTypeTensorQuant16SymmPerformanceExecTime, defaultValue),
709 .powerUsage = ParseSystemProperty(g_OperandTypeTensorQuant16SymmPerformancePowerUsage, defaultValue)
710 });
711
Kevin Mayec1e5b82020-02-26 17:00:39 +0000712 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL,
Kevin May87cb7612019-11-11 17:30:35 +0000713 {
714 .execTime =
715 ParseSystemProperty(g_OperandTypeTensorQuant8SymmPerChannelPerformanceExecTime, defaultValue),
716 .powerUsage =
717 ParseSystemProperty(g_OperandTypeTensorQuant8SymmPerChannelPerformancePowerUsage, defaultValue)
718 });
719
Kevin Mayec1e5b82020-02-26 17:00:39 +0000720 update(&capabilities.operandPerformance, V1_2::OperandType::TENSOR_INT32,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100721 {
722 .execTime = ParseSystemProperty(g_OperandTypeTensorInt32PerformanceExecTime, defaultValue),
723 .powerUsage = ParseSystemProperty(g_OperandTypeTensorInt32PerformancePowerUsage, defaultValue)
724 });
725
Kevin Mayec1e5b82020-02-26 17:00:39 +0000726 update(&capabilities.operandPerformance, V1_2::OperandType::INT32,
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100727 {
728 .execTime = ParseSystemProperty(g_OperandTypeInt32PerformanceExecTime, defaultValue),
729 .powerUsage = ParseSystemProperty(g_OperandTypeInt32PerformancePowerUsage, defaultValue)
730 });
Mike Kellyb5fdf382019-06-11 16:35:25 +0100731
Kevin Mayec1e5b82020-02-26 17:00:39 +0000732 cb(V1_0::ErrorStatus::NONE, capabilities);
Mike Kellyb5fdf382019-06-11 16:35:25 +0100733 }
734 else
735 {
Kevin May2eaa1192020-04-15 16:50:57 +0100736 capabilities.relaxedFloat32toFloat16PerformanceScalar.execTime = 0;
737 capabilities.relaxedFloat32toFloat16PerformanceScalar.powerUsage = 0;
738 capabilities.relaxedFloat32toFloat16PerformanceTensor.execTime = 0;
739 capabilities.relaxedFloat32toFloat16PerformanceTensor.powerUsage = 0;
Mike Kellyb5fdf382019-06-11 16:35:25 +0100740
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100741 // Set the base value for all operand types
Sadik Armagan188675f2021-02-12 17:16:42 +0000742 #if defined(ARMNN_ANDROID_R) || defined(ARMNN_ANDROID_S)
Kevin Mayec1e5b82020-02-26 17:00:39 +0000743 capabilities.operandPerformance = nonExtensionOperandPerformance<HalVersion::V1_2>({0.f, 0.0f});
744 #else
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100745 capabilities.operandPerformance = nonExtensionOperandPerformance({0.f, 0.0f});
Kevin Mayec1e5b82020-02-26 17:00:39 +0000746 #endif
Ferran Balaguerd7c8eb92019-07-01 13:37:44 +0100747
Kevin Mayec1e5b82020-02-26 17:00:39 +0000748 cb(V1_0::ErrorStatus::DEVICE_UNAVAILABLE, capabilities);
Mike Kellyb5fdf382019-06-11 16:35:25 +0100749 }
750
751 return Void();
752}
753
754} // namespace hal_1_2
Kevin Mayec1e5b82020-02-26 17:00:39 +0000755} // namespace armnn_driver