node.py 35 KB

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