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
| """ DMS模型转换到QNN/SNPE格式
步骤: 1. PyTorch -> ONNX 2. ONNX -> DLC (SNPE) 3. ONNX -> QNN Context Binary """
import torch import torch.onnx import subprocess from typing import Dict, List import numpy as np
class QCS8255ModelConverter: """QCS8255模型转换器""" def __init__( self, model: torch.nn.Module, input_shape: tuple = (1, 3, 224, 224), output_dir: str = "./converted_models" ): self.model = model self.input_shape = input_shape self.output_dir = output_dir import os os.makedirs(output_dir, exist_ok=True) def export_onnx( self, filename: str = "dms_model.onnx", opset: int = 13 ) -> str: """ 导出ONNX模型 Args: filename: 输出文件名 opset: ONNX opset版本 Returns: onnx_path: ONNX文件路径 """ self.model.eval() dummy_input = torch.randn(*self.input_shape) onnx_path = f"{self.output_dir}/{filename}" torch.onnx.export( self.model, dummy_input, onnx_path, opset_version=opset, input_names=['input'], output_names=['output'], dynamic_axes={ 'input': {0: 'batch_size'}, 'output': {0: 'batch_size'} } ) print(f"ONNX模型导出完成: {onnx_path}") return onnx_path def convert_to_dlc( self, onnx_path: str, input_list: str = None ) -> str: """ 转换为SNPE DLC格式 Args: onnx_path: ONNX模型路径 input_list: 量化输入数据列表 Returns: dlc_path: DLC文件路径 """ dlc_path = onnx_path.replace(".onnx", ".dlc") cmd = [ "snpe-pytorch-to-dlc", "--input_network", onnx_path, "--output_path", dlc_path, "--input_dim", f"input,{','.join(map(str, self.input_shape))}" ] subprocess.run(cmd, check=True) print(f"DLC转换完成: {dlc_path}") return dlc_path def quantize_dlc( self, dlc_path: str, calibration_data_dir: str ) -> str: """ 量化DLC模型到INT8 Args: dlc_path: FP32 DLC路径 calibration_data_dir: 校准数据目录 Returns: quantized_dlc: 量化后DLC路径 """ quantized_dlc = dlc_path.replace(".dlc", "_quantized.dlc") cmd = [ "snpe-dlc-quantize", "--input_dlc", dlc_path, "--input_list", f"{calibration_data_dir}/input_list.txt", "--output_dlc", quantized_dlc ] subprocess.run(cmd, check=True) print(f"INT8量化完成: {quantized_dlc}") return quantized_dlc def convert_to_qnn( self, onnx_path: str, target_chip: str = "SM8250" ) -> str: """ 转换为QNN Context Binary Args: onnx_path: ONNX模型路径 target_chip: 目标芯片 Returns: qnn_path: QNN文件路径 """ qnn_path = onnx_path.replace(".onnx", ".bin") cmd = [ "qnn-onnx-converter", "--input_model", onnx_path, "--output_path", qnn_path, "--target_chip", target_chip ] subprocess.run(cmd, check=True) print(f"QNN转换完成: {qnn_path}") return qnn_path
class SimpleDMSModel(nn.Module): """示例DMS模型""" def __init__(self, num_classes: int = 5): super().__init__() self.backbone = nn.Sequential( nn.Conv2d(3, 32, 3, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.AdaptiveAvgPool2d(1) ) self.head = nn.Linear(128, num_classes) def forward(self, x): x = self.backbone(x) x = x.view(x.size(0), -1) x = self.head(x) return x
if __name__ == "__main__": model = SimpleDMSModel(num_classes=5) converter = QCS8255ModelConverter( model=model, input_shape=(1, 3, 224, 224) ) onnx_path = converter.export_onnx() print(f"\n模型转换完成!") print(f"ONNX模型: {onnx_path}")
|