当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python PyTorch ignore用法及代码示例


本文简要介绍python语言中 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")

相关用法


注:本文由纯净天空筛选整理自pytorch.org大神的英文原创作品 torch.jit.ignore。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。