torch.jit.script模块vs @ torch.jit.script装饰器

问题描述

为什么要添加装饰器“ @ torch.jit.script”会导致错误,而我可以在该模块上调用torch.jit.script,例如失败了:

''.join([str(child) for child in soup.select('.c-w .c-s')[0].findAll()])

以下代码可以正常工作:

import torch

@torch.jit.script
class MyCell(torch.nn.Module):
    def __init__(self):
        super(MyCell,self).__init__()
        self.linear = torch.nn.Linear(4,4)

    def forward(self,x,h):
        new_h = torch.tanh(self.linear(x) + h)
        return new_h,new_h

my_cell = MyCell()
x,h = torch.rand(3,4),torch.rand(3,4)
traced_cell = torch.jit.script(my_cell,(x,h))
print(traced_cell)
traced_cell(x,h)

"C:\Users\Administrator\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\torch\jit\__init__.py",line 1262,in script
    raise RuntimeError("Type '{}' cannot be compiled since it inherits"
RuntimeError: Type '<class '__main__.MyCell'>' cannot be compiled since it inherits from nn.Module,pass an instance instead

此问题也出现在PyTorch forums上。

解决方法

您的错误原因是here,此提示正是:

不支持继承或任何其他多态性策略,除非 从对象继承以指定新样式的类。

此外,如顶部所述:

TorchScript类支持是实验性的。目前最适合 对于简单的类似记录的类型(使用方法来命名NamedTuple 附件)。

当前,它的目的是用于简单的 Python 类(请参阅我提供的链接中的其他要点)和函数,请参阅我提供的链接以获取更多信息。

您也可以选中torch.jit.script source code,以更好地了解其工作原理。

从表面上看,当您传递实例时,所有应保留的attributes都会被递归解析(source)。您可以沿用此功能(有注释,但回答的时间太长,请参见here),尽管我确实不知道这种情况的确切原因(以及如此设计的原因),所以希望有人在torch.jit的内部运作方面具有专业知识的人会对此进行详细说明。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...