node.py 26 KB

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