Pytorch C++部署 之 TorchScript 踩坑记录

小白一枚,最近尝试用c++调pytorch模型,网上搜了一对资料,大同小异,都是需要先将模型文件转换成torch script。
pytorch官网提供两种方式,1:trace 2:注释。
这两种方式怎么操作,官网以及很多博客都有详细介绍,不细扣,我也扣不明白,毕竟我是个小白,放链接供参考:
https://blog.csdn.net/dou3516/article/details/82912480

============================
以下记录踩坑记录:
个人环境:
win10
cuda9.0 + cudnn7.0.5
1050Ti-4G
ptorch 1.0稳定版。。。
默认各种环境已经装好,开始撸起袖子码代码。

自己pytorch写了个简单的分类网络,通过注释的方式将模型序列化,举个栗子:

class myModel(torch.jit.ScriptModule):
    def __init__(self,num_classes):
            super(myModel, self).__init__() 
            ...........         
    @torch.jit.script_method
    def forward(self, x):
             ..........
          return x
 my_script_module = myModel(2)
 my_script_module.save("model.pt")

反正按照官方说法,加注释就是按这个样子加的,那么问题来了,各种各样报错。


错误1:ValueError: substring not found
原因:forward 函数里不能有中文注释


错误2: torch.jit.frontend.UnsupportedNodeError: Dict aren’t supported
原因:forward 函数里初始化字典,由 a={} 改成 a=dict()


错误3:torch.jit.frontend.UnsupportedNodeError: ListComp aren’t supported
原因:出现这个感觉多半是有些语法不支持,可以尝试改写一下,举个栗子
语句 layers = [int(a) for a in layers]
改成 for k in range(len(layers)):
layers[k] = int(layers[k])


错误4:torch.jit.frontend.UnsupportedNodeError: continue statements aren’t supported
原因:这玩意不支持continue语句?这我就很方了。按照程序逻辑改吧,避免用cintinue


错误5:torch.jit.frontend.UnsupportedNodeError: try blocks aren’t supported
原因:嗯。。。。好像也不支持 try except。那就默默改代码逻辑吧


错误6:attribute ‘XXX’ of type ‘list’ is not usable in a script method (did you forget to add it constants?)
原因:按照提示,该加的参数加上。官方解释:
Note
To use a module list inside a @script_method it must be marked
constant by adding the name of the attribute to the constants
list for the type. For loops over a ModuleList will unroll the body of the
loop at compile time, with each member of the constant module list.


错误7:TypeError: ‘dict’ object for attribute ‘XXX’ is not a valid constant.
Valid constants are:

  1. a nn.ModuleList
  2. a value of type {bool, float, int, str, NoneType, function, device, layout, dtype}
  3. a list or tuple of (2)
    原因:说得很明白,人家不支持dict类型,自己手动改成其他类型,绕过dict

错误8:RuntimeError: v->type()->isSubtypeOf(elem_type) ASSERT FAILED at …\torch\csrc\jit\ir.cpp:1387, please report a bug to PyTorch. (createList at …\torch\csrc\jit\ir.cpp:1387)
(no backtrace available)
原因:自己搞不定,等待大神帮我解答…拜谢…

未完待续…

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
PyTorch模型转换为TorchScript的步骤如下: 1. 定义和训练PyTorch模型:首先,您需要定义和训练一个PyTorch模型,这可以通过使用标准的PyTorch代码来完成。 2. 导出PyTorch模型:然后,您需要将PyTorch模型导出为TorchScript格式。这可以通过使用PyTorchtorch.jit模块中的trace函数来完成。trace函数接受一个输入样本并生成一个TorchScript模块。 3. 运行TorchScript模型:一旦您导出了TorchScript模型,您可以像普通的Python模块一样使用它。您可以加载模块并使用其forward方法来运行模型。此外,TorchScript模块还可以与C++和Java等其他语言一起使用。 下面是一个简单的示例代码,演示了如何将PyTorch模型转换为TorchScript: ``` import torch import torchvision # 定义和训练PyTorch模型 model = torchvision.models.resnet18() example_input = torch.rand(1, 3, 224, 224) traced_script_module = torch.jit.trace(model, example_input) # 导出PyTorch模型为TorchScript模块 traced_script_module.save("resnet18.pt") # 加载TorchScript模块并运行模型 loaded_script_module = torch.jit.load("resnet18.pt") output = loaded_script_module(example_input) print(output) ``` 在这个示例代码中,我们首先定义了一个ResNet-18模型,并使用一个随机的输入样本来跟踪模型。然后,我们将跟踪后的模型保存为TorchScript格式。最后,我们加载了TorchScript模块并使用它来运行模型。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值