onnx,onnxruntime量化,避坑!!!

import onnx
import onnxruntime
import cv2
model_file = "./a_.onnx"
#加载模型
model = onnx.load(model_file)
# 创建一个量化转换器
converter = onnxruntime.quantization.QuantizationConverter(model, quant_format=onnxruntime.quantization.QuantFormat.QLINEAR)
# 进行静态量化
quantized_model = converter.convert()
# 保存量化后的模型
onnx.save(quantized_model, 'quantized_model.onnx')

这个代码 一直在报错,no module named quantization。。。 找了很多种方法,没有一个说到点子上的。

一度认为是conda出了错误,由于是在服务器上,看代码debug不是很方便,一直以为是安装版本的问题,后面发现 quantization这个函数,包括其下面的函数,都不能这么调用。(之前的人都是这么用的?)

找到源代码进行修改:


import onnx
import onnxruntime
from onnxruntime.quantization import quantize_static
from onnxruntime.quantization.quant_utils import QuantType, QuantFormat
import cv2
model_file = "./a_an.onnx"
#加载模型
model = onnx.load(model_file)
# 创建一个量化转换器
onnxruntime.quantization.quantize_dynamic(model_file, "./out_qu.onnx")
# 进行静态量化
#quantized_model = converter.convert()
# 保存量化后的模型
#onnx.save(quantized_model, 'quantized_model.onnx')

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要将一个.onnx模型量化并在onnxruntime中运行,你可以按照以下步骤进行操作: 1. 导入所需的库:import onnx, onnxruntime as ort 2. 加载.onnx模型:model = onnx.load('模型文件名.onnx') 3. 使用onnxruntime检查模型的有效性:onnx.checker.check_model(model) 4. 创建一个inference session:session = ort.InferenceSession('模型文件名.onnx') 5. 准备输入数据:x = np.random.randn(1, 3, 32, 32).astype(np.float32) # 注意输入类型必须为np.float32 6. 运行模型并获取输出:outputs = session.run(None, input = {'input': x}) 如果在导出.onnx属性时遇到&ldquo;RuntimeError: Failed to export an ONNX attribute, since it's not constant, please try to make things (e.g., kernel size) static if possible&rdquo;错误,这可能是因为某些属性不是常量。您可以尝试将这些属性设置为静态值,例如将内核大小设置为固定值。 请注意,在量化.onnx模型时,您需要确保模型的所有属性都是常量,并且输入数据的类型正确。<span class=&quot;em&quot;>1</span><span class=&quot;em&quot;>2</span><span class=&quot;em&quot;>3</span> #### 引用[.reference_title] - *1* *2* *3* [pytorch模型(.pt)转onnx模型(.onnx)的方法详解(1)](https://blog.csdn.net/Vertira/article/details/127601368)[target=&quot;_blank&quot; data-report-click={&quot;spm&quot;:&quot;1018.2226.3001.9630&quot;,&quot;extra&quot;:{&quot;utm_source&quot;:&quot;vip_chatgpt_common_search_pc_result&quot;,&quot;utm_medium&quot;:&quot;distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1&quot;}}] [.reference_item style=&quot;max-width: 100%&quot;] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SetMaker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值