东方耀AI技术分享

标题: pytorch转caffe模型的实战操作 [打印本页]

作者: 东方耀    时间: 2020-8-7 14:23
标题: pytorch转caffe模型的实战操作

pytorch转caffe模型的实战操作

总体思路是:pytorch ---> onnx ---> caffe

pytorch转onnx很容易:torch.onnx.export
http://www.ai111.vip/thread-1077-1-1.html

onnx转caffe :https://github.com/MTlab/onnx2caffe


遇到的问题及解决:
1、onnx转caffe的时候很多层提示不支持:
TypeError: ONNX node of type PRelu is not supported.
TypeError: ONNX node of type Shape is not supported
TypeError: ONNX node of type MatMul is not supported.


2、激活函数PRelu修改为Relu之后 重新训练pytorch模型
# 修改激活函数: onnx -->caffe  不支持prelu
        self.prelu = ReLU(out_c)
        
3、type Shape 是在flatten层出现的,修改为torch.reshape还是不行
class Flatten_dfy(Module):
    def forward(self, input):
        # torch.reshape()
        # torch.flatten()
        # 返回具有与self相同的数据和元素数量但具有指定形状的张量。
        # torch.reshape(input, shape) → Tensor
        # return torch.reshape(input, shape=(input.size(0), -1))
        return input.view(input.size(0), -1)
后来查资料是要将onnx模型简化:https://github.com/daquexian/onnx-simplifier
一键转换:  https://convertmodel.com/  之后就没有type Shape了



4、type MatMul的 来源是from torch.nn import Linear 就是一个fc层
这个都不支持,实在无语了!最后稍微修改了网络结构,用一个conv2d层(kernel_size=1*1)替换该fc层
注意:保持参数量的不变    之后需要重新训练网络
至此,onnx转caffe终于成功啦!




作者: 东方耀    时间: 2020-8-7 14:39
还可以继续深入研究,有些不支持的层可以自己写出来,由于时间关系,只能往后拖了,以后研究出来了再分享吧
作者: 东方耀    时间: 2020-8-7 14:40
另外将bn层融入conv层 可提高inference的时间
作者: 东方耀    时间: 2020-8-7 14:44

B、pytorch 直接转caffe (待研究)

pytorch到caffe的坑:反卷积的padding maxpooling的尺寸大小

取整的时候caffe往上取而pytorch往下取,pytorch的maxpool可以设置ceil_mode,把它设置为True就好了

1、保存pytorch参数名和权重。先把pytorch的参数名和权重存成词典,例如存到npy文件里–>.得到npy文件;

2、合并卷积层和bn层的参数(非必须)。将卷积层和batch normalization层的权重进行融合,
更新npy文件里卷积层的权重–>.得到新npy文件;
实际上bn层的weight和bias就是bn层的gamma和beta,通过公式展开就可以得到新的weight和bias了
这一步非必须,适用于卷积层后紧跟bn层的情形,主要是为了节省计算量
在Caffe上做过测试,GTX1080平台,ResNet-50从13.9ms变成了9.5ms

3、建立caffe的.prototxt文件。即按照pytorch的网络架构写出caffe的架构–>得到.prototxt文件;
4、建立参数名映射。建立caffe—>pytorch的参数名称映射,可以存在字典或者txt里面–>得到.txt文件;
5、建立caffemodel。按照参数名称的映射,将pytorch的参数权重赋予对应的caffe参数–>得到.caffemodel文件;
6、推测。在python中将caffemodel嵌进去,进行推断,看看能不能得到对应结果。

https://github.com/xxradon/PytorchToCaffe
https://github.com/hahnyuan/nn_tools
https://blog.csdn.net/vvnzhang2095/article/details/91439924
作者: 东方耀    时间: 2020-8-7 14:46
onnx Shape  Gather  Unsqueeze Concat


先使用这个https://github.com/daquexian/onnx-simplifier,可以去掉这些层




欢迎光临 东方耀AI技术分享 (http://ai111.vip/) Powered by Discuz! X3.4