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 also refine basic types such as bools and ints that
(obj, target_type)
| 194 | |
| 195 | # for torch.jit.isinstance |
| 196 | def isinstance(obj, target_type): |
| 197 | """ |
| 198 | Provide container type refinement in TorchScript. |
| 199 | |
| 200 | It can refine parameterized containers of the List, Dict, Tuple, and Optional types. E.g. ``List[str]``, |
| 201 | ``Dict[str, List[torch.Tensor]]``, ``Optional[Tuple[int,str,int]]``. It can also |
| 202 | refine basic types such as bools and ints that are available in TorchScript. |
| 203 | |
| 204 | Args: |
| 205 | obj: object to refine the type of |
| 206 | target_type: type to try to refine obj to |
| 207 | Returns: |
| 208 | ``bool``: True if obj was successfully refined to the type of target_type, |
| 209 | False otherwise with no new type refinement |
| 210 | |
| 211 | |
| 212 | Example (using ``torch.jit.isinstance`` for type refinement): |
| 213 | .. testcode:: |
| 214 | |
| 215 | import torch |
| 216 | from typing import Any, Dict, List |
| 217 | |
| 218 | class MyModule(torch.nn.Module): |
| 219 | def __init__(self): |
| 220 | super().__init__() |
| 221 | |
| 222 | def forward(self, input: Any): # note the Any type |
| 223 | if torch.jit.isinstance(input, List[torch.Tensor]): |
| 224 | for t in input: |
| 225 | y = t.clamp(0, 0.5) |
| 226 | elif torch.jit.isinstance(input, Dict[str, str]): |
| 227 | for val in input.values(): |
| 228 | print(val) |
| 229 | |
| 230 | m = torch.jit.script(MyModule()) |
| 231 | x = [torch.rand(3,3), torch.rand(4,3)] |
| 232 | m(x) |
| 233 | y = {"key1":"val1","key2":"val2"} |
| 234 | m(y) |
| 235 | """ |
| 236 | return _isinstance(obj, target_type) |
| 237 | |
| 238 | |
| 239 | class strict_fusion: |
searching dependent graphs…