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
| """ 模型量化实现 支持 PyTorch -> ONNX -> TensorRT 量化 """
import torch import torch.nn as nn import numpy as np from typing import Dict, Tuple
class DMSModel(nn.Module): """DMS 模型示例""" def __init__(self): 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.detection_head = nn.Sequential( nn.Flatten(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 4) ) def forward(self, x): features = self.backbone(x) output = self.detection_head(features) return output
def quantize_dynamic(model: nn.Module) -> nn.Module: """ 动态量化 优点:无需校准数据 缺点:精度损失较大 """ quantized = torch.quantization.quantize_dynamic( model, {nn.Linear, nn.Conv2d}, dtype=torch.qint8 ) return quantized
def quantize_static(model: nn.Module, calibration_loader, num_batches: int = 100) -> nn.Module: """ 静态量化 优点:精度损失小 缺点:需要校准数据 """ model.qconfig = torch.quantization.get_default_qconfig('fbgemm') model_fused = torch.quantization.fuse_modules( model, [['backbone.0', 'backbone.1', 'backbone.2'], ['backbone.4', 'backbone.5', 'backbone.6'], ['backbone.8', 'backbone.9', 'backbone.10']] ) model_prepared = torch.quantization.prepare(model_fused) with torch.no_grad(): for i, (images, _) in enumerate(calibration_loader): if i >= num_batches: break model_prepared(images) model_quantized = torch.quantization.convert(model_prepared) return model_quantized
def export_to_onnx(model: nn.Module, output_path: str, input_shape: Tuple = (1, 3, 224, 224)): """导出为 ONNX 格式""" dummy_input = torch.randn(*input_shape) torch.onnx.export( model, dummy_input, output_path, opset_version=13, input_names=['input'], output_names=['output'], dynamic_axes={ 'input': {0: 'batch_size'}, 'output': {0: 'batch_size'} } )
def tensorrt_quantize(onnx_path: str, engine_path: str, precision: str = 'int8'): """ TensorRT 量化 需要安装 TensorRT 和 pycuda """ 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(onnx_path, 'rb') as f: parser.parse(f.read()) config = builder.create_builder_config() 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(engine_path, 'wb') as f: f.write(engine.serialize())
if __name__ == "__main__": model = DMSModel() model.eval() quantized_dynamic = quantize_dynamic(model) calibration_loader = [(torch.randn(1, 3, 224, 224), None) for _ in range(10)] quantized_static = quantize_static(model, calibration_loader) test_input = torch.randn(1, 3, 224, 224) with torch.no_grad(): output_fp32 = model(test_input) output_int8 = quantized_static(test_input) print(f"FP32 输出: {output_fp32}") print(f"INT8 输出: {output_int8}") print(f"差异: {torch.abs(output_fp32 - output_int8.float()).mean()}")
|