當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。