快捷方式

torch.jit.annotate

torch.jit.annotate(the_type, the_value)[来源][来源]

用于在 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 – 应该作为 the_value 的类型提示传递给 TorchScript 编译器的 Python 类型

  • the_value – 要提示类型的 Value 或表达式。

返回值

the_value 作为返回值传递回来。

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取面向初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并获得问题解答

查看资源