量化处理可以加快推理速度,减少模型占用空间 ,提高推理性能的必要选择。
量化时需要对算子进行量化处理,对输入数据fp32格式进行量化处理到int8, 再输入模型中。
最后测试了两种模型相对于torch原始模型的误差均值。
注意安装 onnx/onnxruntime
pip install onnx
pip install onnxruntime
import torch
import torch.quantization
class M(torch.nn.Module):
def __init__(self):
super(M, self).__init__()
self.quant = torch.quantization.QuantStub() # 静态量化时量化桩用于量化数据
self.conv = torch.nn.Conv2d(1, 1, 1)
self.relu = torch.nn.ReLU()
self.dequant = torch.quantization.DeQuantStub() #取消量化桩
def forward(self, x):
x = self.quant(x) #量化数据,从fp32->uint8
x = self.conv(x) #量化后conv
x = self.relu(x) #量化后relu
x = self.dequant(x) #恢复量化变量为fp32
return x
# create a model instance
model_fp32 = M() #创建模型
model_fp32.eval() #推理模式
model_fp32.qconfig = torch.quantization.get_default_qconfig('fbgemm') #设置量化配置
model_fp32_fused = torch.quantization.fuse_modules(model_fp32, [['co

文章展示了如何使用PyTorch进行模型量化,以减少模型大小、提高推理速度。通过创建一个简单的模型,应用静态量化、融合算子、准备和转换模型到int8格式,并导出为ONNX模型。之后,通过ORT(InferenceSession)运行ONNX模型,计算与原始fp32模型的输出差异,以验证量化后的精度损失。
最低0.47元/天 解锁文章
3550

被折叠的 条评论
为什么被折叠?



