annotations.py 17 KB

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