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
| import torch import torch.nn as nn import torch.quantization as quant from torch.quantization import get_default_qconfig, prepare_qat, convert
class DMSModel(nn.Module): """ DMS模型示例 包含: - 人脸检测 - 眼睛检测 - 疲劳判断 """ def __init__(self): super().__init__() self.backbone = nn.Sequential( nn.Conv2d(3, 32, 3, 2, 1), nn.BatchNorm2d(32), nn.ReLU(), nn.Conv2d(32, 64, 3, 2, 1), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(64, 128, 3, 2, 1), nn.BatchNorm2d(128), nn.ReLU(), ) self.head = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 3) ) def forward(self, x): feat = self.backbone(x) out = self.head(feat) return out
def quantize_model_ptq(model, calibration_loader): """ 训练后量化(PTQ) Args: model: FP32模型 calibration_loader: 校准数据集 Returns: quantized_model: INT8量化模型 """ model.qconfig = get_default_qconfig('fbgemm') model_prepared = quant.prepare(model, inplace=True) print("开始校准...") with torch.no_grad(): for batch in calibration_loader: model_prepared(batch) model_quantized = quant.convert(model_prepared) print("量化完成!") return model_quantized
def quantize_model_qat(model, train_loader, epochs=10): """ 量化感知训练(QAT) 优势:精度损失更小,适合精度敏感场景 Args: model: FP32模型 train_loader: 训练数据集 epochs: 训练轮数 Returns: quantized_model: INT8量化模型 """ model.qconfig = get_default_qconfig('fbgemm') model_prepared = prepare_qat(model, inplace=True) optimizer = torch.optim.SGD(model_prepared.parameters(), lr=0.001) criterion = nn.CrossEntropyLoss() print("开始QAT训练...") for epoch in range(epochs): for batch, labels in train_loader: optimizer.zero_grad() outputs = model_prepared(batch) loss = criterion(outputs, labels) loss.backward() optimizer.step() print(f"Epoch {epoch+1}/{epochs}, Loss: {loss.item():.4f}") model_quantized = convert(model_prepared) print("QAT完成!") return model_quantized
def export_to_onnx(model, output_path, input_shape=(1, 3, 224, 224)): """ 导出为ONNX格式 Args: model: 量化模型 output_path: 输出路径 input_shape: 输入尺寸 """ model.eval() dummy_input = torch.randn(input_shape) torch.onnx.export( model, dummy_input, output_path, export_params=True, opset_version=13, do_constant_folding=True, input_names=['input'], output_names=['output'], dynamic_axes={ 'input': {0: 'batch_size'}, 'output': {0: 'batch_size'} } ) print(f"ONNX模型已导出:{output_path}")
def benchmark_quantization(model_fp32, model_int8, test_loader, device='cpu'): """ 对比FP32和INT8模型性能 Returns: results: 性能对比结果 """ import time results = { 'fp32': {'accuracy': 0, 'latency': 0, 'size_mb': 0}, 'int8': {'accuracy': 0, 'latency': 0, 'size_mb': 0} } model_fp32.eval() model_fp32.to(device) correct = 0 total = 0 latencies = [] with torch.no_grad(): for batch, labels in test_loader: batch = batch.to(device) labels = labels.to(device) start = time.time() outputs = model_fp32(batch) latency = (time.time() - start) * 1000 latencies.append(latency) _, predicted = torch.max(outputs, 1) total += labels.size(0) correct += (predicted == labels).sum().item() results['fp32']['accuracy'] = 100 * correct / total results['fp32']['latency'] = sum(latencies) / len(latencies) results['fp32']['size_mb'] = sum(p.numel() * 4 for p in model_fp32.parameters()) / 1024 / 1024 model_int8.eval() correct = 0 total = 0 latencies = [] with torch.no_grad(): for batch, labels in test_loader: start = time.time() outputs = model_int8(batch) latency = (time.time() - start) * 1000 latencies.append(latency) _, predicted = torch.max(outputs, 1) total += labels.size(0) correct += (predicted == labels).sum().item() results['int8']['accuracy'] = 100 * correct / total results['int8']['latency'] = sum(latencies) / len(latencies) results['int8']['size_mb'] = sum(p.numel() for p in model_int8.parameters()) / 1024 / 1024 print("\n性能对比:") print(f"{'指标':<15} {'FP32':<15} {'INT8':<15} {'提升':<15}") print("-" * 60) print(f"{'准确率 (%)':<15} {results['fp32']['accuracy']:<15.2f} {results['int8']['accuracy']:<15.2f} {results['int8']['accuracy'] - results['fp32']['accuracy']:+.2f}") print(f"{'延迟 (ms)':<15} {results['fp32']['latency']:<15.2f} {results['int8']['latency']:<15.2f} {(1 - results['int8']['latency']/results['fp32']['latency'])*100:+.1f}%") print(f"{'大小 (MB)':<15} {results['fp32']['size_mb']:<15.2f} {results['int8']['size_mb']:<15.2f} {(1 - results['int8']['size_mb']/results['fp32']['size_mb'])*100:+.1f}%") return results
if __name__ == '__main__': model = DMSModel()
|