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
| """ PyTorch模型导出ONNX + 量化 """
import torch import torch.nn as nn import onnx from onnxruntime.quantization import quantize_static, quantize_dynamic, QuantFormat, QuantType from onnxruntime.quantization.shape_inference import quant_pre_process from typing import Tuple, Optional import numpy as np
class DMSModel(nn.Module): """ 示例DMS模型 包含:人脸检测 + 眼睛状态 + 头部姿态 """ def __init__( self, backbone: str = 'mobilenetv3', num_classes: int = 10 ): super().__init__() if backbone == 'mobilenetv3': from torchvision.models import mobilenet_v3_small self.backbone = mobilenet_v3_small(pretrained=True) self.backbone.classifier = nn.Identity() feature_dim = 576 else: raise ValueError(f"Unknown backbone: {backbone}") self.face_head = nn.Sequential( nn.Linear(feature_dim, 256), nn.ReLU(inplace=True), nn.Linear(256, 4) ) self.eye_head = nn.Sequential( nn.Linear(feature_dim, 128), nn.ReLU(inplace=True), nn.Linear(128, 2) ) self.pose_head = nn.Sequential( nn.Linear(feature_dim, 128), nn.ReLU(inplace=True), nn.Linear(128, 3) ) def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Args: x: (batch, 3, 224, 224) Returns: face_bbox: (batch, 4) eye_state: (batch, 2) head_pose: (batch, 3) """ features = self.backbone(x) face_bbox = self.face_head(features) eye_state = self.eye_head(features) head_pose = self.pose_head(features) return face_bbox, eye_state, head_pose
def export_to_onnx( model: nn.Module, save_path: str, input_size: Tuple[int, int, int] = (1, 3, 224, 224), opset_version: int = 17 ) -> str: """ 导出ONNX模型 Args: model: PyTorch模型 save_path: 保存路径 input_size: 输入尺寸 opset_version: ONNX opset版本 Returns: onnx_path: ONNX文件路径 """ model.eval() dummy_input = torch.randn(*input_size) onnx_path = save_path.replace('.pt', '.onnx') torch.onnx.export( model, dummy_input, onnx_path, export_params=True, opset_version=opset_version, do_constant_folding=True, input_names=['input'], output_names=['face_bbox', 'eye_state', 'head_pose'], dynamic_axes={ 'input': {0: 'batch_size'}, 'face_bbox': {0: 'batch_size'}, 'eye_state': {0: 'batch_size'}, 'head_pose': {0: 'batch_size'} } ) onnx_model = onnx.load(onnx_path) onnx.checker.check_model(onnx_model) print(f"ONNX模型已导出: {onnx_path}") return onnx_path
def quantize_onnx_static( onnx_path: str, calibration_data: np.ndarray, quant_format: QuantFormat = QuantFormat.QDQ, activation_type: QuantType = QuantType.QUInt8, weight_type: QuantType = QuantType.QInt8 ) -> str: """ 静态量化ONNX模型 Args: onnx_path: ONNX模型路径 calibration_data: 校准数据 quant_format: 量化格式 activation_type: 激活类型 weight_type: 权重类型 Returns: quantized_path: 量化后模型路径 """ from onnxruntime.quantization import CalibrationDataReader class CalibrationData(CalibrationDataReader): def __init__(self, data): self.data = data self.index = 0 def get_next(self): if self.index >= len(self.data): return None item = {'input': self.data[self.index]} self.index += 1 return item def rewind(self): self.index = 0 preprocessed_path = onnx_path.replace('.onnx', '_preprocessed.onnx') quant_pre_process(onnx_path, preprocessed_path) quantized_path = onnx_path.replace('.onnx', '_quantized.onnx') calibration_reader = CalibrationData(calibration_data) quantize_static( model_input=preprocessed_path, model_output=quantized_path, calibration_data_reader=calibration_reader, quant_format=quant_format, per_channel=False, weight_type=weight_type, activation_type=activation_type ) print(f"量化模型已保存: {quantized_path}") return quantized_path
def quantize_onnx_dynamic( onnx_path: str, weight_type: QuantType = QuantType.QInt8 ) -> str: """ 动态量化ONNX模型(简单快速) Args: onnx_path: ONNX模型路径 weight_type: 权重类型 Returns: quantized_path: 量化后模型路径 """ quantized_path = onnx_path.replace('.onnx', '_dynamic_quant.onnx') quantize_dynamic( model_input=onnx_path, model_output=quantized_path, weight_type=weight_type, optimize_model=True ) print(f"动态量化模型已保存: {quantized_path}") return quantized_path
if __name__ == "__main__": model = DMSModel(backbone='mobilenetv3') onnx_path = export_to_onnx( model, "dms_model.onnx", input_size=(1, 3, 224, 224) ) import os original_size = os.path.getsize(onnx_path) / 1024 / 1024 print(f"原始模型大小: {original_size:.2f} MB") quantized_path = quantize_onnx_dynamic(onnx_path) quantized_size = os.path.getsize(quantized_path) / 1024 / 1024 print(f"量化后模型大小: {quantized_size:.2f} MB") print(f"压缩比: {original_size / quantized_size:.2f}x")
|