这篇文章主要介绍了Pytorch转onnx、torchscript方式,具有很好的参考价值,希望对大家有所帮助。一起跟随微点阅读 小编过来看看吧
导语
本文将介绍如何使用ONNX将PyTorch中训练好的模型(.pt、.pth)型转换为ONNX格式,然后将其加载到Caffe2中。需要安装好onnx和Caffe2。
PyTorch及ONNX环境准备
为了正常运行ONNX,我们需要安装最新的Pytorch,你可以选择源码安装:
1
2
3
4
5
6
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的目。
or conda安装
conda install pytorch torchvision -c pytorch
安装ONNX的库
conda install -c conda-forge onnx
onnx-caffe2 安装
pip3 install onnx-caffe2
Pytorch模型转onnx
在PyTorch中导出模型通过跟踪工作。要导出模型,请调用torch.onnx.export()函数。这将执行模型,记录运算符用于计算输出的轨迹。因为_export运行模型,我们需要提供输入张量x。
这个张量的值并不重要; 它可以是图像或随机张量,只要它是正确的大小。
1
2
3
4
5
6
7
8
9
10
11
12
# 输入模型
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进行模型加载推理了。
还可以进一步将onnx模型转换为ncnn进而部署到移动端。这就需要ncnn的onnx2ncnn工具了.
编译ncnn源码,生成 onnx2ncnn。
其中onnx转换模型时有一些冗余,可以使用用工具简化一些onnx模型。
pip3 install onnx-simplifier
简化onnx模型
python3 -m onnxsim pnet.onnx pnet-sim.onnx
转换成ncnn
onnx2ncnn pnet-sim.onnx pnet.param pnet.bin
ncnn 加载模型做推理
Pytorch模型转torch script
pytorch 加入libtorch前端处理,集体步骤为:
以mtcnn pnet为例
1
2
3
4
5
6
7
# 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++调用如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <torch/script.h> // One-stop header.
#include <iostream>
#include <memory>
int
main(
int
argc,
const
char
* argv[])
{
if
(argc != 2)
{
std::cerr <<
"usage: example-app <path-to-exported-script-module>\n"
;
return
-1;
}
// Deserialize the ScriptModule from a file using torch::jit::load().
std::shared_ptr<torch::jit::script::Module> module = torch::jit::load(argv[1]);
assert
(module != nullptr);
std::cout <<
"ok\n"
;
}
转自:微点阅读 https://www.weidianyuedu.com