forked from pytorch/executorch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQnnManager.cpp
More file actions
386 lines (345 loc) · 13.2 KB
/
QnnManager.cpp
File metadata and controls
386 lines (345 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/*
* Copyright (c) Qualcomm Innovation Center, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <executorch/backends/qualcomm/runtime/QnnManager.h>
#include <executorch/backends/qualcomm/runtime/SharedBuffer.h>
#include <executorch/backends/qualcomm/runtime/Utils.h>
#include <executorch/backends/qualcomm/runtime/backends/QnnImplementation.h>
#include <cstdlib>
#include <cstring>
#include <fstream>
namespace torch {
namespace executor {
namespace qnn {
QnnManager::~QnnManager() {
backend_params_ptr_.reset(new BackendConfigParameters());
logger_.reset();
qnn_loaded_backend_.TerminateAllBackends();
}
QnnManager::QnnManager(
const QnnExecuTorchOptions* options,
const QnnExecuTorchContextBinary& qnn_executorch_context_binary)
: qnn_context_blob_(qnn_executorch_context_binary),
qnn_loaded_backend_(""),
// options' life cycle is decided by compiler specs which is
// kept by executorch runtime framework
// please pay attention to any potential seg fault
options_(options) {
QnnExecuTorchBackendType backend_type =
options->backend_options()->backend_type();
std::string library_path = options->library_path()->str();
if (options->log_level() >= QnnExecuTorchLogLevel::kLogLevelInfo) {
QNN_EXECUTORCH_LOG_INFO(
"soc_model in soc_info: %s",
EnumNameQcomChipset(options_->soc_info()->soc_model()));
QNN_EXECUTORCH_LOG_INFO(
"backend_type: %s", EnumNameQnnExecuTorchBackendType(backend_type));
QNN_EXECUTORCH_LOG_INFO("graph_name: %s", options_->graph_name()->c_str());
QNN_EXECUTORCH_LOG_INFO("library_path: %s", library_path.c_str());
QNN_EXECUTORCH_LOG_INFO(
"tensor_dump_output_path: %s",
options_->tensor_dump_output_path()->c_str());
QNN_EXECUTORCH_LOG_INFO(
"log_level: %s", EnumNameQnnExecuTorchLogLevel(options_->log_level()));
QNN_EXECUTORCH_LOG_INFO(
"profile_level: %s",
EnumNameQnnExecuTorchProfileLevel(options_->profile_level()));
QNN_EXECUTORCH_LOG_INFO(
"the size of qnn context binary: %d",
qnn_executorch_context_binary.nbytes);
QNN_EXECUTORCH_LOG_INFO(
"Is on-device graph construction: %d", options->online_prepare());
QNN_EXECUTORCH_LOG_INFO(
"Enable shared buffer: %d", options->shared_buffer());
}
if (library_path.empty()) {
switch (backend_type) {
case QnnExecuTorchBackendType::kHtpBackend:
library_path = htp_library_name_;
break;
case QnnExecuTorchBackendType::kDspBackend:
library_path = dsp_library_name_;
break;
case QnnExecuTorchBackendType::kGpuBackend:
library_path = gpu_library_name_;
break;
default:
QNN_EXECUTORCH_LOG_ERROR("Unknown backend type: %d", backend_type);
break;
}
}
qnn_loaded_backend_ = QnnImplementation(library_path);
backend_params_ptr_ = std::make_unique<BackendConfigParameters>();
}
Error QnnManager::LoadQnnLibrary() {
Error ret = qnn_loaded_backend_.Load(nullptr);
return ret;
}
Error QnnManager::RegisterMem(
void* data_ptr,
const std::shared_ptr<TensorWrapper>& tensor_wrapper) {
SharedBuffer& shared_buffer_manager = SharedBuffer::GetSharedBufferManager();
// Not enable shared buffer
if (!options_->shared_buffer())
return Error::Internal;
if (backend_params_ptr_->qnn_mem_manager_ptr_ == nullptr) {
QNN_EXECUTORCH_LOG_WARN(
"Backend %s doesn't supported shared buffer.",
EnumNameQnnExecuTorchBackendType(
options_->backend_options()->backend_type()));
return Error::Internal;
}
if (!shared_buffer_manager.IsAllocated(data_ptr)) {
// It means two scenarios here:
// 1. the input and output partitioned graph
// 2. Actually, user doesn't allocate shared buffer with
// QnnExecuTorchAllocCustomMem API
return Error::Internal;
} else if (backend_params_ptr_->qnn_mem_manager_ptr_->IsRegistered(
tensor_wrapper->GetMemHandle())) {
if (options_->log_level() >= QnnExecuTorchLogLevel::kLogLevelInfo)
QNN_EXECUTORCH_LOG_INFO(
"Tensor name %s has been registered shared memory.",
tensor_wrapper->GetName().c_str());
return Error::Ok;
}
int32_t mem_fd = SharedBuffer::GetSharedBufferManager().MemToFd(data_ptr);
if (mem_fd == -1) {
QNN_EXECUTORCH_LOG_WARN(
"Tensor name %s is failed to get file descriptor.",
tensor_wrapper->GetName().c_str());
return Error::Internal;
}
ET_CHECK_OR_RETURN_ERROR(
backend_params_ptr_->qnn_mem_manager_ptr_->RegisterMem(
tensor_wrapper, mem_fd) == Error::Ok,
Internal,
"Fail to register to shared memory.");
return Error::Ok;
}
Error QnnManager::Init() {
ET_CHECK_OR_RETURN_ERROR(
LoadQnnLibrary() == Error::Ok, Internal, "Fail to load Qnn library");
logger_ = std::make_unique<QnnLogger>(
qnn_loaded_backend_, LoggingCallback, options_->log_level());
if (backend_params_ptr_->backend_init_state_ ==
BackendInitializeState::UNINITIALIZED) {
QNN_EXECUTORCH_LOG_INFO(
"Initialize Qnn backend "
"parameters for Qnn executorch backend type %d",
options_->backend_options()->backend_type());
backend_params_ptr_ = QnnBackendFactory().Create(
qnn_loaded_backend_, logger_.get(), qnn_context_blob_, options_);
ET_CHECK_OR_RETURN_ERROR(
backend_params_ptr_->qnn_backend_ptr_->Configure() == Error::Ok,
Internal,
"Fail to configure Qnn backend");
ET_CHECK_OR_RETURN_ERROR(
backend_params_ptr_->qnn_device_ptr_->Configure() == Error::Ok,
Internal,
"Fail to configure Qnn device");
ET_CHECK_OR_RETURN_ERROR(
backend_params_ptr_->qnn_context_ptr_->Configure() == Error::Ok,
Internal,
"Fail to configure Qnn context");
ET_CHECK_OR_RETURN_ERROR(
backend_params_ptr_->qnn_graph_ptr_->Configure() == Error::Ok,
Internal,
"Fail to configure Qnn graph");
backend_params_ptr_->backend_init_state_ =
BackendInitializeState::INITIALIZED;
}
return Error::Ok;
}
Error QnnManager::AllocateTensor() {
std::vector<Qnn_Tensor_t> input_tensors =
backend_params_ptr_->qnn_context_ptr_->GetGraphInputs();
std::vector<Qnn_Tensor_t> output_tensors =
backend_params_ptr_->qnn_context_ptr_->GetGraphOutputs();
for (auto& tensor : input_tensors) {
std::shared_ptr<TensorWrapper> tensor_wrapper = CreateTensorWrapper(tensor);
tensor_wrapper->UpdateQnnTensorMeta(tensor);
input_tensors_.emplace_back(std::move(tensor_wrapper));
}
for (auto& tensor : output_tensors) {
std::shared_ptr<TensorWrapper> tensor_wrapper = CreateTensorWrapper(tensor);
tensor_wrapper->UpdateQnnTensorMeta(tensor);
if (IsTensorDump()) {
tensor_wrapper->AllocateDataBuffer();
}
output_tensors_.emplace_back(std::move(tensor_wrapper));
}
return Error::Ok;
}
Error QnnManager::AllocateTensor(
std::vector<std::shared_ptr<TensorWrapper>>& inputs,
std::vector<std::shared_ptr<TensorWrapper>>& outputs) {
input_tensors_ = std::move(inputs);
for (auto& output_tensor : outputs) {
if (IsTensorDump()) {
output_tensor->AllocateDataBuffer();
}
}
output_tensors_ = std::move(outputs);
return Error::Ok;
}
Error QnnManager::Execute(
const std::vector<Qnn_Tensor_t>& input_tensor_structs,
std::vector<Qnn_Tensor_t>& output_tensor_structs) {
Qnn_ErrorHandle_t error = QNN_SUCCESS;
error = backend_params_ptr_->qnn_graph_ptr_->GraphExecute(
input_tensor_structs, output_tensor_structs);
if (error != QNN_SUCCESS) {
QNN_EXECUTORCH_LOG_ERROR(
"qnn_graph_execute failed. Error %d", QNN_GET_ERROR_CODE(error));
return Error::Internal;
}
if (IsTensorDump()) {
// TODO: Need to handle the graph which is partitioned.
// Maybe we could use graph name.
std::string dir = options_->tensor_dump_output_path()->str() + "/Result/";
CreateDirectory(dir);
QNN_EXECUTORCH_LOG_INFO("Dump tensor to the path: %s", dir.c_str());
for (std::size_t out_idx = 0; out_idx < output_tensor_structs.size();
++out_idx) {
const Qnn_Tensor_t& output_tensor = output_tensor_structs[out_idx];
std::string output_path =
dir + QNN_VER_PTR(output_tensor)->name + "_tensor.raw";
std::ofstream fout(output_path, std::ios::binary);
if (fout.fail()) {
QNN_EXECUTORCH_LOG_ERROR(
"Dump tensor name: %s Failed.", QNN_VER_PTR(output_tensor)->name);
return Error::Internal;
}
fout.write(
static_cast<const char*>(QNN_VER_PTR(output_tensor)->clientBuf.data),
QNN_VER_PTR(output_tensor)->clientBuf.dataSize);
}
}
return Error::Ok;
}
Error QnnManager::ProfileExecuteData(EventTracer* event_tracer) {
Qnn_ErrorHandle_t error = QNN_SUCCESS;
if (options_->profile_level() != QnnExecuTorchProfileLevel::kProfileOff) {
error =
backend_params_ptr_->qnn_graph_ptr_->ProfileExecuteData(event_tracer);
if (error != QNN_SUCCESS) {
QNN_EXECUTORCH_LOG_ERROR(
" Failed to profile. Error %d", QNN_GET_ERROR_CODE(error));
return Error::Internal;
}
}
return Error::Ok;
}
void QnnManager::Destroy() {
QNN_EXECUTORCH_LOG_INFO("Destroy Qnn backend parameters");
backend_params_ptr_.reset(new BackendConfigParameters());
logger_.reset();
qnn_loaded_backend_.TerminateAllBackends();
}
bool QnnManager::IsNodeSupportedByBackend(
std::vector<std::shared_ptr<OpWrapper>>& op_wrappers) {
Qnn_ErrorHandle_t error = QNN_SUCCESS;
for (std::shared_ptr<OpWrapper>& op_wrapper : op_wrappers) {
for (const auto& param : op_wrapper->GetParams()) {
// unused?
// auto* p_tensor_param = dynamic_cast<TensorParamWrapper*>(param.get());
if (param->PopulateQnnParam() != Error::Ok) {
QNN_EXECUTORCH_LOG_WARN(
"Qnn Backend op validation failed "
"with PopulateQnnParam: %d",
QNN_GET_ERROR_CODE(error));
return false;
}
}
error = backend_params_ptr_->qnn_backend_ptr_->BackendValidateOpConfig(
op_wrapper->GetOpConfig());
if (error != QNN_SUCCESS) {
QNN_EXECUTORCH_LOG_WARN(
"Qnn Backend op validation failed with error: %d",
QNN_GET_ERROR_CODE(error));
return false;
}
}
return true;
}
Error QnnManager::Compile(
std::vector<std::shared_ptr<OpWrapper>>& op_wrappers,
QnnExecuTorchContextBinary& qnn_executorch_context_binary) {
Qnn_ErrorHandle_t error = QNN_SUCCESS;
for (std::shared_ptr<OpWrapper>& op_wrapper : op_wrappers) {
for (const auto& tensor_wrapper : op_wrapper->GetInputTensors()) {
ET_CHECK_OR_RETURN_ERROR(
backend_params_ptr_->qnn_graph_ptr_->EnsureTensorInQnnGraph(
tensor_wrapper) == Error::Ok,
Internal,
"Tensor name %s isn't added to Qnn Graph",
tensor_wrapper->GetName().c_str());
}
for (const auto& tensor_wrapper : op_wrapper->GetOutputTensors()) {
ET_CHECK_OR_RETURN_ERROR(
backend_params_ptr_->qnn_graph_ptr_->EnsureTensorInQnnGraph(
tensor_wrapper) == Error::Ok,
Internal,
"Tensor name %s isn't added to Qnn Graph",
tensor_wrapper->GetName().c_str());
}
for (const auto& param : op_wrapper->GetParams()) {
auto* p_tensor_param = dynamic_cast<TensorParamWrapper*>(param.get());
if (p_tensor_param != nullptr) {
ET_CHECK_OR_RETURN_ERROR(
backend_params_ptr_->qnn_graph_ptr_->EnsureTensorInQnnGraph(
p_tensor_param->GetTensorWrapper()) == Error::Ok,
Internal,
"Param tensor name %s isn't added to Qnn Graph",
p_tensor_param->GetName().c_str());
}
ET_CHECK_OR_RETURN_ERROR(
param->PopulateQnnParam() == Error::Ok,
Internal,
"Fail to configure Qnn backend");
}
error = backend_params_ptr_->qnn_graph_ptr_->GraphAddNode(
op_wrapper->GetOpConfig());
if (error != QNN_SUCCESS) {
QNN_EXECUTORCH_LOG_ERROR(
"Failed to add node to Qnn Graph with error: %d",
QNN_GET_ERROR_CODE(error));
return Error::Internal;
}
}
error = backend_params_ptr_->qnn_graph_ptr_->GraphFinalize();
if (error != QNN_SUCCESS) {
QNN_EXECUTORCH_LOG_ERROR(
"Failed to finalize Qnn Graph with error: %d",
QNN_GET_ERROR_CODE(error));
return Error::Internal;
}
// no need to generate extra context binary in online prepare scenario
if (!IsOnlinePrepare()) {
ET_CHECK_OR_RETURN_ERROR(
backend_params_ptr_->qnn_context_ptr_->GetContextBinary(
qnn_executorch_context_binary) == Error::Ok,
Internal,
"Fail to get context binary.");
}
return Error::Ok;
};
} // namespace qnn
} // namespace executor
} // namespace torch
#define EXPORT __attribute__((visibility("default")))
EXPORT void* QnnExecuTorchAllocCustomMem(size_t bytes, size_t alignment) {
using torch::executor::qnn::SharedBuffer;
void* buffer_ptr =
SharedBuffer::GetSharedBufferManager().AllocMem(bytes, alignment);
return buffer_ptr;
}
EXPORT void QnnExecuTorchFreeCustomMem(void* buffer_ptr) {
using torch::executor::qnn::SharedBuffer;
SharedBuffer::GetSharedBufferManager().FreeMem(buffer_ptr);
}