pytorch to onnx to caffe,转两种方法,以及部分转换问题记录

1、pytorch 直接转caffe,

自己还没有尝试,
步骤

保存pytorch参数名和权重。先把pytorch的参数名和权重存成词典,例如存到npy文件里–>.得到npy文件;
合并卷积层和bn层的参数(非必须)。将卷积层和batch normalization层的权重进行融合,更新npy文件里卷积层的权重–>.得到npy文件;
建立caffe的.prototxt文件。即按照pytorch的网络架构写出caffe的架构–>得到.prototxt文件;
建立参数名映射。建立caffe—>pytorch的参数名称映射,可以存在字典或者txt里面–>得到.txt文件;
建立caffemodel。按照参数名称的映射,将pytorch的参数权重赋予对应的caffe参数–>得到.caffemodel文件;
推测。在python中将caffemodel嵌进去,进行推断,看看能不能得到对应结果。

————————————————
原文链接:https://blog.csdn.net/vvnzhang2095/article/details/91439924
pytorch2caffe,代码
https://github.com/longcw/pytorch2caffe

2、pytorch onnx caffe

https://github.com/MTlab/onnx2caffe ,代码可用但是
池化有问题,caffe 最大池化如下3,做修改重新编译,可以使用
onnx模型最好,进行简化操作去除onnx出现的多余的层得到new onnx模型,再转换onnx2caffe,
onnx-simplifier.py,代码地址,
https://github.com/daquexian/onnx-simplifier/issues/2

注意版本问题,pytorch

onnx 1.4.1
pytorch 1.3.0
torchvision 0.4.1
np ‘1.16.5’

注意版本问题 mxnet,onnx 不能用最新版本

mxnet-1.4.0 numpy-1.14.6 not use 1.5.1 error(install mxnet-cu100)
onnx 1.2.1
np ‘1.16.5’ ,1.14.6 all ok,建议numpy 高版本,不会错

error1

if error,Your model ir_version is higher than the checker’s. #2
Please try to upgrade your onnx by a command like

error2

mxnet.base.MXNetError: [16:04:06] src/ndarray/ndarray.cc:1805: Check failed: fi->Read(data) Invalid NDArray file format ,
this is mxnet version

pip install --upgrade onnx

3、 转换问题:

取整问题,
caffe卷积向下取整,池化向上取整。
pytorch 默认都是下取整,ceil_mode=True ,是上取整
,所以池化操作会有问题
https://blog.csdn.net/qq_37541097/article/details/102926037 pytorch 取整的详细内容

例如
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1,ceil_mode=True)

bug,pytorch最大池化Maxpool ,默认的参数模型都是下取得整数
但是caffe,得到的是上取整数,
方法
caffe 源码加上卷积下取整的功能
https://blog.csdn.net/weixin_38501242/article/details/82624071

pytorch to caffe
https://blog.csdn.net/vvnzhang2095/article/details/91439924

发布了98 篇原创文章 · 获赞 141 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/m0_37192554/article/details/103363571