node.py 34 KB

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