快捷方式

torch.jit.annotate

torch.jit.annotate(the_type, the_value)[原始碼][原始碼]

用於在 TorchScript 編譯器中指定 the_value 的型別。

此方法是一個直通函式,返回 the_value,用於向 TorchScript 編譯器提示 the_value 的型別。在 TorchScript 外部執行時,此函式不起作用(no-op)。

儘管 TorchScript 可以推斷大多數 Python 表示式的正確型別,但在某些情況下,型別推斷可能不準確,包括:

  • 空容器,如 []{},TorchScript 預設將其視為 Tensor 的容器

  • 可選型別,如 Optional[T],但實際賦值為型別 T 的有效值時,TorchScript 會假定其型別為 T 而非 Optional[T]

注意,annotate()torch.nn.Module 子類的 __init__ 方法中不起作用,因為它是在 Eager 模式下執行的。要標註 torch.nn.Module 屬性的型別,請改用 Attribute()

示例

import torch
from typing import Dict

@torch.jit.script
def fn():
    # Telling TorchScript that this empty dictionary is a (str -> int) dictionary
    # instead of default dictionary type of (str -> Tensor).
    d = torch.jit.annotate(Dict[str, int], {})

    # Without `torch.jit.annotate` above, following statement would fail because of
    # type mismatch.
    d["name"] = 20
引數
  • the_type – 應傳遞給 TorchScript 編譯器作為 the_value 型別提示的 Python 型別

  • the_value – 需要提示型別的 值 或 表示式。

返回值

the_value 作為返回值傳回。

文件

查閱 PyTorch 全面的開發者文件

檢視文件

教程

獲取面向初學者和高階開發者的深度教程

檢視教程

資源

查詢開發資源並解答疑問

檢視資源