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
| #include "qnn_inference_calculator.h" #include "mediapipe/framework/formats/image_frame_opencv.h" #include "mediapipe/framework/port/opencv_imgproc.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/framework/port/status.h"
#include <dlfcn.h>
namespace mediapipe {
absl::Status QNNInferenceCalculator::GetContract(CalculatorContract* cc) { cc->Inputs().Tag("IMAGE").Set<ImageFrame>(); cc->InputSidePackets().Tag("MODEL_PATH").Set<std::string>(); cc->Outputs().Tag("DETECTIONS").Set<std::vector<Detection>>(); cc->Options<QNNInferenceOptions>(); return absl::OkStatus(); }
absl::Status QNNInferenceCalculator::Open(CalculatorContext* cc) { const auto& options = cc->Options<QNNInferenceOptions>(); backend_type_ = options.backend(); input_width_ = options.input_width(); input_height_ = options.input_height(); input_channels_ = options.input_channels(); input_tensor_name_ = options.input_tensor_name(); output_tensor_name_ = options.output_tensor_name(); score_threshold_ = options.score_threshold(); nms_threshold_ = options.nms_threshold(); max_detections_ = options.max_detections(); std::string model_path = cc->InputSidePackets().Tag("MODEL_PATH").Get<std::string>(); MP_RETURN_IF_ERROR(InitializeBackend(model_path)); MP_RETURN_IF_ERROR(LoadModel(model_path)); MP_RETURN_IF_ERROR(CreateGraph()); MP_RETURN_IF_ERROR(CreateTensors()); initialized_ = true; LOG(INFO) << "QNNInferenceCalculator initialized: " << "backend=" << Backend_Name(backend_type_) << ", input_size=" << input_width_ << "x" << input_height_; return absl::OkStatus(); }
absl::Status QNNInferenceCalculator::InitializeBackend( const std::string& model_path) { std::string backend_lib = GetBackendLibraryPath(backend_type_); backend_handle_ = dlopen(backend_lib.c_str(), RTLD_NOW); RET_CHECK(backend_handle_ != nullptr) << "Failed to load QNN backend: " << backend_lib << ", error: " << dlerror(); typedef Qnn_ErrorCode_t (*QnnBackendInitFunc)(const QnnBackend_Config_t*); auto backend_init = (QnnBackendInitFunc)dlsym(backend_handle_, "QnnBackend_initialize"); RET_CHECK(backend_init != nullptr) << "QnnBackend_initialize not found"; Qnn_ErrorCode_t err = backend_init(nullptr); RET_CHECK(err == QNN_SUCCESS) << "Failed to initialize backend: " << err; typedef Qnn_ErrorCode_t (*QnnBackendGetIdFunc)(QnnBackend_Id_t*); auto get_id = (QnnBackendGetIdFunc)dlsym(backend_handle_, "QnnBackend_getId"); QnnBackend_Id_t backend_id = 0; err = get_id(&backend_id); RET_CHECK(err == QNN_SUCCESS) << "Failed to get backend ID: " << err; LOG(INFO) << "QNN backend initialized: " << backend_lib; return absl::OkStatus(); }
absl::Status QNNInferenceCalculator::LoadModel(const std::string& model_path) { model_handle_ = dlopen(model_path.c_str(), RTLD_NOW); RET_CHECK(model_handle_ != nullptr) << "Failed to load model: " << model_path << ", error: " << dlerror(); typedef Qnn_ErrorCode_t (*ModelComposeFunc)( Qnn_BackendHandle_t, Qnn_ContextHandle_t, Qnn_GraphHandle_t*); auto model_compose = (ModelComposeFunc)dlsym(model_handle_, "QnnModel_composeGraphs"); RET_CHECK(model_compose != nullptr) << "QnnModel_composeGraphs not found"; Qnn_ErrorCode_t err = QnnContext_create(backend_, &context_); RET_CHECK(err == QNN_SUCCESS) << "Failed to create context: " << err; err = model_compose(backend_, context_, &graph_); RET_CHECK(err == QNN_SUCCESS) << "Failed to compose graph: " << err; LOG(INFO) << "QNN model loaded: " << model_path; return absl::OkStatus(); }
absl::Status QNNInferenceCalculator::CreateGraph() { QnnGraph_Config_t graph_config; memset(&graph_config, 0, sizeof(graph_config)); graph_config.option = QNN_GRAPH_CONFIG_OPTION_NAME; graph_config.name = "dms_graph"; Qnn_ErrorCode_t err = QnnGraph_create( context_, &graph_config, &graph_); RET_CHECK(err == QNN_SUCCESS) << "Failed to create graph: " << err; err = QnnGraph_finalize(graph_); RET_CHECK(err == QNN_SUCCESS) << "Failed to finalize graph: " << err; return absl::OkStatus(); }
absl::Status QNNInferenceCalculator::CreateTensors() { Qnn_Tensor_t input_tensor; memset(&input_tensor, 0, sizeof(input_tensor)); input_tensor.version = QNN_TENSOR_VERSION_1; input_tensor.v1.id = 0; strncpy(input_tensor.v1.name, input_tensor_name_.c_str(), QNN_MAX_NAME_LEN - 1); input_tensor.v1.type = QNN_TENSOR_TYPE_APP_WRITE; input_tensor.v1.dataType = QNN_DATATYPE_UFIXED_POINT_8; input_tensor.v1.shape.rank = 4; input_tensor.v1.shape.dimensions[0] = 1; input_tensor.v1.shape.dimensions[1] = input_height_; input_tensor.v1.shape.dimensions[2] = input_width_; input_tensor.v1.shape.dimensions[3] = input_channels_; input_tensor.v1.memType = QNN_TENSORMEMTYPE_RAW; size_t input_size = 1 * input_height_ * input_width_ * input_channels_; input_tensor.v1.mem.raw.memSize = input_size; input_tensor.v1.mem.raw.data = malloc(input_size); RET_CHECK(input_tensor.v1.mem.raw.data != nullptr) << "Failed to allocate input buffer"; input_tensors_.push_back(input_tensor); Qnn_Tensor_t output_tensor; memset(&output_tensor, 0, sizeof(output_tensor)); output_tensor.version = QNN_TENSOR_VERSION_1; output_tensor.v1.id = 1; strncpy(output_tensor.v1.name, output_tensor_name_.c_str(), QNN_MAX_NAME_LEN - 1); output_tensor.v1.type = QNN_TENSOR_TYPE_APP_READ; output_tensor.v1.dataType = QNN_DATATYPE_FLOAT_32; output_tensor.v1.shape.rank = 2; output_tensor.v1.shape.dimensions[0] = 100; output_tensor.v1.shape.dimensions[1] = 6; output_tensor.v1.memType = QNN_TENSORMEMTYPE_RAW; size_t output_size = 100 * 6 * sizeof(float); output_tensor.v1.mem.raw.memSize = output_size; output_tensor.v1.mem.raw.data = malloc(output_size); RET_CHECK(output_tensor.v1.mem.raw.data != nullptr) << "Failed to allocate output buffer"; output_tensors_.push_back(output_tensor); return absl::OkStatus(); }
absl::Status QNNInferenceCalculator::Process(CalculatorContext* cc) { if (!initialized_) { return absl::InternalError("Calculator not initialized"); } if (cc->Inputs().Tag("IMAGE").IsEmpty()) { return absl::OkStatus(); } const ImageFrame& image = cc->Inputs().Tag("IMAGE").Get<ImageFrame>(); std::vector<uint8_t> input_data = Preprocess(image); std::memcpy(input_tensors_[0].v1.mem.raw.data, input_data.data(), input_data.size()); Qnn_ErrorCode_t err = QnnGraph_execute( graph_, input_tensors_.data(), input_tensors_.size(), output_tensors_.data(), output_tensors_.size(), nullptr, nullptr); if (err != QNN_SUCCESS) { LOG(WARNING) << "QNN execution failed: " << err; return absl::OkStatus(); } std::vector<Detection> detections = Postprocess(output_tensors_); cc->Outputs().Tag("DETECTIONS").AddPacket( MakePacket<std::vector<Detection>>(detections).At(cc->InputTimestamp())); process_count_++; return absl::OkStatus(); }
absl::Status QNNInferenceCalculator::Close(CalculatorContext* cc) { FreeTensorBuffers(); if (graph_) { QnnGraph_free(graph_); graph_ = nullptr; } if (context_) { QnnContext_free(context_); context_ = nullptr; } if (model_handle_) { dlclose(model_handle_); model_handle_ = nullptr; } if (backend_handle_) { dlclose(backend_handle_); backend_handle_ = nullptr; } LOG(INFO) << "QNNInferenceCalculator closed, processed " << process_count_ << " frames"; return absl::OkStatus(); }
void QNNInferenceCalculator::FreeTensorBuffers() { for (auto& tensor : input_tensors_) { if (tensor.v1.mem.raw.data) { free(tensor.v1.mem.raw.data); tensor.v1.mem.raw.data = nullptr; } } for (auto& tensor : output_tensors_) { if (tensor.v1.mem.raw.data) { free(tensor.v1.mem.raw.data); tensor.v1.mem.raw.data = nullptr; } } }
std::string QNNInferenceCalculator::GetBackendLibraryPath( QNNInferenceOptions::Backend backend) { switch (backend) { case QNNInferenceOptions::CPU: return "/vendor/lib/libQnnCpu.so"; case QNNInferenceOptions::DSP: return "/vendor/lib/libQnnDsp.so"; case QNNInferenceOptions::HTP: return "/vendor/lib/libQnnHtp.so"; default: return "/vendor/lib/libQnnHtp.so"; } }
std::vector<uint8_t> QNNInferenceCalculator::Preprocess(const ImageFrame& image) { cv::Mat mat = formats::MatView(&image); cv::Mat resized; cv::resize(mat, resized, cv::Size(input_width_, input_height_)); std::vector<uint8_t> data(resized.total() * resized.elemSize()); std::memcpy(data.data(), resized.data, data.size()); return data; }
std::vector<Detection> QNNInferenceCalculator::Postprocess( const std::vector<Qnn_Tensor_t>& outputs) { std::vector<Detection> detections; if (outputs.empty()) return detections; const float* data = (const float*)outputs[0].v1.mem.raw.data; int num = outputs[0].v1.shape.dimensions[0]; for (int i = 0; i < num; ++i) { const float* det = data + i * 6; float score = det[4]; if (score < score_threshold_) continue; Detection d; d.set_xmin(det[0]); d.set_ymin(det[1]); d.set_xmax(det[2]); d.set_ymax(det[3]); d.set_score(score); d.set_label_id(static_cast<int>(det[5])); detections.push_back(d); } return detections; }
REGISTER_CALCULATOR(QNNInferenceCalculator);
}
|