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
| import torch import torch.nn as nn import onnx from onnxruntime.quantization import quantize_dynamic, quantize_static, QuantType from onnxruntime.quantization.shape_inference import quant_pre_process
class DMSModelQuantizer: """DMS 模型量化器""" def __init__(self, pytorch_model_path: str, output_dir: str): self.pytorch_model_path = pytorch_model_path self.output_dir = output_dir def export_to_onnx(self, model: nn.Module, input_shape: tuple = (1, 3, 224, 224), opset_version: int = 14): """导出 ONNX 模型 Args: model: PyTorch 模型 input_shape: 输入形状 opset_version: ONNX opset 版本 """ model.eval() dummy_input = torch.randn(*input_shape) onnx_path = f"{self.output_dir}/dms_model.onnx" torch.onnx.export( model, dummy_input, onnx_path, opset_version=opset_version, input_names=['input'], output_names=['output'], dynamic_axes={ 'input': {0: 'batch_size'}, 'output': {0: 'batch_size'} } ) print(f"ONNX model exported to: {onnx_path}") return onnx_path def dynamic_quantization(self, onnx_path: str): """动态量化 优点:无需校准数据 缺点:仅支持部分算子 """ quantized_path = onnx_path.replace('.onnx', '_dynamic_int8.onnx') quantize_dynamic( model_input=onnx_path, model_output=quantized_path, weight_type=QuantType.QInt8, per_channel=True, reduce_range=True ) print(f"Dynamic quantized model: {quantized_path}") return quantized_path def static_quantization(self, onnx_path: str, calibration_data: list): """静态量化 优点:精度更高,推理更快 缺点:需要校准数据 """ preprocessed_path = onnx_path.replace('.onnx', '_preprocessed.onnx') quant_pre_process(onnx_path, preprocessed_path, skip_symbolic_shape=True) from onnxruntime.quantization import CalibrationDataReader class DMSDataReader(CalibrationDataReader): def __init__(self, calibration_data): self.data = calibration_data self.index = 0 def get_next(self): if self.index >= len(self.data): return None data = self.data[self.index] self.index += 1 return {'input': data} def rewind(self): self.index = 0 dr = DMSDataReader(calibration_data) quantized_path = onnx_path.replace('.onnx', '_static_int8.onnx') quantize_static( model_input=preprocessed_path, model_output=quantized_path, calibration_data_reader=dr, quant_format=QuantFormat.QDQ, per_channel=True, weight_type=QuantType.QInt8, activation_type=QuantType.QUInt8 ) print(f"Static quantized model: {quantized_path}") return quantized_path
class TensorRTOptimizer: """TensorRT 优化器""" def __init__(self, onnx_path: str, engine_path: str): self.onnx_path = onnx_path self.engine_path = engine_path def build_engine(self, precision: str = 'fp16', max_batch_size: int = 1, max_workspace_size: int = 1 << 30): """构建 TensorRT 引擎 Args: precision: 'fp32' | 'fp16' | 'int8' max_batch_size: 最大批次大小 max_workspace_size: 最大工作空间大小 """ import tensorrt as trt logger = trt.Logger(trt.Logger.WARNING) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) parser = trt.OnnxParser(network, logger) with open(self.onnx_path, 'rb') as f: if not parser.parse(f.read()): for error in range(parser.num_errors): print(parser.get_error(error)) return None config = builder.create_builder_config() config.max_workspace_size = max_workspace_size if precision == 'fp16': config.set_flag(trt.BuilderFlag.FP16) elif precision == 'int8': config.set_flag(trt.BuilderFlag.INT8) engine = builder.build_engine(network, config) with open(self.engine_path, 'wb') as f: f.write(engine.serialize()) print(f"TensorRT engine saved to: {self.engine_path}") return engine def inference(self, input_data: np.ndarray) -> np.ndarray: """TensorRT 推理""" import tensorrt as trt import pycuda.driver as cuda import pycuda.autoinit with open(self.engine_path, 'rb') as f: engine = trt.Runtime(trt.Logger(trt.Logger.WARNING)).deserialize_cuda_engine(f.read()) context = engine.create_execution_context() input_shape = engine.get_binding_shape(0) output_shape = engine.get_binding_shape(1) input_size = trt.volume(input_shape) * np.dtype(np.float32).itemsize output_size = trt.volume(output_shape) * np.dtype(np.float32).itemsize d_input = cuda.mem_alloc(input_size) d_output = cuda.mem_alloc(output_size) h_input = input_data.astype(np.float32) h_output = np.empty(output_shape, dtype=np.float32) cuda.memcpy_htod(d_input, h_input) context.execute_v2([int(d_input), int(d_output)]) cuda.memcpy_dtoh(h_output, d_output) return h_output
class ONNXRuntimeInference: """ONNX Runtime 推理""" def __init__(self, model_path: str, execution_provider: str = 'CUDAExecutionProvider'): """ Args: model_path: ONNX 模型路径 execution_provider: 'CUDAExecutionProvider' | 'CPUExecutionProvider' | 'TensorrtExecutionProvider' """ import onnxruntime as ort self.session = ort.InferenceSession( model_path, providers=[execution_provider] ) self.input_name = self.session.get_inputs()[0].name self.output_names = [o.name for o in self.session.get_outputs()] self.inference_times = [] def inference(self, input_data: np.ndarray) -> dict: """推理 Args: input_data: (B, C, H, W) 输入数据 Returns: { 'outputs': dict, 'latency_ms': float } """ import time start_time = time.time() outputs = self.session.run( self.output_names, {self.input_name: input_data} ) latency_ms = (time.time() - start_time) * 1000 self.inference_times.append(latency_ms) return { 'outputs': dict(zip(self.output_names, outputs)), 'latency_ms': latency_ms } def get_stats(self) -> dict: """获取性能统计""" import numpy as np return { 'avg_latency_ms': np.mean(self.inference_times), 'max_latency_ms': np.max(self.inference_times), 'min_latency_ms': np.min(self.inference_times), 'p95_latency_ms': np.percentile(self.inference_times, 95), 'fps': 1000 / np.mean(self.inference_times) }
|