infer_schema.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. # mypy: allow-untyped-defs
  2. import collections
  3. import inspect
  4. import typing
  5. from types import GenericAlias
  6. from typing import Optional, Union
  7. import torch
  8. from torch import device, dtype, Tensor, types
  9. from torch.utils._exposed_in import exposed_in
  10. # This is used as a negative test for
  11. # test_custom_ops.py::TestTypeConversion::test_type_eval.
  12. _TestTensor = torch.Tensor
  13. @exposed_in("torch.library")
  14. def infer_schema(
  15. prototype_function: typing.Callable,
  16. /,
  17. *,
  18. mutates_args,
  19. op_name: Optional[str] = None,
  20. ) -> str:
  21. r"""Parses the schema of a given function with type hints. The schema is inferred from the
  22. function's type hints, and can be used to define a new operator.
  23. We make the following assumptions:
  24. * None of the outputs alias any of the inputs or each other.
  25. * | String type annotations "device, dtype, Tensor, types" without library specification are
  26. | assumed to be torch.*. Similarly, string type annotations "Optional, List, Sequence, Union"
  27. | without library specification are assumed to be typing.*.
  28. * | Only the args listed in ``mutates_args`` are being mutated. If ``mutates_args`` is "unknown",
  29. | it assumes that all inputs to the operator are being mutates.
  30. Callers (e.g. the custom ops API) are responsible for checking these assumptions.
  31. Args:
  32. prototype_function: The function from which to infer a schema for from its type annotations.
  33. op_name (Optional[str]): The name of the operator in the schema. If ``name`` is None, then the
  34. name is not included in the inferred schema. Note that the input schema to
  35. ``torch.library.Library.define`` requires a operator name.
  36. mutates_args ("unknown" | Iterable[str]): The arguments that are mutated in the function.
  37. Returns:
  38. The inferred schema.
  39. Example:
  40. >>> def foo_impl(x: torch.Tensor) -> torch.Tensor:
  41. >>> return x.sin()
  42. >>>
  43. >>> infer_schema(foo_impl, op_name="foo", mutates_args={})
  44. foo(Tensor x) -> Tensor
  45. >>>
  46. >>> infer_schema(foo_impl, mutates_args={})
  47. (Tensor x) -> Tensor
  48. """
  49. UNKNOWN_MUTATES = "unknown"
  50. pf_globals = prototype_function.__globals__
  51. pf_locals = None
  52. # TODO: Once our minimum version is py3.10+ pass `eval_str=True` to
  53. # inspect.signature() and we no longer need to deal with stringified
  54. # annotations below.
  55. sig = inspect.signature(prototype_function)
  56. def error_fn(what):
  57. raise ValueError(f"infer_schema(func): {what} Got func with signature {sig})")
  58. def convert_type_string(annotation_type: str):
  59. try:
  60. return eval(annotation_type, pf_globals, pf_locals)
  61. except Exception:
  62. error_fn(
  63. f"Unsupported type annotation {annotation_type}. It is not a type."
  64. )
  65. def unstringify_types(
  66. tys: tuple[Union[type[object], str], ...],
  67. ) -> tuple[tuple[typing.Any, ...], bool]:
  68. res = []
  69. changed = False
  70. for ty in tys:
  71. ty, ty_changed = unstringify_type(ty)
  72. res.append(ty)
  73. changed |= ty_changed
  74. if changed:
  75. return tuple(res), True
  76. else:
  77. return tys, False # type: ignore[return-value]
  78. def unstringify_type(ty: Union[type[object], str]) -> tuple[typing.Any, bool]:
  79. # Dig through a generic type and if it contains a stringified type
  80. # convert that to a real type. The second return value indicates if the
  81. # type contained a string or not.
  82. if isinstance(ty, str):
  83. return convert_type_string(ty), True
  84. elif origin := typing.get_origin(ty):
  85. args, args_changed = unstringify_types(typing.get_args(ty))
  86. if args_changed:
  87. return GenericAlias(origin, args), True
  88. return ty, False
  89. params = []
  90. seen_args = set()
  91. saw_kwarg_only_arg = False
  92. for idx, (name, param) in enumerate(sig.parameters.items()):
  93. if not supported_param(param):
  94. error_fn("We do not support positional-only args, varargs, or varkwargs.")
  95. if param.kind == inspect.Parameter.KEYWORD_ONLY:
  96. # The first time we see a kwarg-only arg, add "*" to the schema.
  97. if not saw_kwarg_only_arg:
  98. params.append("*")
  99. saw_kwarg_only_arg = True
  100. if param.annotation is inspect.Parameter.empty:
  101. error_fn(f"Parameter {name} must have a type annotation.")
  102. # The annotation might be converted to a string by annotation,
  103. # we convert it to the actual type.
  104. annotation_type, _ = unstringify_type(param.annotation)
  105. if annotation_type not in SUPPORTED_PARAM_TYPES:
  106. if annotation_type.__origin__ is tuple:
  107. list_type = tuple_to_list(annotation_type)
  108. example_type_str = "\n\n"
  109. # Only suggest the list type if this type is supported.
  110. if list_type in SUPPORTED_PARAM_TYPES.keys():
  111. example_type_str = f"For example, {list_type}.\n\n"
  112. error_fn(
  113. f"Parameter {name} has unsupported type {param.annotation}. "
  114. f"We do not support Tuple inputs in schema. As a workaround, please try to use List instead. "
  115. f"{example_type_str}"
  116. f"The valid types are: {SUPPORTED_PARAM_TYPES.keys()}."
  117. )
  118. else:
  119. error_fn(
  120. f"Parameter {name} has unsupported type {param.annotation}. "
  121. f"The valid types are: {SUPPORTED_PARAM_TYPES.keys()}."
  122. )
  123. schema_type = SUPPORTED_PARAM_TYPES[annotation_type]
  124. if type(mutates_args) == str:
  125. if mutates_args != UNKNOWN_MUTATES:
  126. raise ValueError(
  127. "mutates_args must either be a sequence of the names of "
  128. "the arguments that are mutated or the string 'unknown'. "
  129. )
  130. if schema_type.startswith("Tensor"):
  131. schema_type = f"Tensor(a{idx}!){schema_type[len('Tensor') :]}"
  132. elif name in mutates_args:
  133. if not schema_type.startswith("Tensor"):
  134. error_fn(
  135. f"Parameter {name} is in mutable_args but only Tensors or collections of Tensors can be mutated"
  136. )
  137. schema_type = f"Tensor(a{idx}!){schema_type[len('Tensor') :]}"
  138. seen_args.add(name)
  139. if param.default is inspect.Parameter.empty:
  140. params.append(f"{schema_type} {name}")
  141. else:
  142. default_repr = None
  143. if param.default is None or isinstance(param.default, (int, float, bool)):
  144. default_repr = str(param.default)
  145. elif isinstance(param.default, (str, torch.device)):
  146. default_repr = f'"{param.default}"'
  147. elif isinstance(param.default, torch.dtype):
  148. dtype_repr = str(param.default)
  149. torch_dot = "torch."
  150. assert dtype_repr.startswith(torch_dot)
  151. default_repr = dtype_repr[len(torch_dot) :]
  152. else:
  153. error_fn(
  154. f"Parameter {name} has an unsupported default value type {type(param.default)}. "
  155. f"Please file an issue on GitHub so we can prioritize this."
  156. )
  157. params.append(f"{schema_type} {name}={default_repr}")
  158. if mutates_args != UNKNOWN_MUTATES:
  159. mutates_args_not_seen = set(mutates_args) - seen_args
  160. if len(mutates_args_not_seen) > 0:
  161. error_fn(
  162. f"{mutates_args_not_seen} in mutates_args were not found in "
  163. f"the custom op's signature. "
  164. f"mutates_args should contain the names of all args that the "
  165. f"custom op mutates, or just the string 'unknown' if you don't know."
  166. )
  167. return_annotation, _ = unstringify_type(sig.return_annotation)
  168. ret = parse_return(return_annotation, error_fn)
  169. if op_name is not None:
  170. return f"{op_name}({', '.join(params)}) -> {ret}"
  171. return f"({', '.join(params)}) -> {ret}"
  172. def derived_types(
  173. base_type: Union[type, typing._SpecialForm],
  174. cpp_type: str,
  175. list_base: bool,
  176. optional_base_list: bool,
  177. optional_list_base: bool,
  178. ):
  179. result: list[tuple[Union[type, typing._SpecialForm, GenericAlias], str]] = [
  180. (base_type, cpp_type),
  181. (typing.Optional[base_type], f"{cpp_type}?"),
  182. ]
  183. def derived_seq_types(typ: Union[type, typing._SpecialForm]):
  184. return (
  185. typing.Sequence[typ], # type: ignore[valid-type] # noqa: UP006
  186. typing.List[typ], # type: ignore[valid-type] # noqa: UP006
  187. GenericAlias(collections.abc.Sequence, (typ,)),
  188. GenericAlias(list, (typ,)),
  189. )
  190. if list_base:
  191. result.extend(
  192. (seq_typ, f"{cpp_type}[]") for seq_typ in derived_seq_types(base_type)
  193. )
  194. if optional_base_list:
  195. result.extend(
  196. (seq_typ, f"{cpp_type}?[]")
  197. for seq_typ in derived_seq_types(typing.Optional[base_type])
  198. )
  199. if optional_list_base:
  200. result.extend(
  201. (typing.Optional[seq_typ], f"{cpp_type}[]?")
  202. for seq_typ in derived_seq_types(base_type)
  203. )
  204. return result
  205. def get_supported_param_types():
  206. data: list[tuple[Union[type, typing._SpecialForm], str, bool, bool, bool]] = [
  207. # (python type, schema type, type[] variant, type?[] variant, type[]? variant
  208. (Tensor, "Tensor", True, True, False),
  209. (int, "SymInt", True, False, True),
  210. (float, "float", True, False, True),
  211. (bool, "bool", True, False, True),
  212. (str, "str", False, False, False),
  213. (types.Number, "Scalar", True, False, False),
  214. (dtype, "ScalarType", False, False, False),
  215. (device, "Device", False, False, False),
  216. ]
  217. result = []
  218. for line in data:
  219. result.extend(derived_types(*line))
  220. return dict(result)
  221. SUPPORTED_RETURN_TYPES = {
  222. Tensor: "Tensor",
  223. typing.List[Tensor]: "Tensor[]", # noqa: UP006
  224. list[Tensor]: "Tensor[]",
  225. int: "SymInt",
  226. float: "float",
  227. bool: "bool",
  228. types.Number: "Scalar",
  229. }
  230. def parse_return(annotation, error_fn):
  231. if annotation is None:
  232. return "()"
  233. if annotation is inspect.Parameter.empty:
  234. error_fn("No return type annotation was provided. Please add one.")
  235. origin = typing.get_origin(annotation)
  236. if origin is not tuple:
  237. if annotation not in SUPPORTED_RETURN_TYPES.keys():
  238. error_fn(
  239. f"Return has unsupported type {annotation}. "
  240. f"The valid types are: {SUPPORTED_RETURN_TYPES}."
  241. )
  242. return SUPPORTED_RETURN_TYPES[annotation]
  243. args = typing.get_args(annotation)
  244. for arg in args:
  245. if arg not in SUPPORTED_RETURN_TYPES:
  246. error_fn(
  247. f"Return has unsupported type {annotation}. "
  248. f"The valid types are: {SUPPORTED_RETURN_TYPES}."
  249. )
  250. output_ty = ", ".join([SUPPORTED_RETURN_TYPES[arg] for arg in args])
  251. # use (()) to represent tuple with single element
  252. if len(args) == 1:
  253. output_ty = "(" + output_ty + ")"
  254. return "(" + output_ty + ")"
  255. SUPPORTED_PARAM_TYPES = get_supported_param_types()
  256. def supported_param(param: inspect.Parameter) -> bool:
  257. return param.kind in (
  258. inspect.Parameter.POSITIONAL_OR_KEYWORD,
  259. inspect.Parameter.KEYWORD_ONLY,
  260. )
  261. def tuple_to_list(tuple_type: type[tuple]) -> type[list]:
  262. """
  263. Convert `tuple_type` into a list type with the same type arguments. Assumes that `tuple_type` is typing.Tuple type.
  264. """
  265. type_args = getattr(tuple_type, "__args__", None)
  266. # Account for different python versions, e.g. python 3.8 would give ()
  267. # but python 3.12 would give None.
  268. if (
  269. tuple_type is typing.Tuple # noqa: UP006
  270. or tuple_type is tuple
  271. or type_args == ()
  272. or type_args is None
  273. ):
  274. # Handle the case of an empty tuple type
  275. return list
  276. elif len(type_args) == 1:
  277. # General case: create a List with the same type arguments
  278. return list[type_args[0]] # type: ignore[valid-type]
  279. elif len(type_args) == 2 and type_args[1] is Ellipsis:
  280. return list[type_args[0]] # type: ignore[valid-type]
  281. else:
  282. return list[typing.Union[tuple(type_args)]] # type: ignore[misc, return-value]