torch.jit.ignore¶
- torch.jit.ignore(drop=False, **kwargs)[源代码][源代码]¶
此装饰器向编译器表明应忽略函数或方法,并将其保留为 Python 函数。这允许您在模型中保留尚未与 TorchScript 兼容的代码。如果从 TorchScript 调用,忽略的函数会将调用分派给 Python 解释器。具有忽略函数的模型无法导出;请改用
@torch.jit.unused
。示例(在方法上使用
@torch.jit.ignore
)import torch import torch.nn as nn class MyModule(nn.Module): @torch.jit.ignore def debugger(self, x): import pdb pdb.set_trace() def forward(self, x): x += 10 # The compiler would normally try to compile `debugger`, # but since it is `@ignore`d, it will be left as a call # to Python self.debugger(x) return x m = torch.jit.script(MyModule()) # Error! The call `debugger` cannot be saved since it calls into Python m.save("m.pt")
示例(在方法上使用
@torch.jit.ignore(drop=True)
)import torch import torch.nn as nn class MyModule(nn.Module): @torch.jit.ignore(drop=True) def training_method(self, x): import pdb pdb.set_trace() def forward(self, x): if self.training: self.training_method(x) return x m = torch.jit.script(MyModule()) # This is OK since `training_method` is not saved, the call is replaced # with a `raise`. m.save("m.pt")