1. 环境配置
pytorch
onnxruntime==1.2.0 (1.3.0版本会报错ImportError: cannot import name 'get_all_providers')
onnxruntime-gpu==1.2.0
cuda10.1+cudnn7.6
2. 模型准备和转换
用torch.save()存储模型结构和权重
model = torch.load('pix2pix.pth', map_location=torch.device('cuda'))
单卡训练的模型
torch.onnx._export(model, dummy_input, "pix2pix.onnx", verbose=True, opset_version=11)
多卡训练的模型
torch.onnx._export(model, dummy_input, "pix2pix.onnx", verbose=True, opset_version=11)
3. 验证是否有精度损失
import onnxruntime
import numpy as np
from onnxruntime.datasets import get_example
def to_numpy(tensor):
return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
# 得到torch模型的输出
dummy_input = torch.randn(1, 3, 256, 256, device=

本文介绍了如何将PyTorch模型转换为ONNX格式,并进行精度验证。首先,确保安装了合适的环境,包括PyTorch、ONNXRuntime和CUDA。接着,通过torch.save()保存模型结构和权重,然后使用torch.onnx._export()函数进行模型转换。对于单卡和多卡训练的模型,转换方法略有不同。最后,利用ONNXRuntime运行模型并对比ONNX模型和PyTorch模型的输出,确保在小数点后3位上一致,以验证精度无损失。
最低0.47元/天 解锁文章
1万+

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



