node.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. # Nodes represent a definition of a value in our graph of operators.
  2. import builtins
  3. import inspect
  4. import logging
  5. import operator
  6. import types
  7. from collections.abc import Iterable, Mapping, Sequence
  8. from typing import Any, Callable, Optional, TYPE_CHECKING, Union
  9. from typing_extensions import ParamSpec, TypeAlias, TypeVar
  10. import torch
  11. from torch._C import _fx_map_aggregate, _fx_map_arg, _NodeBase
  12. from torch.fx.operator_schemas import (
  13. ArgsKwargsPair,
  14. normalize_function,
  15. normalize_module,
  16. )
  17. from torch.utils._dtype_abbrs import dtype_abbrs
  18. from .._ops import ops as _ops
  19. from ._compatibility import compatibility
  20. if TYPE_CHECKING:
  21. from .graph import Graph
  22. __all__ = ["Node", "map_arg", "map_aggregate", "has_side_effect"]
  23. log = logging.getLogger(__name__)
  24. BaseArgumentTypes = Union[
  25. str,
  26. int,
  27. float,
  28. bool,
  29. complex,
  30. torch.dtype,
  31. torch.Tensor,
  32. torch.device,
  33. torch.memory_format,
  34. torch.layout,
  35. torch._ops.OpOverload,
  36. torch.SymInt,
  37. torch.SymBool,
  38. torch.SymFloat,
  39. ]
  40. base_types = BaseArgumentTypes.__args__ # type: ignore[attr-defined]
  41. Target: TypeAlias = Union[Callable[..., Any], str]
  42. Argument = Optional[
  43. Union[
  44. tuple["Argument", ...],
  45. Sequence["Argument"],
  46. Mapping[str, "Argument"],
  47. slice, # Slice[Argument, Argument, Argument], but slice is not a templated type in typing
  48. range,
  49. "Node",
  50. BaseArgumentTypes,
  51. ]
  52. ]
  53. ArgumentT = TypeVar("ArgumentT", bound=Argument)
  54. _P = ParamSpec("_P")
  55. _R = TypeVar("_R")
  56. _legal_ops = dict.fromkeys(
  57. [
  58. "placeholder",
  59. "call_method",
  60. "call_module",
  61. "call_function",
  62. "get_attr",
  63. "output",
  64. "root",
  65. ]
  66. )
  67. # Dynamo is unable to trace global set[Callable].__contains__.
  68. # See https://github.com/pytorch/pytorch/issues/145761. Since we only have
  69. # a handful of ops so switch to list of callables.
  70. _side_effectful_need_to_be_preserved_pre_dispatch: list[Callable[..., Any]] = [
  71. torch._C._set_grad_enabled,
  72. torch.amp._enter_autocast,
  73. torch.amp._exit_autocast,
  74. ]
  75. # TODO: Either refactor this into 2 functions 1 dce for functional graphs and 1 dce for all graphs,
  76. # or add logic to correctly mark all inplace ops as side effectful.
  77. _side_effectful_functions: set[Callable[..., Any]] = {
  78. torch._assert,
  79. torch._assert_async,
  80. _ops.aten._assert_async.msg,
  81. _ops.aten._assert_scalar.default,
  82. _ops.aten._assert_tensor_metadata.default,
  83. _ops.aten.sym_constrain_range.default,
  84. _ops.aten.sym_constrain_range_for_size.default,
  85. _ops.profiler._record_function_enter,
  86. _ops.profiler._record_function_enter_new,
  87. _ops.profiler._record_function_exit,
  88. _ops.inductor.accumulate_grad_.default,
  89. operator.setitem,
  90. *_side_effectful_need_to_be_preserved_pre_dispatch,
  91. }
  92. if hasattr(_ops.inductor, "resize_storage_bytes_"):
  93. _side_effectful_functions.add(_ops.inductor.resize_storage_bytes_.default)
  94. @compatibility(is_backward_compatible=False)
  95. def has_side_effect(fn: Callable[_P, _R]) -> Callable[_P, _R]:
  96. _side_effectful_functions.add(fn)
  97. return fn
  98. # this is fixed on master, WAR for 1.5
  99. def _find_module_of_method(orig_method: Callable[..., Any]) -> str:
  100. name = orig_method.__name__
  101. module = orig_method.__module__
  102. if module is not None:
  103. return module
  104. for guess in [torch, torch.nn.functional]:
  105. if getattr(guess, name, None) is orig_method:
  106. return guess.__name__
  107. raise RuntimeError(f"cannot find module for {orig_method}")
  108. # Borrowed from CPython typing module
  109. # https://github.com/python/cpython/blob/f90dc36c15d7fee0efaf6d39e97be0bdf2683e93/Lib/typing.py#L156
  110. def _type_repr(obj: object) -> str:
  111. """Return the repr() of an object, special-casing types (internal helper).
  112. If obj is a type, we return a shorter version than the default
  113. type.__repr__, based on the module and qualified name, which is
  114. typically enough to uniquely identify a type. For everything
  115. else, we fall back on repr(obj).
  116. """
  117. # Extension: If we don't ignore GenericAlias then `list[int]` will print
  118. # simply "list".
  119. if isinstance(obj, type) and not isinstance(obj, types.GenericAlias):
  120. if obj.__module__ == "builtins":
  121. return obj.__qualname__
  122. return f"{obj.__module__}.{obj.__qualname__}"
  123. if obj is ...:
  124. return "..."
  125. if isinstance(obj, types.FunctionType):
  126. return obj.__name__
  127. return repr(obj)
  128. def _get_qualified_name(func: Callable[..., Any]) -> str:
  129. # things like getattr just appear in builtins
  130. if getattr(builtins, func.__name__, None) is func:
  131. return func.__name__
  132. # torch.Tensor.{fn}
  133. if (
  134. isinstance(func, (types.MethodDescriptorType, types.WrapperDescriptorType))
  135. and func is getattr(torch.Tensor, func.__name__, None)
  136. ) or (
  137. func.__module__ == torch._tensor.__name__
  138. and func.__qualname__ == f"Tensor.{func.__name__}"
  139. ):
  140. return f"torch.Tensor.{func.__name__}"
  141. name = func.__name__
  142. if name == "<lambda>":
  143. # For lambdas, try to get their defining name in the module
  144. try:
  145. name = inspect.getsource(func).split("=")[0].strip()
  146. except Exception as e:
  147. raise RuntimeError("Unable to represent lambda") from e
  148. module = _find_module_of_method(func)
  149. module = module.replace(
  150. "torch._ops", "torch.ops"
  151. ) # WAR for bug in how torch.ops assigns module
  152. # Fixup segment_reduce mismatch
  153. if module == "torch" and name == "segment_reduce":
  154. name = "_" + name
  155. return f"{module}.{name}"
  156. def _format_arg(arg: object, max_list_len: float = float("inf")) -> str:
  157. if hasattr(arg, "_custom_fx_repr_fn"):
  158. return arg._custom_fx_repr_fn()
  159. elif isinstance(arg, list):
  160. items = ", ".join(
  161. _format_arg(a) for idx, a in enumerate(arg) if idx < max_list_len
  162. )
  163. maybe_len = (
  164. "" if len(arg) < max_list_len + 1 else f", ...[total_len={len(arg)}]"
  165. )
  166. return f"[{items}{maybe_len}]"
  167. elif isinstance(arg, tuple):
  168. items = ", ".join(
  169. _format_arg(a) for idx, a in enumerate(arg) if idx < max_list_len
  170. )
  171. maybe_len = (
  172. "" if len(arg) < max_list_len + 1 else f", ...[total_len={len(arg)}]"
  173. )
  174. maybe_comma = "," if len(arg) == 1 else ""
  175. return f"({items}{maybe_comma}{maybe_len})"
  176. elif isinstance(arg, dict):
  177. items_str = ", ".join(f"{k}: {_format_arg(v)}" for k, v in arg.items())
  178. return f"{{{items_str}}}"
  179. if isinstance(arg, Node):
  180. return "%" + str(arg)
  181. else:
  182. return str(arg)
  183. @compatibility(is_backward_compatible=True)
  184. class Node(_NodeBase):
  185. """
  186. ``Node`` is the data structure that represents individual operations within
  187. a ``Graph``. For the most part, Nodes represent callsites to various entities,
  188. such as operators, methods, and Modules (some exceptions include nodes that
  189. specify function inputs and outputs). Each ``Node`` has a function specified
  190. by its ``op`` property. The ``Node`` semantics for each value of ``op`` are as follows:
  191. - ``placeholder`` represents a function input. The ``name`` attribute specifies the name this value will take on.
  192. ``target`` is similarly the name of the argument. ``args`` holds either: 1) nothing, or 2) a single argument
  193. denoting the default parameter of the function input. ``kwargs`` is don't-care. Placeholders correspond to
  194. the function parameters (e.g. ``x``) in the graph printout.
  195. - ``get_attr`` retrieves a parameter from the module hierarchy. ``name`` is similarly the name the result of the
  196. fetch is assigned to. ``target`` is the fully-qualified name of the parameter's position in the module hierarchy.
  197. ``args`` and ``kwargs`` are don't-care
  198. - ``call_function`` applies a free function to some values. ``name`` is similarly the name of the value to assign
  199. to. ``target`` is the function to be applied. ``args`` and ``kwargs`` represent the arguments to the function,
  200. following the Python calling convention
  201. - ``call_module`` applies a module in the module hierarchy's ``forward()`` method to given arguments. ``name`` is
  202. as previous. ``target`` is the fully-qualified name of the module in the module hierarchy to call.
  203. ``args`` and ``kwargs`` represent the arguments to invoke the module on, *excluding the self argument*.
  204. - ``call_method`` calls a method on a value. ``name`` is as similar. ``target`` is the string name of the method
  205. to apply to the ``self`` argument. ``args`` and ``kwargs`` represent the arguments to invoke the module on,
  206. *including the self argument*
  207. - ``output`` contains the output of the traced function in its ``args[0]`` attribute. This corresponds to the "return" statement
  208. in the Graph printout.
  209. """
  210. _args: tuple["Argument", ...]
  211. _kwargs: dict[str, "Argument"]
  212. graph: "Graph"
  213. # unique name of value being created
  214. name: str
  215. # the kind of operation = placeholder|call_method|call_module|call_function|get_attr
  216. op: str
  217. # for method/module/function, the name of the method/module/function/attr
  218. # being invoked, e.g add, layer1, or torch.add
  219. target: "Target"
  220. # All `Node`-valued inputs. Key is the Node, value is don't-care.
  221. # The public API for this is `all_input_nodes`, this private attribute
  222. # should not be accessed directly.
  223. _input_nodes: dict["Node", None]
  224. # All of the nodes that use the value produced by this Node
  225. # Note one user may correspond to several uses, e.g. the node for ``x + x``
  226. # would appear once here, but represents two uses.
  227. # Is a dict to act as an "ordered set". Keys are significant, value dont-care
  228. users: dict["Node", None]
  229. # Type expression representing the output value of this node.
  230. # This should contain the same class of Type objects that would appear
  231. # as type annotations for function inputs/outputs.
  232. #
  233. # For placeholder nodes, this value will be used to type-annotate the
  234. # generated function parameters.
  235. # For the return node, this value will be used to type-annotate the
  236. # generated function return type. (Note this is a special case. ``return``
  237. # does not produce a value, it's more of a notation. Thus, this value
  238. # describes the type of args[0] in the ``return`` node.
  239. type: Optional[Any]
  240. _sort_key: Any
  241. # If set, use this fn to print this node
  242. _repr_fn: Optional[Callable[["Node"], str]]
  243. # Dictionary to store metadata passes need to do their
  244. # transformations. This metadata is preserved across node copies
  245. meta: dict[str, Any]
  246. @compatibility(is_backward_compatible=True)
  247. def __init__(
  248. self,
  249. graph: "Graph",
  250. name: str,
  251. op: str,
  252. target: "Target",
  253. args: tuple["Argument", ...],
  254. kwargs: dict[str, "Argument"],
  255. return_type: Optional[Any] = None,
  256. ) -> None:
  257. """
  258. Instantiate an instance of ``Node``. Note: most often, you want to use the
  259. Graph APIs, i.e. ``Graph.call_module``, ``Graph.call_method``, etc. rather
  260. than instantiating a ``Node`` directly.
  261. Args:
  262. graph (Graph): The ``Graph`` to which this ``Node`` should belong.
  263. name (str): The name to which the output of this ``Node`` should be assigned
  264. op (str): The opcode for this ``Node``. Can be one of 'placeholder',
  265. 'call_method', 'call_module', 'call_function', 'get_attr',
  266. 'output'
  267. target ('Target'): The target this op should call. See the broader
  268. ``Node`` docstring for more details.
  269. args (Tuple['Argument']): The args to be passed to ``target``
  270. kwargs (Dict[str, 'Argument']): The kwargs to be passed to ``target``
  271. return_type (Optional[Any]): The python type expression representing the
  272. type of the output of this node. This field can be used for
  273. annotation of values in the generated code or for other types
  274. of analyses.
  275. """
  276. if op == "call_function":
  277. if not callable(target):
  278. raise ValueError(
  279. f"Node [graph = {graph}, name = '{name}'] target {target} has type {torch.typename(target)} "
  280. "but a Callable is expected"
  281. )
  282. else:
  283. assert op in _legal_ops
  284. if not isinstance(target, str):
  285. raise ValueError(
  286. f"Node [graph = {graph}, name = '{name}'] target {target} has type {torch.typename(target)} "
  287. "but a str is expected"
  288. )
  289. super().__init__(graph, name, op, target, return_type)
  290. self._update_args_kwargs(args, kwargs)
  291. def __getstate__(self) -> dict[str, Any]:
  292. return {
  293. **self.__dict__,
  294. "graph": self.graph,
  295. "name": self.name,
  296. "op": self.op,
  297. "target": self.target,
  298. "type": self.target,
  299. "_sort_key": self._sort_key,
  300. "_args": self._args,
  301. "_kwargs": self._kwargs,
  302. "_erased": self._erased,
  303. "_prev": self._prev,
  304. "_next": self._next,
  305. "_input_nodes": self._input_nodes,
  306. "users": self.users,
  307. "_repr_fn": self._repr_fn,
  308. "meta": self.meta,
  309. }
  310. def __setstate__(self, state: dict[str, Any]) -> None:
  311. for k, v in state.items():
  312. setattr(self, k, v)
  313. @property
  314. def next(self) -> "Node":
  315. """
  316. Returns the next ``Node`` in the linked list of Nodes.
  317. Returns:
  318. The next ``Node`` in the linked list of Nodes.
  319. """
  320. return self._next
  321. @property
  322. def prev(self) -> "Node":
  323. """
  324. Returns the previous ``Node`` in the linked list of Nodes.
  325. Returns:
  326. The previous ``Node`` in the linked list of Nodes.
  327. """
  328. return self._prev
  329. @compatibility(is_backward_compatible=True)
  330. def prepend(self, x: "Node") -> None:
  331. """
  332. Insert x before this node in the list of nodes in the graph. Example::
  333. Before: p -> self
  334. bx -> x -> ax
  335. After: p -> x -> self
  336. bx -> ax
  337. Args:
  338. x (Node): The node to put before this node. Must be a member of the same graph.
  339. """
  340. assert self.graph == x.graph, "Attempting to move a Node into a different Graph"
  341. if self == x:
  342. log.debug(
  343. "Trying to prepend a node to itself. This behavior has no effect on the graph."
  344. )
  345. return
  346. x._remove_from_list()
  347. p = self._prev
  348. p._next, x._prev = x, p
  349. x._next, self._prev = self, x
  350. # compute x._sort_key
  351. psk = x._prev._sort_key
  352. nsk = x._next._sort_key
  353. if len(psk) > len(nsk):
  354. idx: int
  355. *prefix, idx = psk[: len(nsk) + 1]
  356. x._sort_key = (*prefix, idx + 1)
  357. elif len(psk) < len(nsk):
  358. *prefix, idx = nsk[: len(psk) + 1]
  359. x._sort_key = (*prefix, idx - 1)
  360. else: # same length, increase length by 1
  361. x._sort_key = (*psk, 0)
  362. def __gt__(self, other: "Node") -> bool:
  363. return self._sort_key > other._sort_key
  364. def __lt__(self, other: "Node") -> bool:
  365. return self._sort_key < other._sort_key
  366. def __ge__(self, other: "Node") -> bool:
  367. return self > other or self == other
  368. def __le__(self, other: "Node") -> bool:
  369. return self < other or self == other
  370. @compatibility(is_backward_compatible=True)
  371. def append(self, x: "Node") -> None:
  372. """
  373. Insert ``x`` after this node in the list of nodes in the graph.
  374. Equivalent to ``self.next.prepend(x)``
  375. Args:
  376. x (Node): The node to put after this node. Must be a member of the same graph.
  377. """
  378. self._next.prepend(x)
  379. def _remove_from_list(self) -> None:
  380. p, n = self._prev, self._next
  381. p._next, n._prev = n, p
  382. @property
  383. def args(self) -> tuple[Argument, ...]:
  384. """
  385. The tuple of arguments to this ``Node``. The interpretation of arguments
  386. depends on the node's opcode. See the :class:`Node` docstring for more
  387. information.
  388. Assignment to this property is allowed. All accounting of uses and users
  389. is updated automatically on assignment.
  390. """
  391. return self._args
  392. @args.setter
  393. def args(self, a: tuple[Argument, ...]) -> None:
  394. """
  395. Set the tuple of arguments to this Node. The interpretation of arguments
  396. depends on the node's opcode. See the ``fx.Graph`` docstring for more
  397. information.
  398. """
  399. # DO NOT CALL `_update_args_kwargs` directly. The correct way to
  400. # set `args` is via direct assignment, i.e. `node.args = new_args`
  401. self._update_args_kwargs(a, self._kwargs)
  402. @property
  403. def kwargs(self) -> dict[str, Argument]:
  404. """
  405. The dict of keyword arguments to this ``Node``. The interpretation of arguments
  406. depends on the node's opcode. See the :class:`Node` docstring for more
  407. information.
  408. Assignment to this property is allowed. All accounting of uses and users
  409. is updated automatically on assignment.
  410. """
  411. return self._kwargs
  412. @kwargs.setter
  413. def kwargs(self, k: dict[str, Argument]) -> None:
  414. """
  415. Set the dict of kwargs to this Node. The interpretation of arguments
  416. depends on the node's opcode. See the ``fx.Graph`` docstring for more
  417. information.
  418. """
  419. # DO NOT CALL `_update_args_kwargs` directly. The correct way to
  420. # set `args` is via direct assignment, i.e. `node.kwargs = new_kwargs`
  421. self._update_args_kwargs(self._args, k)
  422. @property
  423. def all_input_nodes(self) -> list["Node"]:
  424. """
  425. Return all Nodes that are inputs to this Node. This is equivalent to
  426. iterating over ``args`` and ``kwargs`` and only collecting the values that
  427. are Nodes.
  428. Returns:
  429. List of ``Nodes`` that appear in the ``args`` and ``kwargs`` of this
  430. ``Node``, in that order.
  431. """
  432. return list(self._input_nodes.keys())
  433. @compatibility(is_backward_compatible=True)
  434. def update_arg(self, idx: int, arg: Argument) -> None:
  435. """
  436. Update an existing positional argument to contain the new value
  437. ``arg``. After calling, ``self.args[idx] == arg``.
  438. Args:
  439. idx (int): The index into ``self.args`` of the element to update
  440. arg (Argument): The new argument value to write into ``args``
  441. """
  442. args = list(self.args)
  443. args[idx] = arg
  444. self.args = tuple(args)
  445. @compatibility(is_backward_compatible=True)
  446. def insert_arg(self, idx: int, arg: Argument) -> None:
  447. """
  448. Insert an positional argument to the argument list with given index.
  449. Args:
  450. idx (int): The index of the element in ``self.args`` to be inserted before.
  451. arg (Argument): The new argument value to insert into ``args``
  452. """
  453. assert 0 <= idx <= len(self.args), (
  454. "insert_args index must be between 0 and len(self.args)"
  455. )
  456. args_left = self.args[:idx]
  457. args_right = self.args[idx:]
  458. self._args = args_left + (arg,) + args_right
  459. _new_input_nodes: dict[Node, None] = {}
  460. _fx_map_arg(arg, _new_input_nodes.setdefault)
  461. for new_use in _new_input_nodes.keys():
  462. if new_use not in self._input_nodes:
  463. self._input_nodes.setdefault(new_use)
  464. new_use.users.setdefault(self)
  465. @compatibility(is_backward_compatible=True)
  466. def update_kwarg(self, key: str, arg: Argument) -> None:
  467. """
  468. Update an existing keyword argument to contain the new value
  469. ``arg``. After calling, ``self.kwargs[key] == arg``.
  470. Args:
  471. key (str): The key in ``self.kwargs`` of the element to update
  472. arg (Argument): The new argument value to write into ``kwargs``
  473. """
  474. self.kwargs = {**self.kwargs, key: arg}
  475. @property
  476. def stack_trace(self) -> Optional[str]:
  477. """
  478. Return the Python stack trace that was recorded during tracing, if any.
  479. When traced with fx.Tracer, this property is usually populated by
  480. `Tracer.create_proxy`. To record stack traces during tracing for debug purposes,
  481. set `record_stack_traces = True` on the `Tracer` instance.
  482. When traced with dynamo, this property will be populated by default by
  483. `OutputGraph.create_proxy`.
  484. stack_trace would have the innermost frame at the end of the string.
  485. """
  486. return self.meta.get("stack_trace", None)
  487. @stack_trace.setter
  488. def stack_trace(self, trace: Optional[str]) -> None:
  489. self.meta["stack_trace"] = trace
  490. def __repr__(self) -> str:
  491. if self._repr_fn:
  492. return self._repr_fn(self)
  493. return self.name
  494. @staticmethod
  495. def _pretty_print_target(target: object) -> str:
  496. """
  497. Make target printouts more user-friendly.
  498. 1) builtins will be printed as `builtins.xyz`
  499. 2) operators will be printed as `operator.xyz`
  500. 3) other callables will be printed with qualified name, e.g. torch.add
  501. """
  502. if isinstance(target, str):
  503. return target
  504. if hasattr(target, "__module__"):
  505. name = getattr(target, "__name__", None)
  506. if name is None:
  507. # Just to be defensive, if we don't have `__name__`, get the
  508. # qualname. Not sure if this happens for any members of `operator`
  509. # or `builtins`. This fallback path is not as good, since e.g.
  510. # things in `operator` have `_operator` as their __module__.
  511. # TODO: THIS IS BROKEN: _get_qualified_name calls `__name__`
  512. return _get_qualified_name(target) # type: ignore[arg-type]
  513. if target.__module__ == "builtins":
  514. return f"builtins.{name}"
  515. elif target.__module__ == "_operator":
  516. return f"operator.{name}"
  517. return _get_qualified_name(target) # type: ignore[arg-type]
  518. @compatibility(is_backward_compatible=True)
  519. def format_node(
  520. self,
  521. placeholder_names: Optional[list[str]] = None,
  522. maybe_return_typename: Optional[list[str]] = None,
  523. *,
  524. include_tensor_metadata: bool = False,
  525. ) -> Optional[str]:
  526. """
  527. Return a descriptive string representation of ``self``.
  528. This method can be used with no arguments as a debugging
  529. utility.
  530. This function is also used internally in the ``__str__`` method
  531. of ``Graph``. Together, the strings in ``placeholder_names``
  532. and ``maybe_return_typename`` make up the signature of the
  533. autogenerated ``forward`` function in this Graph's surrounding
  534. GraphModule. ``placeholder_names`` and ``maybe_return_typename``
  535. should not be used otherwise.
  536. Args:
  537. placeholder_names: A list that will store formatted strings
  538. representing the placeholders in the generated
  539. ``forward`` function. Internal use only.
  540. maybe_return_typename: A single-element list that will store
  541. a formatted string representing the output of the
  542. generated ``forward`` function. Internal use only.
  543. include_tensor_metadata: Whether to include tensor metadata
  544. Returns:
  545. str: If 1) we're using ``format_node`` as an internal helper
  546. in the ``__str__`` method of ``Graph``, and 2) ``self``
  547. is a placeholder Node, return ``None``. Otherwise,
  548. return a descriptive string representation of the
  549. current Node.
  550. """
  551. if self.op == "placeholder":
  552. assert isinstance(self.target, str)
  553. arg_str = self.target
  554. arg_str += arg_str + f": {_type_repr(self.type)}" if self.type else ""
  555. if placeholder_names:
  556. placeholder_names.append(arg_str)
  557. return None
  558. maybe_typename = f"{_type_repr(self.type)} " if self.type else ""
  559. default_val = "(default=" + str(self.args[0]) + ")" if self.args else ""
  560. return f"%{self.name} : {maybe_typename}[num_users={len(self.users)}] = {self.op}[target={self.target}]{default_val}"
  561. elif self.op == "get_attr":
  562. maybe_typename = (
  563. f"{_type_repr(self.type)} " if self.type is not None else ""
  564. )
  565. return (
  566. f"%{self.name} : {maybe_typename}[num_users={len(self.users)}] = "
  567. f"{self.op}[target={self._pretty_print_target(self.target)}]"
  568. )
  569. elif self.op == "output":
  570. if self.type and maybe_return_typename:
  571. maybe_return_typename[0] = f" -> {_type_repr(self.type)}"
  572. return f"return {self.args[0]}"
  573. else:
  574. def stringify_shape(shape: Iterable) -> str:
  575. return f"[{', '.join([str(x) for x in shape])}]"
  576. meta_val = self.meta.get(
  577. "val",
  578. self.meta.get("tensor_meta", self.meta.get("example_value", None)),
  579. )
  580. type_annotation = ""
  581. if (
  582. include_tensor_metadata
  583. and isinstance(meta_val, torch.Tensor)
  584. and meta_val.layout
  585. not in (
  586. torch.sparse_csc,
  587. torch.sparse_csr,
  588. )
  589. ):
  590. stride_annotation = f"{stringify_shape(meta_val.stride())}"
  591. device_annotation = f"{meta_val.device}"
  592. type_annotation = (
  593. f'Tensor "{dtype_abbrs[meta_val.dtype]}{stringify_shape(meta_val.shape)}'
  594. f'{stride_annotation}{device_annotation}"'
  595. )
  596. else:
  597. type_annotation = (
  598. f"{_type_repr(self.type)} " if self.type is not None else ""
  599. )
  600. return (
  601. f"%{self.name} : {type_annotation}[num_users={len(self.users)}] = "
  602. f"{self.op}[target={self._pretty_print_target(self.target)}]("
  603. f"args = {_format_arg(self.args)}, kwargs = {_format_arg(self.kwargs)})"
  604. )
  605. @compatibility(is_backward_compatible=True)
  606. def replace_all_uses_with(
  607. self,
  608. replace_with: "Node",
  609. delete_user_cb: Callable[["Node"], bool] = lambda user: True,
  610. *,
  611. propagate_meta: bool = False,
  612. ) -> list["Node"]:
  613. """
  614. Replace all uses of ``self`` in the Graph with the Node ``replace_with``.
  615. Args:
  616. replace_with (Node): The node to replace all uses of ``self`` with.
  617. delete_user_cb (Callable): Callback that is called to determine
  618. whether a given user of the self node should be removed.
  619. propagate_meta (bool): Whether or not to copy all properties
  620. on the .meta field of the original node onto the replacement node.
  621. For safety, this is only valid to do if the replacement node
  622. doesn't already have an existing .meta field.
  623. Returns:
  624. The list of Nodes on which this change was made.
  625. """
  626. if propagate_meta:
  627. assert len(replace_with.meta) == 0, (
  628. "Called node.replace_all_uses_with(replace_with, propagate_meta=True), "
  629. "but replace_with already has .meta keys"
  630. )
  631. for k, v in self.meta.items():
  632. replace_with.meta[k] = v
  633. to_process = list(self.users)
  634. skipped = []
  635. m = self.graph.owning_module
  636. for use_node in to_process:
  637. if not delete_user_cb(use_node):
  638. skipped.append(use_node)
  639. continue
  640. def maybe_replace_node(n: Node) -> Node:
  641. if n == self:
  642. return replace_with
  643. else:
  644. return n
  645. if getattr(m, "_replace_hooks", None):
  646. for replace_hook in m._replace_hooks:
  647. replace_hook(old=self, new=replace_with.name, user=use_node)
  648. new_args = _fx_map_arg(use_node.args, maybe_replace_node)
  649. new_kwargs = _fx_map_arg(use_node.kwargs, maybe_replace_node)
  650. assert isinstance(new_args, tuple)
  651. assert isinstance(new_kwargs, dict)
  652. use_node._update_args_kwargs(new_args, new_kwargs)
  653. assert len(self.users) - len(skipped) == 0
  654. return [n for n in to_process if n not in skipped]
  655. @compatibility(is_backward_compatible=False)
  656. def is_impure(self, impure_random: bool = True) -> bool:
  657. """
  658. Returns whether this op is impure, i.e. if its op is a placeholder or
  659. output, or if a call_function or call_module which is impure.
  660. Args:
  661. impure_random (bool): Whether to treat rand op as impure.
  662. Returns:
  663. bool: If the op is impure or not.
  664. """
  665. if self.op in {"placeholder", "output"}:
  666. return True
  667. if self.op == "call_function":
  668. schema = getattr(self.target, "_schema", None)
  669. if schema is not None and schema.is_mutable:
  670. # impure since it mutates inputs
  671. return True
  672. if impure_random:
  673. if getattr(self.target, "_nondeterministic_seeded", False):
  674. # impure since it mutates RNG state
  675. return True
  676. # Handle Python random functions that don't have _nondeterministic_seeded
  677. # but still affect global RNG state (issue #151524)
  678. # These should be impure regardless of impure_random setting to maintain
  679. # consistency between eager and compiled execution
  680. _random_functions = {
  681. torch.rand,
  682. torch.randn,
  683. torch.randint,
  684. torch.randperm,
  685. torch.rand_like,
  686. torch.randn_like,
  687. torch.randint_like,
  688. torch.normal,
  689. torch.poisson,
  690. torch.bernoulli,
  691. torch.multinomial,
  692. }
  693. if self.target in _random_functions:
  694. # All random operations are impure to ensure consistent behavior
  695. # between eager and compiled execution, regardless of generator usage
  696. return True
  697. return self.target in _side_effectful_functions
  698. # Check if an impure module.
  699. if self.op == "call_module":
  700. assert self.graph.owning_module is not None, (
  701. "self.graph.owning_module not set for purity check"
  702. )
  703. target_mod = self.graph.owning_module.get_submodule(self.target)
  704. assert target_mod is not None, (
  705. f"Did not find expected submodule target {self.target}"
  706. )
  707. return getattr(target_mod, "_is_impure", False)
  708. return False
  709. @compatibility(is_backward_compatible=False)
  710. def normalized_arguments(
  711. self,
  712. root: torch.nn.Module,
  713. arg_types: Optional[tuple[Any]] = None,
  714. kwarg_types: Optional[dict[str, Any]] = None,
  715. normalize_to_only_use_kwargs: bool = False,
  716. ) -> Optional[ArgsKwargsPair]:
  717. """
  718. Returns normalized arguments to Python targets. This means that
  719. `args/kwargs` will be matched up to the module/functional's
  720. signature and return exclusively kwargs in positional order
  721. if `normalize_to_only_use_kwargs` is true.
  722. Also populates default values. Does not support positional-only
  723. parameters or varargs parameters.
  724. Supports module calls.
  725. May require `arg_types` and `kwarg_types` in order to disambiguate overloads.
  726. Args:
  727. root (torch.nn.Module): Module upon which to resolve module targets.
  728. arg_types (Optional[Tuple[Any]]): Tuple of arg types for the args
  729. kwarg_types (Optional[Dict[str, Any]]): Dict of arg types for the kwargs
  730. normalize_to_only_use_kwargs (bool): Whether to normalize to only use kwargs.
  731. Returns:
  732. Returns NamedTuple ArgsKwargsPair, or `None` if not successful.
  733. """
  734. if self.op == "call_function":
  735. assert callable(self.target)
  736. return normalize_function(
  737. self.target,
  738. self.args, # type: ignore[arg-type]
  739. self.kwargs,
  740. arg_types,
  741. kwarg_types,
  742. normalize_to_only_use_kwargs=normalize_to_only_use_kwargs,
  743. )
  744. elif self.op == "call_module":
  745. assert isinstance(self.target, str)
  746. return normalize_module(
  747. root,
  748. self.target,
  749. self.args, # type: ignore[arg-type]
  750. self.kwargs,
  751. normalize_to_only_use_kwargs=normalize_to_only_use_kwargs,
  752. )
  753. return None
  754. @compatibility(is_backward_compatible=True)
  755. def replace_input_with(self, old_input: "Node", new_input: "Node") -> None:
  756. """
  757. Loop through input nodes of ``self``, and replace all instances of
  758. ``old_input`` with ``new_input``.
  759. Args:
  760. old_input (Node): The old input node to be replaced.
  761. new_input (Node): The new input node to replace ``old_input``.
  762. """
  763. def maybe_replace_node(n: Node) -> Node:
  764. return new_input if n == old_input else n
  765. m = self.graph.owning_module
  766. if getattr(m, "_replace_hooks", None):
  767. for replace_hook in m._replace_hooks:
  768. replace_hook(old=old_input, new=new_input.name, user=self)
  769. new_args = _fx_map_arg(self.args, maybe_replace_node)
  770. new_kwargs = _fx_map_arg(self.kwargs, maybe_replace_node)
  771. assert isinstance(new_args, tuple)
  772. assert isinstance(new_kwargs, dict)
  773. self._update_args_kwargs(new_args, new_kwargs)
  774. def _rename(self, candidate: str) -> None:
  775. if candidate == self.name:
  776. return
  777. name = self.graph._graph_namespace.create_name(candidate, None)
  778. self.name = name
  779. self.graph._graph_namespace._rename_object(self, name)
  780. def __setattr__(self, name: str, value: Any) -> None:
  781. if name == "name" and hasattr(self, "name"):
  782. m = self.graph.owning_module
  783. if getattr(m, "_replace_hooks", None):
  784. assert isinstance(value, str)
  785. for user in self.users:
  786. for replace_hook in m._replace_hooks:
  787. replace_hook(old=self, new=value, user=user)
  788. update = False
  789. if (
  790. hasattr(self, name)
  791. and hasattr(self.graph, "_find_nodes_lookup_table")
  792. and self in self.graph._find_nodes_lookup_table
  793. ):
  794. update = True
  795. self.graph._find_nodes_lookup_table.remove(self)
  796. object.__setattr__(self, name, value)
  797. if update:
  798. self.graph._find_nodes_lookup_table.insert(self)
  799. @compatibility(is_backward_compatible=True)
  800. def map_arg(a: ArgumentT, fn: Callable[[Node], Argument]) -> ArgumentT:
  801. """
  802. Apply fn recursively to each Node appearing in arg.
  803. arg may be a list, tuple, slice, or dict with string keys: the return value will
  804. have the same type and structure.
  805. """
  806. assert callable(fn), "torch.fx.map_arg(a, fn): fn must be a callable"
  807. return _fx_map_arg(a, fn)
  808. @compatibility(is_backward_compatible=True)
  809. def map_aggregate(a: ArgumentT, fn: Callable[[Argument], Argument]) -> ArgumentT:
  810. """
  811. Apply fn recursively to each object appearing in arg.
  812. arg may be a list, tuple, slice, or dict with string keys: the return value will
  813. have the same type and structure.
  814. """
  815. return _fx_map_aggregate(a, fn)