torch.jit.annotate¶
- torch.jit.annotate(类型, 值)[来源][来源] ¶
用于在 TorchScript 编译器中指定_the_value 的类型。
此方法是一个透传函数,返回值_value,用于向 TorchScript 编译器提示值_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 作为返回值返回。