node.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. # Nodes represent a definition of a value in our graph of operators.
  2. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set
  3. from ._compatibility import compatibility
  4. from .immutable_collections import immutable_dict, immutable_list
  5. import torch
  6. import builtins
  7. import types
  8. import warnings
  9. from torch.fx.operator_schemas import normalize_function, normalize_module, ArgsKwargsPair
  10. from .._ops import ops as _ops
  11. if TYPE_CHECKING:
  12. from .graph import Graph
  13. __all__ = ['Node', 'map_arg', 'map_aggregate']
  14. BaseArgumentTypes = Union[str, int, float, bool, complex, torch.dtype,
  15. torch.Tensor, torch.device, torch.memory_format, torch.layout]
  16. base_types = BaseArgumentTypes.__args__ # type: ignore[attr-defined]
  17. Target = Union[Callable[..., Any], str]
  18. Argument = Optional[Union[
  19. Tuple[Any, ...], # actually Argument, but mypy can't represent recursive types
  20. List[Any], # actually Argument
  21. Dict[str, Any], # actually Argument
  22. slice, # Slice[Argument, Argument, Argument], but slice is not a templated type in typing
  23. range,
  24. 'Node',
  25. BaseArgumentTypes
  26. ]]
  27. _side_effectful_functions: Set[Callable] = {
  28. torch._assert,
  29. _ops.profiler._record_function_enter,
  30. _ops.profiler._record_function_enter_new,
  31. _ops.profiler._record_function_exit}
  32. # this is fixed on master, WAR for 1.5
  33. def _find_module_of_method(orig_method: Callable[..., Any]) -> str:
  34. name = orig_method.__name__
  35. module = orig_method.__module__
  36. if module is not None:
  37. return module
  38. for guess in [torch, torch.nn.functional]:
  39. if getattr(guess, name, None) is orig_method:
  40. return guess.__name__
  41. raise RuntimeError(f'cannot find module for {orig_method}')
  42. # Borrowed from CPython typing module
  43. # https://github.com/python/cpython/blob/f90dc36c15d7fee0efaf6d39e97be0bdf2683e93/Lib/typing.py#L156
  44. def _type_repr(obj):
  45. """Return the repr() of an object, special-casing types (internal helper).
  46. If obj is a type, we return a shorter version than the default
  47. type.__repr__, based on the module and qualified name, which is
  48. typically enough to uniquely identify a type. For everything
  49. else, we fall back on repr(obj).
  50. """
  51. if isinstance(obj, type):
  52. if obj.__module__ == 'builtins':
  53. return obj.__qualname__
  54. return f'{obj.__module__}.{obj.__qualname__}'
  55. if obj is ...:
  56. return('...')
  57. if isinstance(obj, types.FunctionType):
  58. return obj.__name__
  59. return repr(obj)
  60. def _get_qualified_name(func: Callable[..., Any]) -> str:
  61. # things like getattr just appear in builtins
  62. if getattr(builtins, func.__name__, None) is func:
  63. return func.__name__
  64. # torch.Tensor.{fn}
  65. if isinstance(func, types.MethodDescriptorType) and func is getattr(torch.Tensor, func.__name__, None):
  66. return f"torch.Tensor.{func.__name__}"
  67. name = func.__name__
  68. module = _find_module_of_method(func)
  69. module = module.replace('torch._ops', 'torch.ops') # WAR for bug in how torch.ops assigns module
  70. # Fixup segment_reduce mismatch
  71. if module == "torch" and name == "segment_reduce":
  72. name = "_" + name
  73. return f'{module}.{name}'
  74. def _format_arg(arg, max_list_len=float('inf')) -> str:
  75. if hasattr(arg, '_custom_fx_repr_fn'):
  76. return arg._custom_fx_repr_fn()
  77. elif isinstance(arg, list):
  78. items = ', '.join(_format_arg(a) for idx, a in enumerate(arg) if idx < max_list_len)
  79. maybe_len = '' if len(arg) < max_list_len + 1 else f', ...[total_len={len(arg)}]'
  80. return f'[{items}{maybe_len}]'
  81. elif isinstance(arg, tuple):
  82. items = ', '.join(_format_arg(a) for idx, a in enumerate(arg) if idx < max_list_len)
  83. maybe_len = '' if len(arg) < max_list_len + 1 else f', ...[total_len={len(arg)}]'
  84. maybe_comma = ',' if len(arg) == 1 else ''
  85. return f'({items}{maybe_comma}{maybe_len})'
  86. elif isinstance(arg, dict):
  87. items_str = ', '.join(f'{k}: {_format_arg(v)}' for k, v in arg.items())
  88. return f'{{{items_str}}}'
  89. if isinstance(arg, Node):
  90. return '%' + str(arg)
  91. else:
  92. return str(arg)
  93. @compatibility(is_backward_compatible=True)
  94. class Node:
  95. """
  96. ``Node`` is the data structure that represents individual operations within
  97. a ``Graph``. For the most part, Nodes represent callsites to various entities,
  98. such as operators, methods, and Modules (some exceptions include nodes that
  99. specify function inputs and outputs). Each ``Node`` has a function specified
  100. by its ``op`` property. The ``Node`` semantics for each value of ``op`` are as follows:
  101. - ``placeholder`` represents a function input. The ``name`` attribute specifies the name this value will take on.
  102. ``target`` is similarly the name of the argument. ``args`` holds either: 1) nothing, or 2) a single argument
  103. denoting the default parameter of the function input. ``kwargs`` is don't-care. Placeholders correspond to
  104. the function parameters (e.g. ``x``) in the graph printout.
  105. - ``get_attr`` retrieves a parameter from the module hierarchy. ``name`` is similarly the name the result of the
  106. fetch is assigned to. ``target`` is the fully-qualified name of the parameter's position in the module hierarchy.
  107. ``args`` and ``kwargs`` are don't-care
  108. - ``call_function`` applies a free function to some values. ``name`` is similarly the name of the value to assign
  109. to. ``target`` is the function to be applied. ``args`` and ``kwargs`` represent the arguments to the function,
  110. following the Python calling convention
  111. - ``call_module`` applies a module in the module hierarchy's ``forward()`` method to given arguments. ``name`` is
  112. as previous. ``target`` is the fully-qualified name of the module in the module hierarchy to call.
  113. ``args`` and ``kwargs`` represent the arguments to invoke the module on, *excluding the self argument*.
  114. - ``call_method`` calls a method on a value. ``name`` is as similar. ``target`` is the string name of the method
  115. to apply to the ``self`` argument. ``args`` and ``kwargs`` represent the arguments to invoke the module on,
  116. *including the self argument*
  117. - ``output`` contains the output of the traced function in its ``args[0]`` attribute. This corresponds to the "return" statement
  118. in the Graph printout.
  119. """
  120. @compatibility(is_backward_compatible=True)
  121. def __init__(self, graph: 'Graph', name: str, op: str, target: 'Target',
  122. args: Tuple['Argument', ...], kwargs: Dict[str, 'Argument'],
  123. return_type : Optional[Any] = None) -> None:
  124. """
  125. Instantiate an instance of ``Node``. Note: most often, you want to use the
  126. Graph APIs, i.e. ``Graph.call_module``, ``Graph.call_method``, etc. rather
  127. than instantiating a ``Node`` directly.
  128. Args:
  129. graph (Graph): The ``Graph`` to which this ``Node`` should belong.
  130. name (str): The name to which the output of this ``Node`` should be assigned
  131. op (str): The opcode for this ``Node``. Can be one of 'placeholder',
  132. 'call_method', 'call_module', 'call_function', 'get_attr',
  133. 'output'
  134. target ('Target'): The target this op should call. See the broader
  135. ``Node`` docstring for more details.
  136. args (Tuple['Argument']): The args to be passed to ``target``
  137. kwargs (Dict[str, 'Argument']): The kwargs to be passed to ``target``
  138. return_type (Optional[Any]): The python type expression representing the
  139. type of the output of this node. This field can be used for
  140. annotation of values in the generated code or for other types
  141. of analyses.
  142. """
  143. self.graph = graph
  144. self.name = name # unique name of value being created
  145. assert op in ['placeholder', 'call_method', 'call_module', 'call_function', 'get_attr', 'output', 'root']
  146. self.op = op # the kind of operation = placeholder|call_method|call_module|call_function|get_attr
  147. if op == 'call_function':
  148. if not callable(target):
  149. raise ValueError(f'Node [graph = {graph}, name = \'{name}\'] target {target} has type {torch.typename(target)} '
  150. 'but a Callable is expected')
  151. else:
  152. if not isinstance(target, str):
  153. raise ValueError(f'Node [graph = {graph}, name = \'{name}\'] target {target} has type {torch.typename(target)} '
  154. 'but a str is expected')
  155. self.target = target # for method/module/function, the name of the method/module/function/attr
  156. # being invoked, e.g add, layer1, or torch.add
  157. # All `Node`-valued inputs. Key is the Node, value is don't-care.
  158. # The public API for this is `all_input_nodes`, this private attribute
  159. # should not be accessed directly.
  160. self._input_nodes : Dict[Node, None] = {}
  161. self.__update_args_kwargs(map_arg(args, lambda x: x), map_arg(kwargs, lambda x: x)) # type: ignore[arg-type]
  162. # All of the nodes that use the value produced by this Node
  163. # Note one user may correspond to several uses, e.g. the node fo ``x + x``
  164. # would appear once here, but represents two uses.
  165. #
  166. # Is a dict to act as an "ordered set". Keys are significant, value dont-care
  167. self.users : Dict['Node', None] = {}
  168. # Type expression representing the output value of this node.
  169. # This should contain the same class of Type objects that would appear
  170. # as type annotations for function inputs/outputs.
  171. #
  172. # For placeholder nodes, this value will be used to type-annotate the
  173. # generated function parameters.
  174. # For the return node, this value will be used to type-annotate the
  175. # generated function return type. (Note this is a special case. ``return``
  176. # does not produce a value, it's more of a notation. Thus, this value
  177. # describes the type of args[0] in the ``return`` node.
  178. self.type : Optional[Any] = return_type
  179. self._prev = self
  180. self._next = self
  181. self._erased = False
  182. # If set, use this fn to print this node
  183. self._repr_fn : Optional[Callable[[Node], str]] = None
  184. # Dictionary to store metadata passes need to do their
  185. # transformations. This metadata is preserved across node copies
  186. self.meta : Dict[str, Any] = {}
  187. @property
  188. def next(self) -> 'Node':
  189. """
  190. Returns the next ``Node`` in the linked list of Nodes.
  191. Returns:
  192. The next ``Node`` in the linked list of Nodes.
  193. """
  194. return self._next
  195. @property
  196. def prev(self) -> 'Node':
  197. """
  198. Returns the previous ``Node`` in the linked list of Nodes.
  199. Returns:
  200. The previous ``Node`` in the linked list of Nodes.
  201. """
  202. return self._prev
  203. @compatibility(is_backward_compatible=True)
  204. def prepend(self, x: 'Node') -> None:
  205. """
  206. Insert x before this node in the list of nodes in the graph. Example::
  207. Before: p -> self
  208. bx -> x -> ax
  209. After: p -> x -> self
  210. bx -> ax
  211. Args:
  212. x (Node): The node to put before this node. Must be a member of the same graph.
  213. """
  214. assert self.graph == x.graph, "Attempting to move a Node into a different Graph"
  215. if self == x:
  216. warnings.warn("Trying to prepend a node to itself. This behavior has no effect on the graph.")
  217. return
  218. x._remove_from_list()
  219. p = self._prev
  220. p._next, x._prev = x, p
  221. x._next, self._prev = self, x
  222. @compatibility(is_backward_compatible=True)
  223. def append(self, x: 'Node') -> None:
  224. """
  225. Insert ``x`` after this node in the list of nodes in the graph.
  226. Equivalent to ``self.next.prepend(x)``
  227. Args:
  228. x (Node): The node to put after this node. Must be a member of the same graph.
  229. """
  230. self._next.prepend(x)
  231. def _remove_from_list(self):
  232. p, n = self._prev, self._next
  233. p._next, n._prev = n, p
  234. @property
  235. def args(self) -> Tuple[Argument, ...]:
  236. """
  237. The tuple of arguments to this ``Node``. The interpretation of arguments
  238. depends on the node's opcode. See the :class:`Node` docstring for more
  239. information.
  240. Assignment to this property is allowed. All accounting of uses and users
  241. is updated automatically on assignment.
  242. """
  243. return self._args
  244. @args.setter
  245. def args(self, a : Tuple[Argument, ...]):
  246. """
  247. Set the tuple of arguments to this Node. The interpretation of arguments
  248. depends on the node's opcode. See the ``fx.Graph`` docstring for more
  249. information.
  250. """
  251. # DO NOT CALL `__update_args_kwargs` directly. The correct way to
  252. # set `args` is via direct assignment, i.e. `node.args = new_args`
  253. self.__update_args_kwargs(map_arg(a, lambda x: x), self._kwargs) # type: ignore[arg-type]
  254. @property
  255. def kwargs(self) -> Dict[str, Argument]:
  256. """
  257. The dict of keyword arguments to this ``Node``. The interpretation of arguments
  258. depends on the node's opcode. See the :class:`Node` docstring for more
  259. information.
  260. Assignment to this property is allowed. All accounting of uses and users
  261. is updated automatically on assignment.
  262. """
  263. return self._kwargs
  264. @kwargs.setter
  265. def kwargs(self, k : Dict[str, Argument]):
  266. """
  267. Set the dict of kwargs to this Node. The interpretation of arguments
  268. depends on the node's opcode. See the ``fx.Graph`` docstring for more
  269. information.
  270. """
  271. # DO NOT CALL `__update_args_kwargs` directly. The correct way to
  272. # set `args` is via direct assignment, i.e. `node.kwargs = new_kwargs`
  273. self.__update_args_kwargs(self._args, map_arg(k, lambda x: x)) # type: ignore[arg-type]
  274. @property
  275. def all_input_nodes(self) -> List['Node']:
  276. """
  277. Return all Nodes that are inputs to this Node. This is equivalent to
  278. iterating over ``args`` and ``kwargs`` and only collecting the values that
  279. are Nodes.
  280. Returns:
  281. List of ``Nodes`` that appear in the ``args`` and ``kwargs`` of this
  282. ``Node``, in that order.
  283. """
  284. return list(self._input_nodes.keys())
  285. @compatibility(is_backward_compatible=True)
  286. def update_arg(self, idx : int, arg : Argument) -> None:
  287. """
  288. Update an existing positional argument to contain the new value
  289. ``arg``. After calling, ``self.args[idx] == arg``.
  290. Args:
  291. idx (int): The index into ``self.args`` of the element to update
  292. arg (Argument): The new argument value to write into ``args``
  293. """
  294. args = list(self.args)
  295. args[idx] = arg
  296. self.args = tuple(args)
  297. @compatibility(is_backward_compatible=True)
  298. def update_kwarg(self, key : str, arg : Argument) -> None:
  299. """
  300. Update an existing keyword argument to contain the new value
  301. ``arg``. After calling, ``self.kwargs[key] == arg``.
  302. Args:
  303. key (str): The key in ``self.kwargs`` of the element to update
  304. arg (Argument): The new argument value to write into ``kwargs``
  305. """
  306. kwargs = dict(self.kwargs)
  307. kwargs[key] = arg
  308. self.kwargs = kwargs
  309. @property
  310. def stack_trace(self) -> Optional[str]:
  311. """
  312. Return the Python stack trace that was recorded during tracing, if any.
  313. This property is usually populated by `Tracer.create_proxy`. To record
  314. stack traces during tracing for debug purposes, set
  315. `record_stack_traces = True` on the `Tracer` instance.
  316. """
  317. return self.meta.get("stack_trace", None)
  318. @stack_trace.setter
  319. def stack_trace(self, trace : Optional[str]):
  320. self.meta["stack_trace"] = trace
  321. def __update_args_kwargs(self, new_args : Tuple['Argument', ...], new_kwargs : Dict[str, 'Argument']):
  322. """
  323. This API is internal. Do *not* call it directly.
  324. """
  325. self._args = new_args
  326. self._kwargs = new_kwargs
  327. for old_use in self._input_nodes.keys():
  328. old_use.users.pop(self)
  329. self._input_nodes = {}
  330. map_arg(self._args, lambda n: self._input_nodes.setdefault(n))
  331. map_arg(self._kwargs, lambda n: self._input_nodes.setdefault(n))
  332. for new_use in self._input_nodes.keys():
  333. new_use.users.setdefault(self)
  334. def __repr__(self) -> str:
  335. if self._repr_fn:
  336. return self._repr_fn(self)
  337. return self.name
  338. def _pretty_print_target(self, target):
  339. """
  340. Make target printouts more user-friendly.
  341. 1) builtins will be printed as `builtins.xyz`
  342. 2) operators will be printed as `operator.xyz`
  343. 3) other callables will be printed with qualfied name, e.g. torch.add
  344. """
  345. if isinstance(target, str):
  346. return target
  347. if hasattr(target, '__module__'):
  348. if not hasattr(target, '__name__'):
  349. # Just to be defensive, if we don't have `__name__`, get the
  350. # qualname. Not sure if this happens for any members of `operator`
  351. # or `builtins`. This fallback path is not as good, since e.g.
  352. # things in `operator` have `_operator` as their __module__.
  353. return _get_qualified_name(target)
  354. if target.__module__ == 'builtins':
  355. return f'builtins.{target.__name__}'
  356. elif target.__module__ == '_operator':
  357. return f'operator.{target.__name__}'
  358. return _get_qualified_name(target)
  359. @compatibility(is_backward_compatible=True)
  360. def format_node(self,
  361. placeholder_names: Optional[List[str]] = None,
  362. maybe_return_typename: Optional[List[str]] = None) -> Optional[str]:
  363. """
  364. Return a descriptive string representation of ``self``.
  365. This method can be used with no arguments as a debugging
  366. utility.
  367. This function is also used internally in the ``__str__`` method
  368. of ``Graph``. Together, the strings in ``placeholder_names``
  369. and ``maybe_return_typename`` make up the signature of the
  370. autogenerated ``forward`` function in this Graph's surrounding
  371. GraphModule. ``placeholder_names`` and ``maybe_return_typename``
  372. should not be used otherwise.
  373. Args:
  374. placeholder_names: A list that will store formatted strings
  375. representing the placeholders in the generated
  376. ``forward`` function. Internal use only.
  377. maybe_return_typename: A single-element list that will store
  378. a formatted string representing the output of the
  379. generated ``forward`` function. Internal use only.
  380. Returns:
  381. str: If 1) we're using ``format_node`` as an internal helper
  382. in the ``__str__`` method of ``Graph``, and 2) ``self``
  383. is a placeholder Node, return ``None``. Otherwise,
  384. return a descriptive string representation of the
  385. current Node.
  386. """
  387. if self.op == 'placeholder':
  388. assert isinstance(self.target, str)
  389. arg_str = self.target
  390. arg_str += arg_str + f': {_type_repr(self.type)}' if self.type else ''
  391. if placeholder_names:
  392. placeholder_names.append(arg_str)
  393. return None
  394. maybe_typename = f'{_type_repr(self.type)} ' if self.type else ''
  395. default_val = '(default=' + str(self.args[0]) + ')' if self.args else ''
  396. return f'%{self.name} : {maybe_typename}[#users={len(self.users)}] = {self.op}[target={self.target}]{default_val}'
  397. elif self.op == 'get_attr':
  398. maybe_typename = f'{_type_repr(self.type)} ' if self.type is not None else ''
  399. return f'%{self.name} : {maybe_typename}[#users={len(self.users)}] = ' \
  400. f'{self.op}[target={self._pretty_print_target(self.target)}]'
  401. elif self.op == 'output':
  402. if self.type and maybe_return_typename:
  403. maybe_return_typename[0] = f' -> {_type_repr(self.type)}'
  404. return f'return {self.args[0]}'
  405. else:
  406. maybe_typename = f'{_type_repr(self.type)} ' if self.type is not None else ''
  407. return f'%{self.name} : {maybe_typename}[#users={len(self.users)}] = ' \
  408. f'{self.op}[target={self._pretty_print_target(self.target)}](' \
  409. f'args = {_format_arg(self.args)}, kwargs = {_format_arg(self.kwargs)})'
  410. @compatibility(is_backward_compatible=True)
  411. def replace_all_uses_with(self,
  412. replace_with : 'Node',
  413. delete_user_cb: Callable[['Node'], bool] = lambda user: True,
  414. *,
  415. propagate_meta=False
  416. ) -> List['Node']:
  417. """
  418. Replace all uses of ``self`` in the Graph with the Node ``replace_with``.
  419. Args:
  420. replace_with (Node): The node to replace all uses of ``self`` with.
  421. delete_user_cb (Callable): Callback that is called to determine
  422. whether a given user of the self node should be removed.
  423. propagate_meta (bool): Whether or not to copy all properties
  424. on the .meta field of the original node onto the replacement node.
  425. For safety, this is only valid to do if the replacement node
  426. doesn't already have an existing .meta field.
  427. Returns:
  428. The list of Nodes on which this change was made.
  429. """
  430. if propagate_meta:
  431. assert len(replace_with.meta) == 0, \
  432. 'Called node.replace_all_uses_with(replace_with, propagate_meta=True), ' \
  433. 'but replace_with already has .meta keys'
  434. for k, v in self.meta.items():
  435. replace_with.meta[k] = v
  436. to_process = list(self.users)
  437. skipped = []
  438. for use_node in to_process:
  439. if not delete_user_cb(use_node):
  440. skipped.append(use_node)
  441. continue
  442. def maybe_replace_node(n : Node) -> Node:
  443. if n == self:
  444. return replace_with
  445. else:
  446. return n
  447. new_args = map_arg(use_node.args, maybe_replace_node)
  448. new_kwargs = map_arg(use_node.kwargs, maybe_replace_node)
  449. assert isinstance(new_args, tuple)
  450. assert isinstance(new_kwargs, dict)
  451. use_node.__update_args_kwargs(new_args, new_kwargs)
  452. assert len(self.users) - len(skipped) == 0
  453. return [n for n in to_process if n not in skipped]
  454. @compatibility(is_backward_compatible=False)
  455. def is_impure(self):
  456. """
  457. Returns whether this op is impure, i.e. if its op is a placeholder or
  458. output, or if a call_function or call_module which is impure.
  459. Returns:
  460. bool: If the op is impure or not.
  461. """
  462. if self.op in {"placeholder", "output"}:
  463. return True
  464. # Check if an impure function.
  465. if self.op == "call_function":
  466. return self.target in _side_effectful_functions
  467. # Check if an impure module.
  468. if self.op == "call_module":
  469. assert (
  470. self.graph.owning_module is not None
  471. ), "self.graph.owning_module not set for purity check"
  472. target_mod = self.graph.owning_module.get_submodule(self.target)
  473. assert (
  474. target_mod is not None
  475. ), f"Did not find expected submodule target {self.target}"
  476. return getattr(target_mod, "_is_impure", False)
  477. return False
  478. @compatibility(is_backward_compatible=False)
  479. def normalized_arguments(
  480. self, root : torch.nn.Module, arg_types : Optional[Tuple[Any]] = None,
  481. kwarg_types : Optional[Dict[str, Any]] = None,
  482. normalize_to_only_use_kwargs : bool = False) -> Optional[ArgsKwargsPair]:
  483. """
  484. Returns normalized arguments to Python targets. This means that
  485. `args/kwargs` will be matched up to the module/functional's
  486. signature and return exclusively kwargs in positional order
  487. if `normalize_to_only_use_kwargs` is true.
  488. Also populates default values. Does not support positional-only
  489. parameters or varargs parameters.
  490. Supports module calls.
  491. May require `arg_types` and `kwarg_types` in order to disambiguate overloads.
  492. Args:
  493. root (torch.nn.Module): Module upon which to resolve module targets.
  494. arg_types (Optional[Tuple[Any]]): Tuple of arg types for the args
  495. kwarg_types (Optional[Dict[str, Any]]): Dict of arg types for the kwargs
  496. normalize_to_only_use_kwargs (bool): Whether to normalize to only use kwargs.
  497. Returns:
  498. Returns NamedTuple ArgsKwargsPair, or `None` if not successful.
  499. """
  500. if self.op == 'call_function':
  501. assert callable(self.target)
  502. return normalize_function(self.target, self.args, self.kwargs, arg_types, kwarg_types) # type: ignore[arg-type]
  503. elif self.op == 'call_module':
  504. assert isinstance(self.target, str)
  505. return normalize_module(root, self.target, self.args, self.kwargs) # type: ignore[arg-type]
  506. return None
  507. @compatibility(is_backward_compatible=True)
  508. def replace_input_with(self, old_input: 'Node', new_input: 'Node'):
  509. """
  510. Loop through input nodes of ``self``, and replace all instances of
  511. ``old_input`` with ``new_input``.
  512. Args:
  513. old_input (Node): The old input node to be replaced.
  514. new_input (Node): The new input node to replace ``old_input``.
  515. """
  516. def maybe_replace_node(n : Node) -> Node:
  517. return new_input if n == old_input else n
  518. new_args = map_arg(self.args, maybe_replace_node)
  519. new_kwargs = map_arg(self.kwargs, maybe_replace_node)
  520. assert isinstance(new_args, tuple)
  521. assert isinstance(new_kwargs, dict)
  522. self.__update_args_kwargs(new_args, new_kwargs)
  523. @compatibility(is_backward_compatible=True)
  524. def map_arg(a: Argument, fn: Callable[[Node], Argument]) -> Argument:
  525. """
  526. Apply fn to each Node appearing arg. arg may be a list, tuple, slice, or dict with string keys.
  527. """
  528. assert callable(fn), "torch.fx.map_arg(a, fn): fn must be a callable"
  529. return map_aggregate(a, lambda x: fn(x) if isinstance(x, Node) else x)
  530. @compatibility(is_backward_compatible=True)
  531. def map_aggregate(a: Argument, fn: Callable[[Argument], Argument]) -> Argument:
  532. """
  533. Apply fn to each Node appearing arg. arg may be a list, tuple, slice, or dict with string keys.
  534. """
  535. if isinstance(a, tuple):
  536. t = tuple(map_aggregate(elem, fn) for elem in a)
  537. # Support NamedTuple (if it has `_fields`) by repacking into original type.
  538. return t if not hasattr(a, '_fields') else type(a)(*t)
  539. elif isinstance(a, list):
  540. return immutable_list(map_aggregate(elem, fn) for elem in a)
  541. elif isinstance(a, dict):
  542. return immutable_dict((k, map_aggregate(v, fn)) for k, v in a.items())
  543. elif isinstance(a, slice):
  544. return slice(map_aggregate(a.start, fn), map_aggregate(a.stop, fn), map_aggregate(a.step, fn))
  545. else:
  546. return fn(a)