小白一枚,最近尝试用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:
- a nn.ModuleList
- a value of type {bool, float, int, str, NoneType, function, device, layout, dtype}
- 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)
原因:自己搞不定,等待大神帮我解答…拜谢…
未完待续…