annotations.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. # mypy: allow-untyped-defs
  2. import ast
  3. import builtins
  4. import dis
  5. import enum
  6. import inspect
  7. import re
  8. import typing
  9. import warnings
  10. from textwrap import dedent
  11. from typing import Type
  12. import torch
  13. from torch._C import (
  14. _GeneratorType,
  15. AnyType,
  16. AwaitType,
  17. BoolType,
  18. ComplexType,
  19. DeviceObjType,
  20. DictType,
  21. EnumType,
  22. FloatType,
  23. FutureType,
  24. InterfaceType,
  25. IntType,
  26. ListType,
  27. NoneType,
  28. NumberType,
  29. OptionalType,
  30. StreamObjType,
  31. StringType,
  32. TensorType,
  33. TupleType,
  34. UnionType,
  35. )
  36. from torch._sources import get_source_lines_and_file
  37. from .._jit_internal import ( # type: ignore[attr-defined]
  38. _Await,
  39. _qualified_name,
  40. Any,
  41. BroadcastingList1,
  42. BroadcastingList2,
  43. BroadcastingList3,
  44. Dict,
  45. Future,
  46. is_await,
  47. is_dict,
  48. is_future,
  49. is_ignored_fn,
  50. is_list,
  51. is_optional,
  52. is_tuple,
  53. is_union,
  54. List,
  55. Optional,
  56. Tuple,
  57. Union,
  58. )
  59. from ._state import _get_script_class
  60. if torch.distributed.rpc.is_available():
  61. from torch._C import RRefType
  62. from .._jit_internal import is_rref, RRef
  63. from torch._ops import OpOverloadPacket
  64. class Module:
  65. def __init__(self, name, members):
  66. self.name = name
  67. self.members = members
  68. def __getattr__(self, name):
  69. try:
  70. return self.members[name]
  71. except KeyError:
  72. raise RuntimeError(
  73. f"Module {self.name} has no member called {name}"
  74. ) from None
  75. class EvalEnv:
  76. env = {
  77. "torch": Module("torch", {"Tensor": torch.Tensor}),
  78. "Tensor": torch.Tensor,
  79. "typing": Module("typing", {"Tuple": Tuple}),
  80. "Tuple": Tuple,
  81. "List": List,
  82. "Dict": Dict,
  83. "Optional": Optional,
  84. "Union": Union,
  85. "Future": Future,
  86. "Await": _Await,
  87. }
  88. def __init__(self, rcb):
  89. self.rcb = rcb
  90. if torch.distributed.rpc.is_available():
  91. self.env["RRef"] = RRef
  92. def __getitem__(self, name):
  93. if name in self.env:
  94. return self.env[name]
  95. if self.rcb is not None:
  96. return self.rcb(name)
  97. return getattr(builtins, name, None)
  98. def get_signature(fn, rcb, loc, is_method):
  99. if isinstance(fn, OpOverloadPacket):
  100. signature = try_real_annotations(fn.op, loc)
  101. else:
  102. signature = try_real_annotations(fn, loc)
  103. if signature is not None and is_method:
  104. # If this is a method, then the signature will include a type for
  105. # `self`, but type comments do not contain a `self`. So strip it
  106. # away here so everything is consistent (`inspect.ismethod` does
  107. # not work here since `fn` is unbound at this point)
  108. param_types, return_type = signature
  109. param_types = param_types[1:]
  110. signature = (param_types, return_type)
  111. if signature is None:
  112. type_line, source = None, None
  113. try:
  114. source = dedent("".join(get_source_lines_and_file(fn)[0]))
  115. type_line = get_type_line(source)
  116. except TypeError:
  117. pass
  118. # This might happen both because we failed to get the source of fn, or
  119. # because it didn't have any annotations.
  120. if type_line is not None:
  121. signature = parse_type_line(type_line, rcb, loc)
  122. return signature
  123. def is_function_or_method(the_callable):
  124. # A stricter version of `inspect.isroutine` that does not pass for built-in
  125. # functions
  126. return inspect.isfunction(the_callable) or inspect.ismethod(the_callable)
  127. def is_vararg(the_callable):
  128. if not is_function_or_method(the_callable) and callable(the_callable): # noqa: B004
  129. # If `the_callable` is a class, de-sugar the call so we can still get
  130. # the signature
  131. the_callable = the_callable.__call__
  132. if is_function_or_method(the_callable):
  133. return inspect.getfullargspec(the_callable).varargs is not None
  134. else:
  135. return False
  136. def get_param_names(fn, n_args):
  137. if isinstance(fn, OpOverloadPacket):
  138. fn = fn.op
  139. if (
  140. not is_function_or_method(fn)
  141. and callable(fn)
  142. and is_function_or_method(fn.__call__)
  143. ): # noqa: B004
  144. # De-sugar calls to classes
  145. fn = fn.__call__
  146. if is_function_or_method(fn):
  147. if is_ignored_fn(fn):
  148. fn = inspect.unwrap(fn)
  149. return inspect.getfullargspec(fn).args
  150. else:
  151. # The `fn` was not a method or function (maybe a class with a __call__
  152. # method, so use a default param name list)
  153. return [str(i) for i in range(n_args)]
  154. def check_fn(fn, loc):
  155. # Make sure the function definition is not a class instantiation
  156. try:
  157. source = dedent("".join(get_source_lines_and_file(fn)[0]))
  158. except (OSError, TypeError):
  159. return
  160. if source is None:
  161. return
  162. py_ast = ast.parse(source)
  163. if len(py_ast.body) == 1 and isinstance(py_ast.body[0], ast.ClassDef):
  164. raise torch.jit.frontend.FrontendError(
  165. loc,
  166. f"Cannot instantiate class '{py_ast.body[0].name}' in a script function",
  167. )
  168. if len(py_ast.body) != 1 or not isinstance(py_ast.body[0], ast.FunctionDef):
  169. raise torch.jit.frontend.FrontendError(
  170. loc, "Expected a single top-level function"
  171. )
  172. def _eval_no_call(stmt, glob, loc):
  173. """Evaluate statement as long as it does not contain any method/function calls."""
  174. bytecode = compile(stmt, "", mode="eval")
  175. for insn in dis.get_instructions(bytecode):
  176. if "CALL" in insn.opname:
  177. raise RuntimeError(
  178. f"Type annotation should not contain calls, but '{stmt}' does"
  179. )
  180. return eval(bytecode, glob, loc) # type: ignore[arg-type] # noqa: P204
  181. def parse_type_line(type_line, rcb, loc):
  182. """Parse a type annotation specified as a comment.
  183. Example inputs:
  184. # type: (Tensor, torch.Tensor) -> Tuple[Tensor]
  185. # type: (Tensor, Tuple[Tensor, Tensor]) -> Tensor
  186. """
  187. arg_ann_str, ret_ann_str = split_type_line(type_line)
  188. try:
  189. arg_ann = _eval_no_call(arg_ann_str, {}, EvalEnv(rcb))
  190. except (NameError, SyntaxError) as e:
  191. raise RuntimeError(
  192. "Failed to parse the argument list of a type annotation"
  193. ) from e
  194. if not isinstance(arg_ann, tuple):
  195. arg_ann = (arg_ann,)
  196. try:
  197. ret_ann = _eval_no_call(ret_ann_str, {}, EvalEnv(rcb))
  198. except (NameError, SyntaxError) as e:
  199. raise RuntimeError(
  200. "Failed to parse the return type of a type annotation"
  201. ) from e
  202. arg_types = [ann_to_type(ann, loc) for ann in arg_ann]
  203. return arg_types, ann_to_type(ret_ann, loc)
  204. def get_type_line(source):
  205. """Try to find the line containing a comment with the type annotation."""
  206. type_comment = "# type:"
  207. lines = source.split("\n")
  208. lines = list(enumerate(lines))
  209. type_lines = list(filter(lambda line: type_comment in line[1], lines))
  210. # `type: ignore` comments may be needed in JIT'ed functions for mypy, due
  211. # to the hack in torch/_VF.py.
  212. # An ignore type comment can be of following format:
  213. # 1) type: ignore
  214. # 2) type: ignore[rule-code]
  215. # This ignore statement must be at the end of the line
  216. # adding an extra backslash before the space, to avoid triggering
  217. # one of the checks in .github/workflows/lint.yml
  218. type_pattern = re.compile("# type:\\ ignore(\\[[a-zA-Z-]+\\])?$")
  219. type_lines = list(filter(lambda line: not type_pattern.search(line[1]), type_lines))
  220. if len(type_lines) == 0:
  221. # Catch common typo patterns like extra spaces, typo in 'ignore', etc.
  222. wrong_type_pattern = re.compile("#[\t ]*type[\t ]*(?!: ignore(\\[.*\\])?$):")
  223. wrong_type_lines = list(
  224. filter(lambda line: wrong_type_pattern.search(line[1]), lines)
  225. )
  226. if len(wrong_type_lines) > 0:
  227. raise RuntimeError(
  228. "The annotation prefix in line "
  229. + str(wrong_type_lines[0][0])
  230. + " is probably invalid.\nIt must be '# type:'"
  231. + "\nSee PEP 484 (https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code)" # noqa: B950
  232. + "\nfor examples"
  233. )
  234. return None
  235. elif len(type_lines) == 1:
  236. # Only 1 type line, quit now
  237. return type_lines[0][1].strip()
  238. # Parse split up argument types according to PEP 484
  239. # https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code
  240. return_line = None
  241. parameter_type_lines = []
  242. for line_num, line in type_lines:
  243. if "# type: (...) -> " in line:
  244. return_line = (line_num, line)
  245. break
  246. elif type_comment in line:
  247. parameter_type_lines.append(line)
  248. if return_line is None:
  249. raise RuntimeError(
  250. "Return type line '# type: (...) -> ...' not found on multiline "
  251. "type annotation\nfor type lines:\n"
  252. + "\n".join([line[1] for line in type_lines])
  253. + "\n(See PEP 484 https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code)"
  254. )
  255. def get_parameter_type(line):
  256. item_type = line[line.find(type_comment) + len(type_comment) :]
  257. return item_type.strip()
  258. types = map(get_parameter_type, parameter_type_lines)
  259. parameter_types = ", ".join(types)
  260. return return_line[1].replace("...", parameter_types)
  261. def split_type_line(type_line):
  262. """Split the comment with the type annotation into parts for argument and return types.
  263. For example, for an input of:
  264. # type: (Tensor, torch.Tensor) -> Tuple[Tensor, Tensor]
  265. This function will return:
  266. ("(Tensor, torch.Tensor)", "Tuple[Tensor, Tensor]")
  267. """
  268. start_offset = len("# type:")
  269. try:
  270. arrow_pos = type_line.index("->")
  271. except ValueError:
  272. raise RuntimeError(
  273. "Syntax error in type annotation (couldn't find `->`)"
  274. ) from None
  275. return type_line[start_offset:arrow_pos].strip(), type_line[arrow_pos + 2 :].strip()
  276. def try_real_annotations(fn, loc):
  277. """Try to use the Py3.5+ annotation syntax to get the type."""
  278. try:
  279. # Note: anything annotated as `Optional[T]` will automatically
  280. # be returned as `Union[T, None]` per
  281. # https://github.com/python/typing/blob/master/src/typing.py#L850
  282. sig = inspect.signature(fn)
  283. except ValueError:
  284. return None
  285. all_annots = [sig.return_annotation] + [
  286. p.annotation for p in sig.parameters.values()
  287. ]
  288. if all(ann is sig.empty for ann in all_annots):
  289. return None
  290. arg_types = [ann_to_type(p.annotation, loc) for p in sig.parameters.values()]
  291. return_type = ann_to_type(sig.return_annotation, loc)
  292. return arg_types, return_type
  293. # Finds common type for enum values belonging to an Enum class. If not all
  294. # values have the same type, AnyType is returned.
  295. def get_enum_value_type(e: Type[enum.Enum], loc):
  296. enum_values: List[enum.Enum] = list(e)
  297. if not enum_values:
  298. raise ValueError(f"No enum values defined for: '{e.__class__}'")
  299. types = {type(v.value) for v in enum_values}
  300. ir_types = [try_ann_to_type(t, loc) for t in types]
  301. # If Enum values are of different types, an exception will be raised here.
  302. # Even though Python supports this case, we chose to not implement it to
  303. # avoid overcomplicate logic here for a rare use case. Please report a
  304. # feature request if you find it necessary.
  305. res = torch._C.unify_type_list(ir_types)
  306. if not res:
  307. return AnyType.get()
  308. return res
  309. def is_tensor(ann):
  310. if issubclass(ann, torch.Tensor):
  311. return True
  312. if issubclass(
  313. ann,
  314. (
  315. torch.LongTensor,
  316. torch.DoubleTensor,
  317. torch.FloatTensor,
  318. torch.IntTensor,
  319. torch.ShortTensor,
  320. torch.HalfTensor,
  321. torch.CharTensor,
  322. torch.ByteTensor,
  323. torch.BoolTensor,
  324. ),
  325. ):
  326. warnings.warn(
  327. "TorchScript will treat type annotations of Tensor "
  328. "dtype-specific subtypes as if they are normal Tensors. "
  329. "dtype constraints are not enforced in compilation either."
  330. )
  331. return True
  332. return False
  333. def _fake_rcb(inp):
  334. return None
  335. def try_ann_to_type(ann, loc, rcb=None):
  336. ann_args = typing.get_args(ann) # always returns a tuple!
  337. if ann is inspect.Signature.empty:
  338. return TensorType.getInferred()
  339. if ann is None:
  340. return NoneType.get()
  341. if inspect.isclass(ann) and is_tensor(ann):
  342. return TensorType.get()
  343. if is_tuple(ann):
  344. # Special case for the empty Tuple type annotation `Tuple[()]`
  345. if len(ann_args) == 1 and ann_args[0] == ():
  346. return TupleType([])
  347. return TupleType([try_ann_to_type(a, loc) for a in ann_args])
  348. if is_list(ann):
  349. elem_type = try_ann_to_type(ann_args[0], loc)
  350. if elem_type:
  351. return ListType(elem_type)
  352. if is_dict(ann):
  353. key = try_ann_to_type(ann_args[0], loc)
  354. value = try_ann_to_type(ann_args[1], loc)
  355. # Raise error if key or value is None
  356. if key is None:
  357. raise ValueError(
  358. f"Unknown type annotation: '{ann_args[0]}' at {loc.highlight()}"
  359. )
  360. if value is None:
  361. raise ValueError(
  362. f"Unknown type annotation: '{ann_args[1]}' at {loc.highlight()}"
  363. )
  364. return DictType(key, value)
  365. if is_optional(ann):
  366. if issubclass(ann_args[1], type(None)):
  367. contained = ann_args[0]
  368. else:
  369. contained = ann_args[1]
  370. valid_type = try_ann_to_type(contained, loc)
  371. msg = "Unsupported annotation {} could not be resolved because {} could not be resolved. At\n{}"
  372. assert valid_type, msg.format(repr(ann), repr(contained), repr(loc))
  373. return OptionalType(valid_type)
  374. if is_union(ann):
  375. # TODO: this is hack to recognize NumberType
  376. if set(ann_args) == {int, float, complex}:
  377. return NumberType.get()
  378. inner: List = []
  379. # We need these extra checks because both `None` and invalid
  380. # values will return `None`
  381. # TODO: Determine if the other cases need to be fixed as well
  382. for a in typing.get_args(ann):
  383. if a is None:
  384. inner.append(NoneType.get())
  385. maybe_type = try_ann_to_type(a, loc)
  386. msg = "Unsupported annotation {} could not be resolved because {} could not be resolved. At\n{}"
  387. assert maybe_type, msg.format(repr(ann), repr(maybe_type), repr(loc))
  388. inner.append(maybe_type)
  389. return UnionType(inner) # type: ignore[arg-type]
  390. if torch.distributed.rpc.is_available() and is_rref(ann):
  391. return RRefType(try_ann_to_type(ann_args[0], loc))
  392. if is_future(ann):
  393. return FutureType(try_ann_to_type(ann_args[0], loc))
  394. if is_await(ann):
  395. elementType = try_ann_to_type(ann_args[0], loc) if ann_args else AnyType.get()
  396. return AwaitType(elementType)
  397. if ann is float:
  398. return FloatType.get()
  399. if ann is complex:
  400. return ComplexType.get()
  401. if ann is int or ann is torch.SymInt:
  402. return IntType.get()
  403. if ann is str:
  404. return StringType.get()
  405. if ann is bool:
  406. return BoolType.get()
  407. if ann is Any:
  408. return AnyType.get()
  409. if ann is type(None):
  410. return NoneType.get()
  411. if inspect.isclass(ann) and hasattr(ann, "__torch_script_interface__"):
  412. return InterfaceType(ann.__torch_script_interface__)
  413. if ann is torch.device:
  414. return DeviceObjType.get()
  415. if ann is torch.Generator:
  416. return _GeneratorType.get()
  417. if ann is torch.Stream:
  418. return StreamObjType.get()
  419. if ann is torch.dtype:
  420. return IntType.get() # dtype not yet bound in as its own type
  421. if inspect.isclass(ann) and issubclass(ann, enum.Enum):
  422. if _get_script_class(ann) is None:
  423. scripted_class = torch.jit._script._recursive_compile_class(ann, loc)
  424. name = scripted_class.qualified_name()
  425. else:
  426. name = _qualified_name(ann)
  427. return EnumType(name, get_enum_value_type(ann, loc), list(ann))
  428. if inspect.isclass(ann):
  429. maybe_script_class = _get_script_class(ann)
  430. if maybe_script_class is not None:
  431. return maybe_script_class
  432. if torch._jit_internal.can_compile_class(ann):
  433. return torch.jit._script._recursive_compile_class(ann, loc)
  434. # Maybe resolve a NamedTuple to a Tuple Type
  435. if rcb is None:
  436. rcb = _fake_rcb
  437. return torch._C._resolve_type_from_object(ann, loc, rcb)
  438. def ann_to_type(ann, loc, rcb=None):
  439. the_type = try_ann_to_type(ann, loc, rcb)
  440. if the_type is not None:
  441. return the_type
  442. raise ValueError(f"Unknown type annotation: '{ann}' at {loc.highlight()}")
  443. __all__ = [
  444. "Any",
  445. "List",
  446. "BroadcastingList1",
  447. "BroadcastingList2",
  448. "BroadcastingList3",
  449. "Tuple",
  450. "is_tuple",
  451. "is_list",
  452. "Dict",
  453. "is_dict",
  454. "is_optional",
  455. "is_union",
  456. "TensorType",
  457. "TupleType",
  458. "FloatType",
  459. "ComplexType",
  460. "IntType",
  461. "ListType",
  462. "StringType",
  463. "DictType",
  464. "AnyType",
  465. "Module",
  466. # TODO: Consider not exporting these during wildcard import (reserve
  467. # that for the types; for idiomatic typing code.)
  468. "get_signature",
  469. "check_fn",
  470. "get_param_names",
  471. "parse_type_line",
  472. "get_type_line",
  473. "split_type_line",
  474. "try_real_annotations",
  475. "try_ann_to_type",
  476. "ann_to_type",
  477. ]