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
| """ DMS 模型 INT8 量化
支持框架: 1. PyTorch -> ONNX -> TensorRT 2. PyTorch -> TFLite 3. ONNX Runtime INT8 """
import torch import torch.nn as nn import onnx import onnxruntime as ort import numpy as np
class DMSModel(nn.Module): """简化 DMS 模型""" def __init__(self): super().__init__() self.face_encoder = nn.Sequential( nn.Conv2d(3, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(64, 128, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1) ) self.keypoint_head = nn.Linear(128, 68 * 2) self.fatigue_head = nn.Linear(128, 2) self.gaze_head = nn.Linear(128, 2) def forward(self, x): feat = self.face_encoder(x) feat = feat.view(feat.size(0), -1) keypoints = self.keypoint_head(feat) fatigue = self.fatigue_head(feat) gaze = self.gaze_head(feat) return { "keypoints": keypoints, "fatigue": fatigue, "gaze": gaze }
def export_to_onnx(model, output_path, input_shape=(1, 3, 224, 224)): """导出 ONNX""" model.eval() dummy_input = torch.randn(*input_shape) torch.onnx.export( model, dummy_input, output_path, input_names=["input"], output_names=["keypoints", "fatigue", "gaze"], dynamic_axes={ "input": {0: "batch"}, "keypoints": {0: "batch"}, "fatigue": {0: "batch"}, "gaze": {0: "batch"} }, opset_version=11 ) print(f"ONNX 模型已导出: {output_path}") return output_path
def quantize_onnx_ptq(onnx_path, calibration_data, output_path): """ ONNX PTQ 量化 Args: onnx_path: FP32 ONNX 模型路径 calibration_data: 校准数据 output_path: 输出路径 """ from onnxruntime.quantization import quantize_dynamic, quantize_static, QuantFormat, QuantType from onnxruntime.quantization.shape_inference import quant_pre_process preprocessed_path = onnx_path.replace(".onnx", "_preprocessed.onnx") quant_pre_process(onnx_path, preprocessed_path) quantize_static( preprocessed_path, output_path, calibration_data_reader=calibration_data, quant_format=QuantFormat.QDQ, per_channel=False, weight_type=QuantType.QInt8 ) print(f"INT8 模型已保存: {output_path}") return output_path
def benchmark_model(model_path, input_shape=(1, 3, 224, 224), num_runs=100): """性能基准测试""" import time session = ort.InferenceSession(model_path) input_name = session.get_inputs()[0].name input_data = np.random.randn(*input_shape).astype(np.float32) for _ in range(10): session.run(None, {input_name: input_data}) start = time.time() for _ in range(num_runs): session.run(None, {input_name: input_data}) elapsed = time.time() - start avg_time = elapsed / num_runs * 1000 fps = 1000 / avg_time model_size = onnx.load(model_path).ByteSize() / 1024 / 1024 return { "avg_inference_time_ms": avg_time, "fps": fps, "model_size_mb": model_size }
if __name__ == "__main__": model = DMSModel() onnx_path = "dms_model.onnx" export_to_onnx(model, onnx_path) int8_path = "dms_model_int8.onnx" fp32_perf = benchmark_model(onnx_path) print(f"FP32 性能: {fp32_perf}")
|