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
| class LNNQuantizer: """ LNN 量化部署 量化方案: 1. 动态量化(INT8) 2. 静态量化(INT8) 3. QAT量化感知训练 """ def __init__(self, model: nn.Module): self.model = model def dynamic_quantization(self): """ 动态量化 特点: - 权重量化为INT8 - 激活值保持FP32 - 推理时动态量化 """ quantized_model = torch.quantization.quantize_dynamic( self.model, {nn.Linear, nn.LSTM, nn.GRU}, dtype=torch.qint8 ) return quantized_model def static_quantization(self, calibration_data): """ 静态量化 特点: - 权重和激活值都量化为INT8 - 需要校准数据 - 精度损失较小 """ self.model.qconfig = torch.quantization.get_default_qconfig('fbgemm') self.model = torch.quantization.fuse_modules(self.model, [['conv', 'bn', 'relu']]) torch.quantization.prepare(self.model, inplace=True) with torch.no_grad(): for data in calibration_data: self.model(data) torch.quantization.convert(self.model, inplace=True) return self.model def export_onnx(self, output_path: str): """导出ONNX格式""" dummy_input = torch.randn(1, 3, 224, 224) torch.onnx.export( self.model, dummy_input, output_path, opset_version=14, input_names=['input'], output_names=['output'], dynamic_axes={'input': {0: 'batch_size'}, 'output': {0: 'batch_size'}} ) print(f"ONNX模型导出至: {output_path}")
""" FP32模型大小: 58.2 MB INT8量化后: 15.4 MB 压缩比: 3.78× """
|