torch.jit.annotate#
- torch.jit.annotate(the_type, the_value)[source]#
用於在 TorchScript 編譯器中指定 the_value 的型別。
此方法是一個傳遞函式,返回 the_value,用於向 TorchScript 編譯器提示 the_value 的型別。在 TorchScript 外部執行時,它是一個空操作。
儘管 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 編譯器的 Python 型別,作為 the_value 的型別提示。
the_value – 要提示其型別的數值或表示式。
- 返回
the_value 將作為返回值返回。