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
| """ Qualcomm Snapdragon Ride DMS模型部署流程
从训练模型到边缘部署的完整流程 """
import numpy as np import torch import torch.nn as nn
class LightweightDMS(nn.Module): """ 轻量级DMS模型 设计原则: - 参数量 < 5M - 支持INT8量化 - 输入:224x224 RGB图像 - 输出:疲劳分数 + 分心分类 """ def __init__(self): super().__init__() from torchvision.models import mobilenet_v3_small mobilenet = mobilenet_v3_small(pretrained=True) self.backbone = nn.Sequential(*list(mobilenet.features.children())) self.drowsiness_head = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(576, 128), nn.ReLU(), nn.Linear(128, 1), nn.Sigmoid() ) self.distraction_head = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(576, 64), nn.ReLU(), nn.Linear(64, 5) ) self.keypoint_head = nn.Sequential( nn.ConvTranspose2d(576, 256, 4, 2, 1), nn.ReLU(), nn.ConvTranspose2d(256, 64, 4, 2, 1), nn.ReLU(), nn.ConvTranspose2d(64, 17, 4, 2, 1) ) def forward(self, x): features = self.backbone(x) drowsiness = self.drowsiness_head(features) distraction = self.distraction_head(features) keypoints = self.keypoint_head(features) return { 'drowsiness': drowsiness, 'distraction': distraction, 'keypoints': keypoints }
def export_to_onnx(model, output_path: str): """ 导出ONNX模型 Args: model: PyTorch模型 output_path: 输出路径 """ model.eval() dummy_input = torch.randn(1, 3, 224, 224) torch.onnx.export( model, dummy_input, output_path, input_names=['input'], output_names=['drowsiness', 'distraction', 'keypoints'], dynamic_axes={ 'input': {0: 'batch_size'}, 'drowsiness': {0: 'batch_size'}, 'distraction': {0: 'batch_size'} }, opset_version=13 ) print(f"ONNX模型已导出: {output_path}")
def quantize_model(model, calibration_dataloader): """ 量化模型为INT8 Qualcomm NPU对INT8推理有最佳性能 Args: model: PyTorch模型 calibration_dataloader: 校准数据加载器 Returns: quantized_model: 量化后的模型 """ model.eval() model.qconfig = torch.quantization.get_default_qconfig('qnnpack') model_fused = torch.quantization.fuse_modules(model, [['backbone.0', 'backbone.1']]) model_prepared = torch.quantization.prepare(model_fused) with torch.no_grad(): for batch in calibration_dataloader: model_prepared(batch) model_quantized = torch.quantization.convert(model_prepared) return model_quantized
def convert_to_dlc(onnx_path: str, dlc_path: str): """ 将ONNX转换为DLC格式 DLC是Snapdragon的专用模型格式 命令行工具:snpe-onnx-to-dlc Args: onnx_path: ONNX模型路径 dlc_path: DLC输出路径 """ import subprocess cmd = [ 'snpe-onnx-to-dlc', '--input_network', onnx_path, '--output_path', dlc_path ] subprocess.run(cmd, check=True) print(f"DLC模型已生成: {dlc_path}")
class SnapdragonDMSInference: """ Snapdragon平台DMS推理类 使用SNPE/QNN进行推理 """ def __init__(self, dlc_path: str): """ 初始化推理引擎 Args: dlc_path: DLC模型路径 """ import snpe self.model = snpe.Model(dlc_path) self.context = self.model.create_context() self.input_buffer = self.context.create_input_buffer('input') self.output_buffers = { 'drowsiness': self.context.create_output_buffer('drowsiness'), 'distraction': self.context.create_output_buffer('distraction'), 'keypoints': self.context.create_output_buffer('keypoints') } def infer(self, image: np.ndarray) -> dict: """ 执行推理 Args: image: RGB图像 (H, W, 3) Returns: result: 检测结果 """ input_tensor = self._preprocess(image) self.input_buffer.copy_from(input_tensor) self.context.execute() drowsiness = self.output_buffers['drowsiness'].copy_to() distraction = self.output_buffers['distraction'].copy_to() keypoints = self.output_buffers['keypoints'].copy_to() return { 'drowsiness_score': float(drowsiness[0]), 'distraction_class': int(np.argmax(distraction)), 'keypoints': keypoints.reshape(17, 2) } def _preprocess(self, image: np.ndarray) -> np.ndarray: """ 预处理图像 Args: image: RGB图像 Returns: tensor: 预处理后的tensor """ image = cv2.resize(image, (224, 224)) image = image.astype(np.float32) / 255.0 image = (image - [0.485, 0.456, 0.406]) / [0.229, 0.224, 0.225] tensor = image.transpose(2, 0, 1) return tensor
def deploy_dms_to_snapdragon(): """ 完整部署流程 """ print("=" * 50) print("Snapdragon Ride DMS部署流程") print("=" * 50) print("\n[1/6] 训练模型...") model = LightweightDMS() print("\n[2/6] 导出ONNX...") export_to_onnx(model, "dms_model.onnx") print("\n[3/6] 量化模型...") print("\n[4/6] 转换为DLC...") convert_to_dlc("dms_model.onnx", "dms_model.dlc") print("\n[5/6] 部署到设备...") print("\n[6/6] 测试推理...") print("\n部署完成!")
if __name__ == "__main__": deploy_dms_to_snapdragon()
|