torch.jit.isinstance#
- torch.jit.isinstance(obj,target_type)[source]#
Provide container type refinement in TorchScript.
It can refine parameterized containers of the List, Dict, Tuple, and Optional types. E.g.
List[str],Dict[str,List[torch.Tensor]],Optional[Tuple[int,str,int]]. It can alsorefine basic types such as bools and ints that are available in TorchScript.- Parameters
obj – object to refine the type of
target_type – type to try to refine obj to
- Returns
- True if obj was successfully refined to the type of target_type,
False otherwise with no new type refinement
- Return type
bool
Example (using
torch.jit.isinstancefor type refinement):.. testcode:importtorchfromtypingimportAny,Dict,ListclassMyModule(torch.nn.Module):def__init__(self)->None:super().__init__()defforward(self,input:Any):# note the Any typeiftorch.jit.isinstance(input,List[torch.Tensor]):fortininput:y=t.clamp(0,0.5)eliftorch.jit.isinstance(input,Dict[str,str]):forvalininput.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)