Paddle2ONNX最新升级:飞桨模型全面支持ONNX协议啦!
发布日期:2021-02-05 02:07浏览量:1874次
什么是ONNX
什么是Paddle2ONNX
Paddle2ONNX项目升级解读
-
支持基于飞桨框架2.0导出动态图模型
-
更丰富的Paddle OP覆盖
-
支持转换飞桨CV、NLP领域的主流模型
覆盖CV和NLP领域主流模型,不仅支持PP-YOLO这样模型新星的转换,还开始支持ERNIE这样NLP领域的王牌!它们均已支持转为ONNX进行部署,有需求的同学快去试试吧!
Paddle2ONNX使用教程
将动态图模型导出为ONNX模型
import os
import time
import paddle
# 从模型代码中导入模型
from paddle.vision.models import mobilenet_v2
# 实例化模型
model = mobilenet_v2()
# 将模型设置为推理状态
model.eval()
# 定义输入数据
input_spec = paddle.static.InputSpec(shape=[None, 3, 320, 320], dtype='float32', name='image')
# ONNX模型导出
# enable_onnx_checker设置为True,表示使用官方ONNX工具包来check模型的正确性,需要安装ONNX(pip install onnx)
paddle.onnx.export(model, 'mobilenet_v2', input_spec=[input_spec], opset_version=12, enable_onnx_checker=True)
执行结果:
2021-01-26 10:52:13 [INFO] ONNX model genarated is valid.
2021-01-26 10:52:13 [INFO] ONNX model saved in mobilenet_v2.onnx
将静态图模型导出为ONNX模型
# Paddle动态图保存为静态图
paddle.jit.save(model, 'inference/model', input_spec=[input_spec])
# 调用paddle2onnx命令
!paddle2onnx \
--model_dir inference \
--model_filename model.pdmodel\
--params_filename model.pdiparams \
--save_file mobilenet_v2.onnx \
--opset_version 12
执行结果:
2021-01-26 10:53:29 [INFO] ONNX model saved in mobilenet_v2.onnx
模型测试
# 动态图导出的ONNX模型测试
import time
import numpy as np
from onnxruntime import InferenceSession
# 加载ONNX模型
sess = InferenceSession('mobilenet_v2.onnx')
# 准备输入
x = np.random.random((1, 3, 320, 320)).astype('float32')
# 模型预测
start = time.time()
ort_outs = sess.run(output_names=None, input_feed={'image': x})
end = time.time()
print("Exported model has been predicted by ONNXRuntime!")
print('ONNXRuntime predict time: %.04f s' % (end - start))
# 对比ONNX Runtime 和 飞桨的结果
paddle_outs = model(paddle.to_tensor(x))
diff = ort_outs[0] - paddle_outs.numpy()
max_abs_diff = np.fabs(diff).max()
if max_abs_diff < 1e-05:
print("The difference of results between ONNXRuntime and Paddle looks good!")
else:
relative_diff = max_abs_diff / np.fabs(paddle_outs.numpy()).max()
if relative_diff < 1e-05:
print("The difference of results between ONNXRuntime and Paddle looks good!")
else:
print("The difference of results between ONNXRuntime and Paddle looks bad!")
print('relative_diff: ', relative_diff)
print('max_abs_diff: ', max_abs_diff)
执行结果:
Exported model has been predicted by ONNXRuntime!
ONNXRuntime predict time: 0.0260 s
The difference of results between ONNXRuntime and Paddle looks good!
max_abs_diff: 4.2632564e-13
-
PaddleX基于Paddle2ONNX的OpenVINO部署方案:
https://paddlex.readthedocs.io/zh_CN/develop/deploy/openvino/index.html
-
飞桨官网导出ONNX模型协议教程:
-
手把手教你通过ONNX部署飞桨模型教程:
-
Paddle2ONNX项目地址:
体验AI
Web端 前往AI能力体验中心
移动端 打开百度APP“扫一扫”