首页 > 其他分享 >pytorch 量化相关参考

pytorch 量化相关参考

时间:2023-10-18 16:14:15浏览次数:40  
标签:traced 参考 fp32 onnx torch pytorch input 量化 model

ref:
https://blog.csdn.net/znsoft/article/details/130788437

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, [['conv', 'relu']]) #量化算子并融合
model_fp32_prepared = torch.quantization.prepare(model_fp32_fused) #准备
input_fp32 = torch.randn(4, 1, 4, 4) #产生伪数据用于测试模型
model_fp32_prepared(input_fp32) #数据量化操作,准备范围,刻度等
model_int8 = torch.quantization.convert(model_fp32_prepared) #量化数据
 
 
output_x = model_int8(input_fp32) #量化后推理
traced = torch.jit.trace(model_int8, (input_fp32,))  #用于演示trace方法
traced_script = torch.jit.script(model_int8, (input_fp32,)) #用于验证script方法
 
torch.onnx.export(model_int8,             # model being run
                    input_fp32,                         # model input (or a tuple for multiple inputs)
                    './model_int8.onnx',   # where to save the model (can be a file or file-like object)
                    export_params=True,        # store the trained parameter weights inside the model file
                    opset_version=13,          # the ONNX version to export the model to
                    #do_constant_folding=True,  # whether to execute constant folding for optimization
                    input_names = ['input'],   # the model's input names
                    #output_names = ['output'], # the model's output names
                    #example_outputs=traced(input_fp32)
                    )
 
torch.onnx.export(traced,             # model being run
                    input_fp32,                         # model input (or a tuple for multiple inputs)
                    './model_int8_trace.onnx',   # where to save the model (can be a file or file-like object)
                    export_params=True,        # store the trained parameter weights inside the model file
                    opset_version=13,          # the ONNX version to export the model to
                    do_constant_folding=True,  # whether to execute constant folding for optimization
                    input_names = ['input'],   # the model's input names
                    output_names = ['output'], # the model's output names
                  #  example_outputs=traced(input_fp32)
                    )
 
onnx_pth= './model_int8.onnx'
 
oxx_m = ort.InferenceSession(onnx_pth)
onnx_blob = input_fp32.data.numpy()
onnx_out = oxx_m.run(None, {'input':onnx_blob})[0]
 
print('mean diff of int8 onnx= ', np.mean(onnx_out - torch_out.data.numpy()))
 
onnx_pth='./model_int8_trace.onnx'
oxx_m = ort.InferenceSession(onnx_pth)
onnx_out2 = oxx_m.run(None, {'input':onnx_blob})[0]
 
print('mean diff of traced int8 onnx= ', np.mean(onnx_out2 - torch_out.data.numpy()))
 
 
# for traced
 
traced_out=traced(input_fp32)
 
print('mean diff of traced torch= ', np.mean(traced_out.data.numpy() - torch_out.data.numpy()))
# for script
script_out=traced_script(input_fp32)
 
print('mean diff of script torch= ', np.mean(script_out.data.numpy() - torch_out.data.numpy()))
#保存模型,可以用于pnnx转换ncnn
torch.jit.save(traced,"./jit_trace.pth")
torch.jit.save(traced_script,"jit_script.pth")

标签:traced,参考,fp32,onnx,torch,pytorch,input,量化,model
From: https://www.cnblogs.com/wioponsen/p/17772578.html

相关文章

  • pytorch一些准备工作
    conda常用指令激活以及退出当前虚拟环境condaactivatexxxcondadeactivate创建以及删除condacreate-nxxxpython=3.8condaremove-nxxx查看当前虚拟环境有哪些condainfo--envs查看当前环境中有哪些库condalist安装与更新包condainstallnump......
  • Python3,3分钟,带你了解PyTorch,原来科学计算库也不是很难嘛。
    1、引言小屌丝:鱼哥,最近忙啥嘞?小鱼:啥也没干。小屌丝:确定没干??小鱼:…这话到你嘴里,咋就变为了。小屌丝:也没有啊,我就是确认下,你干没干。小鱼:…能干啥,你想干啥?小屌丝:我想请教你个问题。小鱼:正儿八经的问题,是不?小屌丝:你就看我今天这身穿的,还能不正经?小鱼:穿新鞋走老路小屌丝:此话咋......
  • 《动手学深度学习 Pytorch版》 9.1 门控循环单元(GRU)
    我们可能会遇到这样的情况:早期观测值对预测所有未来观测值具有非常重要的意义。考虑一个极端情况,其中第一个观测值包含一个校验和,目标是在序列的末尾辨别校验和是否正确。在这种情况下,第一个词元的影响至关重要。我们希望有某些机制能够在一个记忆元里存储重要的早期信息。如......
  • pytorch问题集合
    根据kernelsize,stride和padding计算卷积后的尺寸对于PyTorch中的1维卷积层nn.Conv1d,输出序列长度可以根据以下公式计算:假设:-输入序列长度:L_in-卷积核大小:K-步长:S-填充:P则输出序列长度为:pythonL_out=(L_in+2*P-K)//S+1这里://表示地板除(向下......
  • [pytorch] 训练时冻结一部分模型的参数 —— module.requires_grad_(False)
    prologuetitle:[pytorch]训练时冻结一部分模型的参数——module.requires_grad_(False)代码用到一个解码器\(dec\),希望用它预测生成结果\(g\)的countingencode并用以计算损失,以此约束生成器生成合理的结果(能解码出正确的countingencode)但考虑到\(g\)并不准确,如果不冻结\(......
  • 量化初识
    仓位管理及风险控制1、风险控制中的止盈止损1)止盈-目标止盈-指标(信号)止盈2)止损-目标止损-指标(信号)止损3)浮动止盈止损***从建仓开始监测股价,若股价从后续的最高点回落3%,则退出(清盘)2、仓位管理基于风险控制的仓位管理(风险大的,需要少买;风险小的,可以多买)以下是5/5建仓法......
  • 如何满足越来越多的轻量化场景智能视频监控需求?
    一、行业现状随着视频及监控应用技术的发展与安防意识的普及,视频监控行业已经进入高速发展阶段,市场规模不断扩大,应用领域也随之不断拓展。越来越多的用户会有各种不同小场景的监控需求,如餐饮、仓库、独立车间、商场独立空间等需单独监控、单独管理,并且根据自身场景的特点也会需要......
  • pytorch_Tensorboard的使用
     SummaryWriter()将什么写入文件中,如果不指定的话,就写入默认的需要两个方法writer.add_image()wruter.add_scalar() fromtorch.utils.tensorboardimportSummaryWriter#导入tensorboard,再导入SummaryWriter这个类writer=SummaryWriter("logs")#利用OpenC......
  • 量化
    均匀量化已知信号x(t)的振幅均匀分布在-1~+1V范围内,频带限制在10kHz以内,以奈奎斯特速率进行抽样。这些抽样值均匀量化后编为二进制代码,如果量化间隔为1/32V,求:(1)抽样频率(2)均匀量化后进行二进制编码的位数n(3)量化间隔△(4)量化器的平均信号量噪比。(1)抽样频率根据奈......
  • pytorch(9.7) keras-Embedding 嵌入层
    https://www.tensorflow.org/text/guide/word_embeddings将文本表示为数字机器学习模型将向量(数字数组)作为输入。处理文本时,您必须做的第一件事是想出一种策略,将字符串转换为数字(或“矢量化”文本),然后再将其输入模型。1独热编码作为第一个想法,您可能会对词汇表中的每个单词进......