pytorch转caffe2模型,方法1亲测可用

原创

pytorch转caffe2模型

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_40671425/article/details/90700908
            </div>
                                                <!--一个博主专栏付费入口-->
         
         <!--一个博主专栏付费入口结束-->
        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-4a3473df85.css">
                                    <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-4a3473df85.css">
            <div class="htmledit_views" id="content_views">
                                        <p>&nbsp; &nbsp; 项目需要用c++调用caffe2接口进行工程化部署,但是模型是用pytorch实现并训练。这就需要把pytorch预训练模型转化为可供c++调用的模型。</p>

 

    目前的问题是:训练环境和工程部署环境是不同的。利用python3.6+pytorch进行训练,模型部署是python2.7+caffe2。

    总体流程:

        1,在训练环境下也就是python3.6+pytorch下利用torch.onnx包把pth文件转化为onnx文件

         2,在python2.7+caffe2环境下把转换好的onnx文件转化为pb文件供c++调用

 

安装编译caffe2参考官网:https://caffe2.ai/docs/getting-started.html?platform=windows&configuration=compile

 

一,pytorch -> onnx


 
 
  1. import numpy as np
  2. import torch
  3. import torch.onnx
  4. from models.faceboxes import FaceBoxes
  5. # 加载定义的网络模型,预测试阶段相同
  6. model = FaceBoxes(phase= 'test', size= None, num_classes= 2)
  7. # 加载预训练模型
  8. pretrained_model = "./pretrained/face_head_brain_our/model_face_brain_ourFinal_FaceBoxes.pth"
  9. # 把预训练模型参数加载进网络,这里采用GPU环境 也可以采用CPU
  10. device = torch.cuda.current_device()
  11. pretrained_dict = torch.load(pretrained_model, map_location= lambda storage, loc: storage.cuda(device))
  12. model.load_state_dict(pretrained_dict, strict= False)
  13. # 将训练模式设置为false, 因为只需要网络forward
  14. model.train( False)
  15. # 生成一个随机张量用于前传,这个张量可以是一个图像张量也可以是一个随机张量,数值不重要,只要size匹配即可
  16. batch_size = 1
  17. x = torch.randn(batch_size, 3, 1024, 1024,requires_grad= True)
  18. print(type(x))
  19. # 导出模型 pytorch -> onnx
  20. """
  21. 这里也可以用torch.onnx.export 详细见:
  22. https://github.com/pytorch/pytorch/blob/master/torch/onnx/utils.py
  23. 但最后都是调用 _export()函数
  24. """
  25. torch_out = torch.onnx._export(
  26. model, # 具有预训练参数的模型
  27. x, # 输入张量,dumm data
  28. "faceboxes.onnx", # 输出文件保存的路径
  29. export_params= True # 保存模型内部训练好的模型参数
  30. )

二,onnx -> caffe2

    方法1:


 
 
  1. import os
  2. import onnx
  3. from caffe2.python.onnx.backend import Caffe2Backend
  4. #也可以用onnx_caffe2中的caffebackend包,需要额外安装onnx_caffe2,但是已经废弃了
  5. # from onnx_caffe2.backend import Caffe2Backend
  6. import argparse
  7. import caffe2.python.utils as putils
  8. from caffe2.python import core, workspace
  9. from caffe2.proto import caffe2_pb2
  10. onnx_proto_file = 'faceboxes-gpu.onnx'
  11. model_name = 'faceboxes'
  12. model_dir = './transform_rst'
  13. if not os.path.exists(model_dir):
  14. os.makedirs(model_dir)
  15. onnx_model = onnx.load(onnx_proto_file)
  16. init_net, predict_net = Caffe2Backend.onnx_graph_to_caffe2_net(onnx_model, device= "CUDA:0")
  17. with open(os.path.join(model_dir, model_name + "_init.pb"), "wb") as f:
  18. f.write(init_net.SerializeToString())
  19. #with open(os.path.join(model_dir, model_name + "_init.pbtxt"), "w") as f:
  20. # f.write(str(init_net))
  21. with open(os.path.join(model_dir, model_name + "_predict.pb"), "wb") as f:
  22. f.write(predict_net.SerializeToString())
  23. #保存为pbtxt文件的格式方便查看转换的网络结构
  24. """
  25. # 如果只有pb也可以用pb文件转化为pbtxtx文件,这两中文件格式可以互相转换
  26. pb和pbtxt互转参考: https://github.com/dzung-hoang/caffe2-utils
  27. """
  28. with open(os.path.join(model_dir, model_name + "_predict.pbtxt"), "w") as f:
  29. f.write(str(predict_net))

    方法2:


 
 
  1. import onnx
  2. import caffe2.python.onnx.backend as backend
  3. import numpy as np
  4. #参考: https://pytorch.org/tutorials/advanced/super_resolution_with_caffe2.html
  5. """
  6. 此方法的转换可以在移动设备上运行,但是转换的效果和用Caffe2Backend包一样的
  7. from caffe2.python.onnx.backend import Caffe2Backend
  8. """
  9. batch_size = 1
  10. dummy_data = np.random.randn( 1, 3, 1024, 1024).astype(np.float32)
  11. model = onnx.load( "faceboxes-gpu.onnx")
  12. onnx.checker.check_model(model)
  13. prepared_backend = backend.prepare(model)
  14. rep = backend.prepare(model,device= "CUDA:0")
  15. output = rep.run(dummy_data)
  16. W = {model.graph.input[ 0].name: dummy_data}
  17. c2_out = rep.run(W)[ 0]
  18. print(c2_out)
  19. #np.testing.assert_almost_equal(torch_out.data.cpu().numpy(), c2_out, decimal=3)
  20. #print("Exported model has been executed on Caffe2 backend, and the result looks good!")
  21. c2_workspace = rep.workspace
  22. c2_model = rep.predict_net
  23. from caffe2.python.predictor import mobile_exporter
  24. init_net, predict_net = mobile_exporter.Export(c2_workspace, c2_model, c2_model.external_input)
  25. with open( 'init_net.pb', "wb") as fopen:
  26. fopen.write(init_net.SerializeToString())
  27. with open( 'predict_net.pb', "wb") as fopen:
  28. fopen.write(predict_net.SerializeToString())

    方法3:直接采用命令行

    

convert-onnx-to-caffe2 assets/squeezenet.onnx --output predict_net.pb --init-net-output init_net.pb
 
 

 

文章最后发布于: 2019-05-30 17:19:16
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值