Pytorch torch.jit.script(模块)vs@torch.jit.script装饰器

Pytorch torch.jit.script(模块)vs@torch.jit.script装饰器,pytorch,torchscript,Pytorch,Torchscript,为什么添加decorator“@torch.jit.script”会导致错误,而我可以在该模块上调用torch.jit.script,例如,此操作失败: import torch @torch.jit.script class MyCell(torch.nn.Module): def __init__(self): super(MyCell, self).__init__() self.linear = torch.nn.Linear(4, 4)

为什么添加decorator“@torch.jit.script”会导致错误,而我可以在该模块上调用torch.jit.script,例如,此操作失败:

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
此问题也出现在上。

您出错的原因是,此要点正是:

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

此外,如顶部所述:

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

目前,它用于简单的Python类(请参阅我提供的链接中的其他点)和函数,有关更多信息,请参阅我提供的链接

您还可以检查以更好地掌握它的工作原理


从表面上看,当您传递一个实例时,所有应该保留的
属性都会被递归解析()。您可以按照此函数进行操作(有很多注释,但回答太长,请参见),尽管我不知道这种情况的确切原因(以及为什么它是这样设计的)(因此希望具有
torch.jit
内部工作专业知识的人会详细介绍它).

如果您从PyTorch论坛获得更深入的解释,请将其作为自我回答发布在此处,谢谢。
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)