pytorch 转换onnx_Pytorch转onnx、torchscript方式

前言Log免费资源网

本文将介绍如何使用ONNX将PyTorch中训练好的模型(.pt、.pth)型转换为ONNX格式,然后将其加载到Caffe2中。需要安装好onnx和Caffe2。Log免费资源网

PyTorch及ONNX环境准备Log免费资源网

为了正常运行ONNX,我们需要安装最新的Pytorch,你可以选择源码安装:Log免费资源网

git clone --recursive https://github.com/pytorch/pytorch

cd pytorch

mkdir build && cd build

sudo cmake .. -DPYTHON_INCLUDE_DIR=/usr/include/python3.6 -DUSE_MPI=OFF

make install

export PYTHONPATH=$PYTHONPATH:/opt/pytorch/build

其中 "/opt/pytorch/build"是前面build pytorch的目。Log免费资源网

or conda安装Log免费资源网

conda install pytorch torchvision -c pytorchLog免费资源网

安装ONNX的库Log免费资源网

conda install -c conda-forge onnxLog免费资源网

onnx-caffe2 安装Log免费资源网

pip3 install onnx-caffe2Log免费资源网

Pytorch模型转onnxLog免费资源网

在PyTorch中导出模型通过跟踪工作。要导出模型,请调用torch.onnx.export()函数。这将执行模型,记录运算符用于计算输出的轨迹。因为_export运行模型,我们需要提供输入张量x。Log免费资源网

这个张量的值并不重要; 它可以是图像或随机张量,只要它是正确的大小。更多详细信息,请查看torch.onnx documentation文档。Log免费资源网

# 输入模型

example = torch.randn(batch_size, 1, 224, 224, requires_grad=True)

# 导出模型

torch_out = torch_out = torch.onnx.export(model, # model being run

example, # model input (or a tuple for multiple inputs)

"peleeNet.onnx",

verbose=False, # store the trained parameter weights inside the model file

training=False,

do_constant_folding=True,

input_names=['input'],

output_names=['output'])

其中torch_out是执行模型后的输出,通常以忽略此输出。转换得到onnx后可以使用OpenCV的 cv::dnn::readNetFromONNX or cv::dnn::readNet进行模型加载推理了。Log免费资源网

还可以进一步将onnx模型转换为ncnn进而部署到移动端。这就需要ncnn的onnx2ncnn工具了.Log免费资源网

编译ncnn源码,生成 onnx2ncnn。Log免费资源网

其中onnx转换模型时有一些冗余,可以使用用工具简化一些onnx模型。Log免费资源网

pip3 install onnx-simplifierLog免费资源网

简化onnx模型Log免费资源网

python3 -m onnxsim pnet.onnx pnet-sim.onnxLog免费资源网

转换成ncnnLog免费资源网

onnx2ncnn pnet-sim.onnx pnet.param pnet.binLog免费资源网

ncnn 加载模型做推理Log免费资源网

Pytorch模型转torch scriptLog免费资源网

pytorch 加入libtorch前端处理,集体步骤为:Log免费资源网

Log免费资源网

以mtcnn pnet为例Log免费资源网

# convert pytorch model to torch script

# An example input you would normally provide to your model's forward() method.

example = torch.rand(1, 3, 12, 12).to(device)

# Use torch.jit.trace to generate a torch.jit.ScriptModule via tracing.

traced_script_module = torch.jit.trace(pnet, example)

# Save traced model

traced_script_module.save("pnet_model_final.pth")

C++调用如下所示:Log免费资源网

#include // One-stop header.

#include

#include

int main(int argc, const char* argv[])

{

if (argc != 2)

{

std::cerr << "usage: example-app \n";

return -1;

}

// Deserialize the ScriptModule from a file using torch::jit::load().

std::shared_ptr<:jit::script::module> module = torch::jit::load(argv[1]);

assert(module != nullptr);

std::cout << "ok\n";

}

你可能感兴趣的:(pytorch,转换onnx)