jit_utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. """Utilities for manipulating the torch.Graph object and the torchscript."""
  2. # TODO(justinchuby): Move more of the symbolic helper functions here and expose
  3. # them to the user.
  4. import dataclasses
  5. import re
  6. import typing
  7. from typing import Any, Dict, Iterable, Optional, Sequence, Tuple, Union
  8. import torch
  9. from torch import _C
  10. from torch._C import _onnx as _C_onnx
  11. from torch.onnx._globals import GLOBALS
  12. from torch.onnx._internal import _beartype, registration
  13. _ATTR_PATTERN = re.compile("^(.+)_(([ifstgz])|(ty))$")
  14. _SKIP_NODE_ATTRIBUTES = {"inplace", "aten"}
  15. @dataclasses.dataclass
  16. class GraphContext:
  17. """Extra context for symbolic functions with all methods from torch.Graph.
  18. NOTE: This class is not meant for external consumption. Please do not depend on
  19. it outside of torch.onnx as the interface may evolve.
  20. Attributes:
  21. graph: The _C.Graph being constructed.
  22. block: The current _C.Block being constructed.
  23. opset: The opset version.
  24. original_node: Current node that is being converted from.
  25. params_dict: Mapping from graph initializer name to IValue.
  26. env: Mapping from Torch domain graph Value to ONNX domain graph Value.
  27. """
  28. graph: _C.Graph
  29. block: _C.Block
  30. opset: int
  31. original_node: _C.Node
  32. params_dict: Dict[str, "_C.IValue"]
  33. env: Dict[_C.Value, _C.Value]
  34. # Relay methods from _C.Graph for compatibility with symbolic functions that expect
  35. # a _C.Graph
  36. def __getattr__(self, name: str) -> Any:
  37. return getattr(self.graph, name)
  38. @_beartype.beartype
  39. def op(
  40. self,
  41. opname: str,
  42. *raw_args: Union[torch.Tensor, _C.Value],
  43. outputs: int = 1,
  44. **kwargs,
  45. ):
  46. """Creates an ONNX operator "opname", taking "raw_args" as inputs and "kwargs" as attributes.
  47. The set of operators and the inputs/attributes they take
  48. is documented at https://github.com/onnx/onnx/blob/master/docs/Operators.md
  49. Args:
  50. opname: The ONNX operator name, e.g., `Abs` or `Add`, or an operator qualified
  51. with a namespace, e.g., `aten::add`.
  52. raw_args: The inputs to the operator; usually provided
  53. as arguments to the `symbolic` definition.
  54. outputs: The number of outputs this operator returns.
  55. By default an operator is assumed to return a single output.
  56. If `outputs` is greater than one, this functions returns a tuple
  57. of output `Value`, representing each output of the ONNX operator
  58. in order.
  59. kwargs: The attributes of the ONNX operator, whose keys are named
  60. according to the following convention: `alpha_f` indicates
  61. the `alpha` attribute with type `f`. The valid type specifiers are
  62. `f` (float), `i` (int), `s` (string) or `t` (Tensor). An attribute
  63. specified with type float accepts either a single float, or a
  64. list of floats (e.g., you would say `dims_i` for a `dims` attribute
  65. that takes a list of integers).
  66. Returns:
  67. The value representing the single output of this operator (see the `outputs`
  68. keyword argument for multi-return nodes).
  69. """
  70. # FIXME(justinchuby): Add the return type back once we know how to handle mypy
  71. return _add_op(self, opname, *raw_args, outputs=outputs, **kwargs)
  72. @_beartype.beartype
  73. def aten_op(self, operator: str, *args, overload_name: str = "", **kwargs):
  74. """Generates an ONNX ATen op node.
  75. This function is for backward compatibility with the old symbolic functions.
  76. """
  77. return self.op(
  78. "aten::ATen",
  79. *args,
  80. operator_s=operator,
  81. overload_name_s=overload_name,
  82. **kwargs,
  83. )
  84. # NOTE: For backward compatibility with the old symbolic functions.
  85. # We are probably going to remove this only after the fx exporter is established.
  86. at = aten_op
  87. @_beartype.beartype
  88. def onnxscript_op(
  89. self,
  90. onnx_fn, # TODO(titaiwang): annotate this when onnx-script becomes dependency
  91. *raw_args: Union[torch.Tensor, _C.Value],
  92. outputs: int = 1,
  93. **kwargs,
  94. ):
  95. """Creates an ONNX operator from onnx-script function, taking "raw_args" as inputs and "kwargs" as attributes.
  96. onnx-script repository: https://github.com/microsoft/onnx-script
  97. Args:
  98. onnx_fn: ONNXFunction from onnx-script; An example can be found at
  99. https://github.com/microsoft/onnx-script#example
  100. raw_args: The inputs to the operator; usually provided
  101. as arguments to the `symbolic` definition.
  102. outputs: The number of outputs this operator returns.
  103. By default an operator is assumed to return a single output.
  104. If `outputs` is greater than one, this functions returns a tuple
  105. of output `Value`, representing each output of the ONNX operator
  106. in order.
  107. kwargs: The attributes of the ONNX operator, whose keys are named
  108. according to the following convention: `alpha_f` indicates
  109. the `alpha` attribute with type `f`. The valid type specifiers are
  110. `f` (float), `i` (int), `s` (string) or `t` (Tensor). An attribute
  111. specified with type float accepts either a single float, or a
  112. list of floats (e.g., you would say `dims_i` for a `dims` attribute
  113. that takes a list of integers).
  114. Returns:
  115. The value representing the single output of this operator (see the `outputs`
  116. keyword argument for multi-return nodes).
  117. """
  118. # NOTE(titaiwang): This is using class attributes, and it needs to be updated
  119. # if onnx-script makes any change on these.
  120. symbolic_name = f"{onnx_fn.opset.domain}::{onnx_fn.opname}"
  121. opset_version = onnx_fn.opset.version
  122. registration.custom_onnx_symbolic(symbolic_name, opset_version)(onnx_fn)
  123. return _add_op(self, symbolic_name, *raw_args, outputs=outputs, **kwargs)
  124. @_beartype.beartype
  125. def add_op_with_blocks(
  126. graph_context: GraphContext,
  127. opname: str,
  128. *inputs: _C.Value,
  129. outputs: int = 1,
  130. n_blocks: int = 1,
  131. **attributes,
  132. ) -> Tuple[Any, Tuple[GraphContext, ...], _C.Node]:
  133. """Creates an ONNX operator "opname", taking inputs and attributes.
  134. Args:
  135. graph_context: The context for the current graph.
  136. opname: The ONNX operator name, e.g., `Abs` or `Add`, or an operator qualified
  137. with a namespace, e.g., `aten::add`.
  138. inputs: The inputs to the operator.
  139. outputs: The number of outputs this operator returns.
  140. By default an operator is assumed to return a single output.
  141. If `outputs` is greater than one, this functions returns a tuple
  142. of output `Value`, representing each output of the ONNX operator
  143. in order.
  144. n_blocks: The number of sub-blocks to create in the node.
  145. attributes: The attributes of the ONNX operator.
  146. Returns:
  147. A tuple of (output_values, new_contexts, node) where:
  148. output_values: ONe or more output value of this operator
  149. (see the `outputs` keyword argument for multi-return nodes).
  150. new_contexts: A tuple of new graph contexts for each sub-block.
  151. node: The node representing the operator.
  152. """
  153. output_values = graph_context.op(opname, *inputs, outputs=outputs, **attributes)
  154. if isinstance(output_values, Sequence):
  155. node = output_values[0].node()
  156. else:
  157. node = output_values.node()
  158. new_contexts = []
  159. for _ in range(n_blocks):
  160. new_block = node.addBlock()
  161. # Create shallow copy of the graph context and update the block
  162. new_context = dataclasses.replace(graph_context, block=new_block)
  163. new_contexts.append(new_context)
  164. return output_values, tuple(new_contexts), node
  165. @_beartype.beartype
  166. def _add_op(
  167. graph_context: GraphContext,
  168. opname: str,
  169. *args: Union[torch.Tensor, _C.Value],
  170. outputs: int = 1,
  171. **kwargs,
  172. ):
  173. """Creates an ONNX operator "opname", taking "args" as inputs and attributes "kwargs".
  174. The set of operators and the inputs/attributes they take
  175. is documented at https://github.com/onnx/onnx/blob/master/docs/Operators.md
  176. This function is monkey-patched onto Graph.
  177. Args:
  178. graph_context: The Torch Graph or Block.
  179. opname: The ONNX operator name, e.g., `Abs` or `Add`, or an operator qualified
  180. with a namespace, e.g., `aten::add`.
  181. args: The inputs to the operator; usually provided
  182. as arguments to the `symbolic` definition.
  183. outputs: The number of outputs this operator returns.
  184. By default an operator is assumed to return a single output.
  185. If `outputs` is greater than one, this functions returns a tuple
  186. of output `Value`, representing each output of the ONNX operator
  187. in order.
  188. kwargs: The attributes of the ONNX operator, whose keys are named
  189. according to the following convention: `alpha_f` indicates
  190. the `alpha` attribute with type `f`. The valid type specifiers are
  191. `f` (float), `i` (int), `s` (string) or `t` (Tensor). An attribute
  192. specified with type float accepts either a single float, or a
  193. list of floats (e.g., you would say `dims_i` for a `dims` attribute
  194. that takes a list of integers).
  195. Returns:
  196. (Union[_C.Value, Tuple[_C.Value, ...]])
  197. The value representing the single output of this operator (see the `outputs`
  198. keyword argument for multi-return nodes).
  199. """
  200. inputs = [_const_if_tensor(graph_context, arg) for arg in args]
  201. # Filter out None attributes, this can be convenient client side because
  202. # now they can pass through None attributes, and have them not show up
  203. attributes = {k: v for k, v in kwargs.items() if v is not None}
  204. if "::" not in opname:
  205. opname = "onnx::" + opname
  206. node = _create_node(
  207. graph_context.block,
  208. opname,
  209. inputs,
  210. attributes,
  211. params_dict=graph_context.params_dict,
  212. opset_version=graph_context.opset,
  213. n_outputs=outputs,
  214. shape_inference=GLOBALS.onnx_shape_inference,
  215. )
  216. if outputs == 1:
  217. return node.output()
  218. return tuple(node.outputs())
  219. @_beartype.beartype
  220. def _const_if_tensor(graph_context: GraphContext, arg):
  221. if arg is None:
  222. return arg
  223. if isinstance(arg, _C.Value):
  224. return arg
  225. return _add_op(graph_context, "onnx::Constant", value_z=arg)
  226. def _create_node(
  227. graph_or_block: Union[_C.Graph, _C.Block],
  228. domain_op: str,
  229. inputs: Sequence,
  230. attributes: dict,
  231. params_dict: dict,
  232. opset_version: int,
  233. n_outputs: int,
  234. shape_inference: bool = True,
  235. ) -> _C.Node:
  236. """Creates an node 'domain_op', taking inputs and attributes."""
  237. if isinstance(graph_or_block, _C.Graph):
  238. graph = graph_or_block
  239. node = graph.create(domain_op, inputs, n_outputs)
  240. node = graph.insertNode(node)
  241. elif isinstance(graph_or_block, _C.Block):
  242. block = graph_or_block
  243. node = block.addNode(domain_op, inputs)
  244. # Block does not have create defined, so we need to add outputs manually
  245. if n_outputs > 1:
  246. for _ in range(1, n_outputs):
  247. node.addOutput()
  248. node_ouputs = tuple(node.outputs())
  249. assert len(node_ouputs) == n_outputs
  250. aten = domain_op.startswith("aten::")
  251. # Add all attributes
  252. for key, value in sorted(attributes.items()):
  253. if key in _SKIP_NODE_ATTRIBUTES:
  254. continue
  255. _add_attribute(node, key, value, aten=aten)
  256. if shape_inference:
  257. _C._jit_pass_onnx_node_shape_type_inference(node, params_dict, opset_version)
  258. return node
  259. @_beartype.beartype
  260. def _is_onnx_list(value):
  261. return (
  262. not isinstance(value, str)
  263. and not isinstance(value, torch.Tensor)
  264. and isinstance(value, Iterable)
  265. )
  266. @_beartype.beartype
  267. def _scalar(x: torch.Tensor):
  268. """Convert a scalar tensor into a Python value."""
  269. assert x.numel() == 1
  270. return x[0]
  271. @_beartype.beartype
  272. def _is_caffe2_aten_fallback() -> bool:
  273. return (
  274. GLOBALS.operator_export_type == _C_onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK
  275. and _C_onnx._CAFFE2_ATEN_FALLBACK
  276. )
  277. @_beartype.beartype
  278. def _add_attribute(node: _C.Node, key: str, value: Any, aten: bool):
  279. r"""Initializes the right attribute based on type of value."""
  280. m = _ATTR_PATTERN.match(key)
  281. if m is None:
  282. raise ValueError(
  283. f"Invalid attribute specifier '{key}' names "
  284. "must be suffixed with type, e.g. 'dim_i' or 'dims_i'"
  285. )
  286. name, kind = m.group(1), m.group(2)
  287. if _is_onnx_list(value):
  288. kind += "s"
  289. if aten and _is_caffe2_aten_fallback():
  290. if isinstance(value, torch.Tensor):
  291. # Caffe2 proto does not support tensor attribute.
  292. if value.numel() > 1:
  293. raise ValueError("Should not pass tensor attribute")
  294. value = _scalar(value)
  295. if isinstance(value, float):
  296. kind = "f"
  297. else:
  298. kind = "i"
  299. return getattr(node, f"{kind}_")(name, value)
  300. # TODO: Expose this to user when migrating symbolic helper functions to here.
  301. @_beartype.beartype
  302. def _is_tensor(x: _C.Value) -> bool:
  303. return x.type().isSubtypeOf(_C.TensorType.get())
  304. @_beartype.beartype
  305. def get_device_from_value(value: _C.Value) -> Optional[torch.device]:
  306. if not _is_tensor(value):
  307. return None
  308. tensor_type = typing.cast(_C.TensorType, value.type())
  309. return tensor_type.device()
  310. @_beartype.beartype
  311. def parse_node_kind(kind: str) -> Tuple[str, str]:
  312. """Parse node kind into domain and Op name."""
  313. if "::" not in kind:
  314. raise ValueError(f"Node kind: {kind} is invalid. '::' is not in node kind.")
  315. domain, opname = kind.split("::", 1)
  316. if "::" in opname:
  317. raise ValueError(f"Node kind: {kind} is invalid. '::' should only apear once.")
  318. return domain, opname
  319. @_beartype.beartype
  320. def is_aten(domain: str) -> bool:
  321. """Check if the domain is official."""
  322. return domain == "aten"
  323. @_beartype.beartype
  324. def is_prim(domain: str) -> bool:
  325. """Check if the domain is official."""
  326. return domain == "prim"
  327. @_beartype.beartype
  328. def is_onnx(domain: str) -> bool:
  329. """Check if the domain is official."""
  330. return domain == "onnx"