torch.jit.isinstance¶
- torch.jit.isinstance(obj, target_type)[source][source]¶
在 TorchScript 中提供容器类型细化。
它可以精炼 List、Dict、Tuple 和 Optional 类型的参数化容器。例如:
List[str]
,Dict[str, List[torch.Tensor]]
,Optional[Tuple[int,str,int]]
。它还可以精炼 TorchScript 中可用的基本类型,如 bools 和 ints。- 参数:
obj – 要精炼的对象类型
target_type – 尝试将 obj 精炼到的类型
- 返回值:
- 如果 obj 成功精炼到 target_type 类型,则为 True
否则为假,没有新的类型细化
- 返回类型:
bool
示例(使用
torch.jit.isinstance
进行类型细化):.. 测试代码:import torch from typing import Any, Dict, List class MyModule(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward(self, input: Any): # note the Any type if torch.jit.isinstance(input, List[torch.Tensor]): for t in input: y = t.clamp(0, 0.5) elif torch.jit.isinstance(input, Dict[str, str]): for val in input.values(): print(val) m = torch.jit.script(MyModule()) x = [torch.rand(3,3), torch.rand(4,3)] m(x) y = {"key1":"val1","key2":"val2"} m(y)