reinplace.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. # mypy: allow-untyped-defs
  2. import _operator
  3. import itertools
  4. from collections import defaultdict
  5. from collections.abc import Callable
  6. from enum import Enum
  7. from typing import Any
  8. import torch
  9. from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
  10. from torch.fx import Node
  11. from torch.fx._compatibility import compatibility
  12. from torch.multiprocessing.reductions import StorageWeakRef
  13. from torch.utils import _pytree as pytree
  14. from torch.utils._pytree import tree_map_only
  15. __all__ = ["reinplace"]
  16. class _ViewType(Enum):
  17. NonView = 0
  18. SingleOutputView = 1
  19. MultiOutputView = 2
  20. def _is_view_op(tgt):
  21. if tgt is not None and isinstance(tgt, torch._ops.OpOverload):
  22. schema = tgt._schema
  23. if len(schema.arguments) > 0:
  24. first_arg = schema.arguments[0]
  25. # check if op is a view
  26. return (
  27. first_arg.alias_info is not None and not first_arg.alias_info.is_write
  28. )
  29. def _get_view_type(tgt) -> _ViewType:
  30. if tgt is not None and isinstance(tgt, torch._ops.OpOverload):
  31. schema = tgt._schema
  32. if len(schema.arguments) > 0:
  33. first_arg = schema.arguments[0]
  34. # check if op is a view
  35. if first_arg.alias_info is not None and not first_arg.alias_info.is_write:
  36. # check if op is a multi-output view
  37. if "*" in first_arg.alias_info.after_set:
  38. return _ViewType.MultiOutputView
  39. else:
  40. return _ViewType.SingleOutputView
  41. return _ViewType.NonView
  42. # Stores a bunch of metadata related to functionalization each node.
  43. # Relevant metadata:
  44. # n.meta['fake_result']: FakeTensor (same type as the output of the node, but with FakeTenors instead of Tensors)
  45. # The fake tensor output from running the current node
  46. # n.meta['view_of']: Node
  47. # If the current node n is a view of some base tensor, the 'view_of' field tells us which
  48. # view node was used to generate the current node (a view tensor).
  49. # This information actually makes `fake_result` redundant, but we can use `fake_result`
  50. # to sanity check that our aliasing information is correct.
  51. @compatibility(is_backward_compatible=False)
  52. class _FunctionalizationMetadataProp(torch.fx.Interpreter):
  53. def run_node(self, node: Node):
  54. self.node_counter += 1
  55. result = super().run_node(node)
  56. node.meta["fake_result"] = result
  57. node.meta["node_idx"] = self.node_counter
  58. # (1) Update metadata with the list of nodes that are used by this node
  59. # copy_() doesn't read from its first argument; it writes to it, overwriting previous data.
  60. # We don't want to treat it as "being used as an input".
  61. node_args = node.args
  62. if node.target is torch.ops.aten.copy_.default:
  63. node_args = node_args[1:]
  64. # (2) Update metadata to track aliasing information about view tensor nodes.
  65. if node.op == "call_function":
  66. view_type = _get_view_type(node.target)
  67. if view_type == _ViewType.SingleOutputView:
  68. if not isinstance(node.args[0], Node):
  69. raise AssertionError(f"Expected Node, got {type(node.args[0])}")
  70. node.meta["view_of"] = node.args[0]
  71. elif view_type == _ViewType.MultiOutputView:
  72. self.multi_output_view_nodes[node] = node.args[0]
  73. # Check if we returned a multi-output view,
  74. # and we're now grabbing the individual views from the output.
  75. #
  76. # For multi-output views, we want to map each output view to the base,
  77. # but this mapping involves two separate nodes in FX IR.
  78. # e.g. "a, b = x_1.split(...)" becomes:
  79. # %split_tensor : [num_users=2] = call_function[target=torch.ops.aten.split.Tensor](args = (%x_1, 2), kwargs = {})
  80. # %getitem : [num_users=1] = call_function[target=operator.getitem](args = (%split_tensor, 0), kwargs = {})
  81. # %getitem_1 : [num_users=1] = call_function[target=operator.getitem](args = (%split_tensor, 1), kwargs = {})
  82. # And we'd like to set:
  83. # getitem1.meta['view_of'] = x_1
  84. elif node.target is _operator.getitem:
  85. list_arg = node.args[0]
  86. maybe_base_of_view = self.multi_output_view_nodes.get(list_arg, None)
  87. if maybe_base_of_view is not None:
  88. # Note: we could also track indexing info here for multi-output views.
  89. # I don't think this metadata is strictly needed for de-functionalization.
  90. if not isinstance(maybe_base_of_view, Node):
  91. raise AssertionError(
  92. f"Expected Node, got {type(maybe_base_of_view)}"
  93. )
  94. node.meta["view_of"] = maybe_base_of_view
  95. if "view_of" in node.meta:
  96. # We're linking the current node with its first argument as views.
  97. # Assert here that this is actually the case, and their storages are the same.
  98. if not isinstance(node.meta["fake_result"], FakeTensor):
  99. raise AssertionError("Expected FakeTensor in fake_result")
  100. if not isinstance(node.meta["view_of"].meta["fake_result"], FakeTensor):
  101. raise AssertionError("Expected FakeTensor in view_of fake_result")
  102. view_storage = StorageWeakRef(node.meta["fake_result"]._typed_storage())
  103. base_storage = StorageWeakRef(
  104. node.meta["view_of"].meta["fake_result"]._typed_storage()
  105. )
  106. if view_storage != base_storage:
  107. raise AssertionError("view_storage != base_storage")
  108. return result
  109. def propagate(self, *args):
  110. self.multi_output_view_nodes = {}
  111. self.node_counter = -1
  112. with FakeTensorMode() as mode:
  113. fake_args = [
  114. mode.from_tensor(a) if isinstance(a, torch.Tensor) else a for a in args
  115. ]
  116. return super().run(*fake_args)
  117. def _schemas_match(functional_schema, inplace_schema):
  118. names_match = (
  119. inplace_schema.name.endswith("_")
  120. and inplace_schema.name[:-1] == functional_schema.name
  121. )
  122. arg_types_match = len(functional_schema.arguments) == len(
  123. inplace_schema.arguments
  124. ) and all(
  125. a1.type == a2.type
  126. for a1, a2 in zip(functional_schema.arguments, inplace_schema.arguments)
  127. )
  128. # for the inplace op, its first argument should be mutable
  129. if not (
  130. inplace_schema.arguments[0].alias_info is not None
  131. and inplace_schema.arguments[0].alias_info.is_write
  132. ):
  133. raise AssertionError("First argument of inplace op must be mutable")
  134. # and its remaining arguments shouldn't be.
  135. if not all(a.alias_info is None for a in inplace_schema.arguments[1:]):
  136. raise AssertionError("Remaining arguments of inplace op must not be mutable")
  137. return names_match and arg_types_match
  138. # TODO: this should be beefed up to be able to properly re-inplace with:
  139. # - mutating ops (e.g. _fused_moving_avg_obs_fq_helper)
  140. # - out= ops (e.g. angle -> angle.out)
  141. # TODO: we should also figure this info out using torchgen.
  142. def _maybe_get_inplace_op(op):
  143. # __module__ seems broken; it returns torch._ops.aten which doesn't exist
  144. if not isinstance(op, torch._ops.OpOverload):
  145. return None
  146. # Some view ops have inplace variants (as_strided_, etc),
  147. # but we do NOT want the reinplacing pass to directly add these into the program.
  148. # (they'll require extra special handling, aren't aren't really useful for perf anyway)
  149. if _is_view_op(op):
  150. return None
  151. op_namespace = op.__module__.split(".")[-1]
  152. op_base_name = op.overloadpacket.__name__
  153. maybe_namespace_module = getattr(torch.ops, op_namespace)
  154. maybe_inplace_op = (
  155. None
  156. if maybe_namespace_module is None
  157. else getattr(maybe_namespace_module, f"{op_base_name}_", None)
  158. )
  159. if maybe_inplace_op is None:
  160. return None
  161. inplace_overloads = [
  162. getattr(maybe_inplace_op, overload_name)
  163. for overload_name in maybe_inplace_op.overloads()
  164. ]
  165. inplace_overloads_with_matching_schemas = [
  166. f for f in inplace_overloads if _schemas_match(op._schema, f._schema)
  167. ]
  168. # Just because foo() and foo_() are both existing operators,
  169. # They aren't guaranteed to have compatible schemas.
  170. # For example, pow.Scalar(Scalar self, Tensor exponent) has no valid inplace variant,
  171. # Even though several overloads of pow_ exist.
  172. if len(inplace_overloads_with_matching_schemas) == 0:
  173. return None
  174. if len(inplace_overloads_with_matching_schemas) != 1:
  175. raise AssertionError(
  176. f"Expected exactly 1 matching inplace overload, got "
  177. f"{len(inplace_overloads_with_matching_schemas)}"
  178. )
  179. inplace_op = inplace_overloads_with_matching_schemas[0]
  180. return inplace_op
  181. _VIEW_INVERSE_MAP: dict[Callable[..., Any], Callable[..., Any]] = {
  182. torch.ops.aten.diagonal_scatter.default: torch.ops.aten.diagonal.default,
  183. torch.ops.aten.select_scatter.default: torch.ops.aten.select.int,
  184. torch.ops.aten.slice_scatter.default: torch.ops.aten.slice.Tensor,
  185. torch.ops.aten.as_strided_scatter.default: torch.ops.aten.as_strided.default,
  186. }
  187. # This function, given a set of set of (aliased) tensor nodes,
  188. # Returns any nodes in the graph that *use* any of the aliases, that occur *after* op_index
  189. # in the node ordering.
  190. def _get_all_later_node_usages(tensor_aliases: set[Node], op_index: int):
  191. def _add_if_tensor(x, set_):
  192. if isinstance(x, FakeTensor):
  193. set_.add(StorageWeakRef(x._typed_storage()))
  194. nodes_used_after = set()
  195. for t in tensor_aliases:
  196. # get all nodes that use the current alias
  197. usage_nodes = t.users
  198. for n in usage_nodes:
  199. # We only care about usages after the current node
  200. if "node_idx" not in n.meta or n.meta["node_idx"] <= op_index:
  201. continue
  202. # We also don't care about intermediate view ops.
  203. # They only matter if their output is then used elsewhere
  204. # (either in an out-of-place op, or as an output to the function).
  205. if n in tensor_aliases:
  206. if (
  207. isinstance(n.target, torch._ops.OpOverload)
  208. or n.target is _operator.getitem
  209. ):
  210. continue
  211. nodes_used_after.add(n)
  212. return nodes_used_after
  213. # Given an op that we're trying to re-inplace, "b = foo(a)",
  214. # And given a {view}_scatter op that shows up later in the graph, "y = {view}_scatter(base, x, args...)"
  215. # Then re-inplacing `foo()` would allow us to remove the `{view}_scatter` op entirely, IF:
  216. # If there are any aliases in the alias_set(a) that satisfy:
  217. # (1) The base of "alias", "alias_base", has the same size/stride/offset metadata as "base"
  218. # (2) The output of running {view}(alias, args...) gives you the same size/stride/offset metadata
  219. # as "alias"
  220. def _get_view_inverse_node_usages(
  221. later_node_usages: set[Node], self_aliases: set[Node]
  222. ) -> set[Node]:
  223. def matching_view_metadata(a, b):
  224. return (
  225. a.size() == b.size()
  226. and a.stride() == b.stride()
  227. and a.storage_offset() == b.storage_offset()
  228. )
  229. view_inverse_nodes = set()
  230. # Go through them in node order, so we can see chains of view_scatter ops.
  231. for n in sorted(later_node_usages, key=lambda x: x.meta["node_idx"]):
  232. if n.target not in _VIEW_INVERSE_MAP:
  233. continue
  234. base = n.args[0]
  235. mutated_view = n.args[1]
  236. if not isinstance(base, Node):
  237. raise AssertionError(f"Expected Node for base, got {type(base)}")
  238. if not isinstance(base.meta["fake_result"], FakeTensor):
  239. raise AssertionError("Expected FakeTensor in base.meta['fake_result']")
  240. if not isinstance(mutated_view, Node):
  241. raise AssertionError(
  242. f"Expected Node for mutated_view, got {type(mutated_view)}"
  243. )
  244. if not isinstance(mutated_view.meta["fake_result"], FakeTensor):
  245. raise AssertionError(
  246. "Expected FakeTensor in mutated_view.meta['fake_result']"
  247. )
  248. if isinstance(n.target, str):
  249. raise AssertionError("n.target should not be a string")
  250. # Check that this view_inverse op actually corresponds to taking doing the inverse
  251. # of one of our existing self_alias nodes.
  252. original_view = _VIEW_INVERSE_MAP[n.target]
  253. for self_alias in self_aliases:
  254. # We're looking for some alias of the self arg, "alias",
  255. # that was created from some op `alias = foo(base, args...)`
  256. # such that the current _scatter op "inverts" that foo call.
  257. # We can check that by running the original op again, and checking that the strides match.
  258. if "view_of" not in self_alias.meta:
  259. continue
  260. self_alias_base = self_alias.meta["view_of"]
  261. try:
  262. # The we're trying to reuse the args from the view_scatter call inside of the corresponding
  263. # view op, which might throw. This just indicates that view_scatter op isn't a valid inverse
  264. # of the current alias we're looking at.
  265. view_replay_metadata = original_view(
  266. self_alias_base.meta["fake_result"], *n.args[2:], **n.kwargs
  267. )
  268. expected_metadata = self_alias.meta["fake_result"]
  269. # If the alias and its base both have matching metadata, then this view_scatter op is valid to re-inplace.
  270. if matching_view_metadata(
  271. self_alias_base.meta["fake_result"], base.meta["fake_result"]
  272. ) and matching_view_metadata(view_replay_metadata, expected_metadata):
  273. view_inverse_nodes.add(n)
  274. except Exception:
  275. continue
  276. return view_inverse_nodes
  277. @compatibility(is_backward_compatible=True)
  278. def reinplace(gm, *sample_args):
  279. """
  280. Given an fx.GraphModule, modifies it to perform "reinplacing",
  281. mutating the nodes of the graph.
  282. We look for out-of-place op call sites like `b = a.add(...)`,
  283. and convert them to be inplace (`b = a.add_(...)`),
  284. as long as the input to the current operator ("a") isn't reused
  285. anywhere later in the graph.
  286. This pass currently expects to operate on a **functional, ATen** graph.
  287. This can be obtained by running `make_fx(functionalize(f))`.
  288. Sample inputs are needed to determine aliasing relationships of the inputs.
  289. In general, we can't reinplace node `b = a.add(...)` if "a" aliases any of the
  290. inputs to the program.
  291. Given a node "b = foo(a, args...) the algorithm for re-inplacing is as follows:
  292. (1) Perform some initial checks on the metadata of "a" and "args..."
  293. that can disqualify them from being reinplaced.
  294. (1a) Check that the self argument we're attempting to reinplace
  295. has acceptable dtype/size metadata to reinplace with.
  296. For example, if we have:
  297. a = torch.ones(1)
  298. b = torch.ones(10)
  299. out = torch.add(a, b)
  300. We can't turn that into
  301. a.add_(b)
  302. Because that would require resizing "a".
  303. Similarly, we can't convert torch.ge(a, b) into a.ge_(b),
  304. because that would require changing a's dtype (from e.g. float32 to bool).
  305. Note that in this specific example, we could technically do better..
  306. If we see the pattern:
  307. a_1 = a.ge(b)
  308. a_2 = aten._to_copy(a_1, a.dtype)
  309. Then we this should be valid to completely re-inplace
  310. (this is exactly what functionalization will emit when it sees a.ge_(b)).
  311. This optimization is only really important for user programs
  312. that directly use inplace comparison ops though.
  313. We also cannot re-inplace on tensors that have overlapping memory,
  314. e.g. torch.ones(1).expand(4, 4).add_(1)
  315. (1b) Check if "a" is an alias of any of the program inputs.
  316. If it is, skip and move to the next node.
  317. Inplace'ing an op that would cause it to mutate a program is not sound,
  318. because that would be a side effect visible to the user.
  319. NOTE: there's a future optimization that we should make:
  320. if "a" is a (alias of a) program input, but later in the program
  321. there is a node that looks like "a.copy_(...)",
  322. Then re-inplacing is ok to do - we are temporarily reusing a's buffer,
  323. which will later be overwritten by the copy_() call.
  324. This will be an important optimization to have for programs that mutate
  325. their inputs. It currently isn't implemented though.
  326. (1c) Check if "a" and "args..." alias
  327. For example, re-inplacing to create code like the below
  328. isn't guaranteed to be sound:
  329. aten.mul_(a, a)
  330. (2) Check that "a" and all of its outstanding aliases are not used anywhere
  331. later in the graph. If this is the case, then it's safe to re-inplace
  332. to "b = foo_(a)".
  333. There are a few caveats to this, explained in more detail below:
  334. (a) If "a" is used later as an argument to a view op, that is okay.
  335. It's only a problem if "a" (or that view) is later passed
  336. into a normal operator, or if it is returned as the program output.
  337. (b) If "a" is a repeat argument in `foo()`, then don't reinplace.
  338. Most ATen kernels don't make any guarantees that this is sound,
  339. e.g. if you do aten.mul_(a, a).
  340. So we'll just ban re-inplacing in this case.
  341. It's only a problem if "a" (or that view) is later passed
  342. (c) If "a" is used as an input into a view "inverse" / "scatter"
  343. operator, it is potentially fine to re-inplace
  344. (and remove that scatter operator from the graph).
  345. See below for a more detailed example.
  346. NOTE: there is an optimization in this step that is crucial
  347. to fully recovering performance from functionalization.
  348. Given this program:
  349. def f(x):
  350. a = torch.ops.aten.add(x, x)
  351. b = torch.ops.aten.diagonal(a)
  352. torch.ops.aten.fill_(b, 0)
  353. return d
  354. Functionalization will emit the following:
  355. def f(x):
  356. a = torch.ops.aten.add(x, x)
  357. b = torch.ops.aten.diagonal(a, 0, 1)
  358. b_updated = torch.ops.aten.fill(b, 0)
  359. a_updated = torch.ops.aten.diagonal_scatter(a, b_updated, 0, 1)
  360. return a_updated
  361. Ordinarily, we would not be able to reinplace the fill,
  362. because "b" aliases with "a" which is used by the diagonal_scatter call.
  363. "re-inplacing" is on the hook for figuring out that it is ok to
  364. completely, the expensive diagonal_scatter call, if we re-inplace the add().
  365. So, for every `alias in alias_set(a)`, instead of checking
  366. that "alias" is not used anywhere later in the graph,
  367. we check that
  368. EITHER:
  369. (a) alias is not used anywhere later in the graph
  370. OR:
  371. (b) alias is used exactly once later on in the graph,
  372. in the following op:
  373. out = foo_scatter(alias, x, args...)
  374. where the following must hold:
  375. (i) "foo_scatter" is the "inverse" operator for foo.
  376. This only applies to "foo" ops that are view operators,
  377. which view into a subset of the original tensor's memory.
  378. In practice, there are ~4 operators where this applies:
  379. diagonal -> diagonal_scatter
  380. slice -> slice_scatter
  381. select -> select_scatter
  382. as_strided -> as_strided_scatter
  383. (ii) "args..." are the same between the foo() and foo_scatter() calls.
  384. (3) Perform the actual re-inplacing on foo!
  385. (3b) is the common case, but special care is needed for {view}_scatter (3a)
  386. (3a) {view}_scatter ops.
  387. Consider this program:
  388. a = torch.zeros(2, 2)
  389. b = torch.ones(2)
  390. a[0] = b
  391. Post functionalization, that will look like:
  392. a = torch.zeros(2)
  393. b = torch.ones(1)
  394. a_updated = torch.select_scatter(a, b, 0, 0)
  395. In this case though, there is no "functional" op to re-inplace!
  396. Instead, we'd like to directly remove toe select_scatter call.
  397. We already know from (3) that this is valid,
  398. because "a" has no later usages in the graph.
  399. We perform the re-inplacing on the {view}_scatter op like so
  400. Before:
  401. a_updated = torch.select_scatter(a, b, args...)
  402. After:
  403. a_slice = a.select(a, args...)
  404. a_slice.copy_(b)
  405. (3b) Otherwise, replace the functional op with its inplace variant.
  406. Before:
  407. b = foo(a, args...)
  408. After:
  409. a.foo_(args...)
  410. (4) Finally, after converting either:
  411. Before:
  412. b = foo(a)
  413. After:
  414. foo_(a)
  415. or
  416. Before:
  417. b = {slice}_scatter(a, mutated_slice, args...)
  418. After:
  419. slice = {slice}(a, args...)
  420. slice.copy_(mutated_slice)
  421. We now need to find all later nodes that use "b" as an argument
  422. and update them to take in "a" instead.
  423. Note that for the majority of inplace ops, this isn't actually necessary
  424. (because most inplace ops return "self" as their output).
  425. This isn't generally true for all mutable ops though, which is why
  426. we need to actually replace all of the arguments.
  427. We also need to update our metadata of Dict[StorageWeakRef, Set[Node]],
  428. That maps a given tensor storage to the set of all nodes that take in that storage
  429. as an input.
  430. Specifically, re-inplacing `b = foo(a)` causes "a" and "b"'s sets to get fused
  431. together.
  432. (5) Any "view_inverse/scatter" nodes that were identified as "it's ok to ignore them"
  433. during step (3) get manually deleted from the graph.
  434. Their outputs are no longer used, so technically standard DCE would be able
  435. to do this, but we can no longer run FX's DCE pass now that we have mutable
  436. ops in the graph.
  437. """
  438. _FunctionalizationMetadataProp(gm).propagate(*sample_args)
  439. # Useful debug printing
  440. # def _print(x):
  441. # if isinstance(x, FakeTensor):
  442. # print(f'fake_result: {StorageWeakRef(x._typed_storage()).cdata}')
  443. # for n in gm.graph.nodes:
  444. # print(n.format_node())
  445. # if hasattr(n, 'meta'):
  446. # print(f'node_idx: {n.meta["node_idx"]}')
  447. # if 'fake_result' in n.meta:
  448. # tree_map(_print, n.meta['fake_result'])
  449. # if 'view_of' in n.meta:
  450. # print(f'view_of: {str(n.meta["view_of"])}')
  451. # print()
  452. # We need to know which nodes correspond to inputs (or their aliases)
  453. # so we know not to re-inplace them.
  454. # NOTE: later, we'll need to add an optimization for fully recovering performance
  455. # on programs that mutate inputs.
  456. input_storages = {
  457. StorageWeakRef(node.meta["fake_result"]._typed_storage())
  458. for node in gm.graph.nodes
  459. if (
  460. node.op == "placeholder"
  461. and isinstance(node.meta["fake_result"], torch.Tensor)
  462. )
  463. }
  464. # We also need to know for a given node, what are all of its aliasing nodes.
  465. storage_to_nodes: dict[StorageWeakRef, set[Node]] = defaultdict(set)
  466. for n in gm.graph.nodes:
  467. if "fake_result" in n.meta:
  468. # Tree-mapping because some ops can return lists of tensors.
  469. def _add_to_map(x):
  470. if isinstance(x, FakeTensor):
  471. storage_to_nodes[StorageWeakRef(x._typed_storage())].add(n)
  472. pytree.tree_map_(_add_to_map, n.meta["fake_result"])
  473. # inplace-ify functional ops, subject to the constraints written below.
  474. all_later_view_inverse_nodes_to_delete = set()
  475. for node in gm.graph.nodes:
  476. if node.op == "call_function":
  477. # Today, the re-inplace pass on directly acts on:
  478. # - functional ops with an inplace variant
  479. # - {view}_scatter ops that can be potentially removed from the graph.
  480. # Both of these ops take in tensor first args, so filtering on this condition
  481. # makes the later code simpler.
  482. # We should revisit this at some point though, particularly when we also want
  483. # the reinplacer to be able to handle out= and mutable operators
  484. # and tensorlist first args (like `_foreach_` ops).
  485. if not isinstance(node.target, torch._ops.OpOverload):
  486. continue
  487. if len(node.target._schema.arguments) < 1:
  488. continue
  489. if type(node.target._schema.arguments[0].type) is not torch.TensorType:
  490. continue
  491. # Step 1a: Check that the self argument we're attempting to reinplace
  492. # has the same size/stride as the output.
  493. # For example, we shouldn't try to reinplace torch.add(scalar_tensor, larger_tensor)
  494. # As it would require resizing scalar_tensor.
  495. # (We could potentially swizzle this into larger_tensor.add_(scalar_tensor),
  496. # this is probably an optimization to revisit later).
  497. self_arg = node.args[0]
  498. self_flattened = pytree.tree_leaves(self_arg.meta["fake_result"])
  499. node_flattened = pytree.tree_leaves(node.meta["fake_result"])
  500. self_has_wrong_metadata = False
  501. if len(self_flattened) == len(node_flattened):
  502. for self_meta, node_meta in zip(self_flattened, node_flattened):
  503. if self_meta.numel() != node_meta.numel():
  504. self_has_wrong_metadata = True
  505. if self_meta.dtype != node_meta.dtype:
  506. self_has_wrong_metadata = True
  507. # We also cannot re-inplace on tensors that have internal memory overlap.
  508. # e.g. torch.ones(1).expand(4, 4).add_(1)
  509. if torch._debug_has_internal_overlap(self_meta) == 1:
  510. self_has_wrong_metadata = True
  511. # Here, we (optimistically) assume that a.resize(b) is valid to re-inplace,
  512. # Since users should never really be calling the functional "torch.ops.aten.resize"
  513. # op directly in their programs.
  514. if self_has_wrong_metadata and node.target != torch.ops.aten.resize.default:
  515. continue
  516. # Step 1b: ensure that the op we're trying to re-inplace isn't a program input
  517. self_arg_storage = StorageWeakRef(
  518. self_arg.meta["fake_result"]._typed_storage()
  519. )
  520. if self_arg_storage in input_storages:
  521. # TODO: later, add the optimization for handling `copy_()` calls in the graph.
  522. continue
  523. if len([x for x in node.args if x is self_arg]) > 1:
  524. # Step 1c:
  525. # Calling stuff like aten.mul_(a, a) isn't guaranteed to be sound,
  526. # so we prevent re-inplacing in this case.
  527. continue
  528. self_arg_storage = StorageWeakRef(
  529. self_arg.meta["fake_result"]._typed_storage()
  530. )
  531. self_aliases = storage_to_nodes[self_arg_storage]
  532. # First, we find all later usages of any of the aliases of self_arg.
  533. later_node_usages = _get_all_later_node_usages(
  534. self_aliases, node.meta["node_idx"]
  535. )
  536. # Then, we check if any of those later usages are actually view_scatter ops
  537. # that are safe to fully remove.
  538. later_view_inverse_node_usages = _get_view_inverse_node_usages(
  539. later_node_usages, self_aliases
  540. )
  541. # Step 2: Check to see if the input to the op is reused later in the graph.
  542. # If not (same goes for its aliases), then this op is safe to re-in place.
  543. # This is a slightly roundabout way to check that there are no later usages of the current self argument.
  544. # (later_view_inverse_node_usages corresponds to "view_scatter" nodes that we are allowed to delete)
  545. can_reinplace = len(later_node_usages - later_view_inverse_node_usages) == 0
  546. if not can_reinplace:
  547. continue
  548. # Step 3a: Special handling for when we see *_scatter operators.
  549. # When we see an operator like `b = torch.slice_scatter(a, ...)`,
  550. # instead of trying to "inplace" it into a.slice_scatter_(..._),
  551. # we would prefer to remove it from the graph entirely,
  552. # and instead copy_() the slice directly into the larger tensor.
  553. # See the description of the algorithm for a full example.
  554. if (
  555. node.target in _VIEW_INVERSE_MAP
  556. and node not in all_later_view_inverse_nodes_to_delete
  557. ):
  558. view_op = _VIEW_INVERSE_MAP[node.target]
  559. # Before:
  560. # base_updated = torch.ops.aten.slice_scatter.default(base, mutated_slice, args...)
  561. # After:
  562. # slice = torch.ops.aten.slice.default(base, args...)
  563. # slice.copy_(mutated_slice)
  564. with gm.graph.inserting_before(node):
  565. mutated_slice_node = node.args[1]
  566. remaining_slice_args = node.args[2:]
  567. slice_node = gm.graph.create_node(
  568. "call_function",
  569. view_op,
  570. (self_arg,) + tuple(remaining_slice_args),
  571. node.kwargs,
  572. )
  573. gm.graph.create_node(
  574. "call_function",
  575. torch.ops.aten.copy_.default,
  576. (
  577. slice_node,
  578. mutated_slice_node,
  579. ),
  580. {},
  581. )
  582. # Add the slice_scatter node to our "nodes to delete" list.
  583. all_later_view_inverse_nodes_to_delete.add(node)
  584. else:
  585. # Step 3b: Check to see if this operator has an inplace variant.
  586. maybe_inplace_op = _maybe_get_inplace_op(node.target)
  587. if maybe_inplace_op is None:
  588. continue
  589. # And if so, replace it with its inplace variant.
  590. node.target = maybe_inplace_op
  591. # At this point, 'storage_to_nodes' will be stale.
  592. # Now that we're inplacing `b = foo(a)`, we need to effectively
  593. # union together the dict values for b and a's storage.
  594. # Hmm... morally I think we also want to keep the `fake_result` metadata
  595. # up to date here, but I'm not sure how easy it is to do.
  596. # Maybe it's fine to wait until the end of the pass to update it.
  597. curr_node_storage = StorageWeakRef(
  598. node.meta["fake_result"]._typed_storage()
  599. )
  600. storage_to_nodes[self_arg_storage].update(
  601. storage_to_nodes[curr_node_storage]
  602. )
  603. storage_to_nodes[curr_node_storage].update(
  604. storage_to_nodes[self_arg_storage]
  605. )
  606. # Need to remember the view_scatter view nodes we found so we can remove them alter.
  607. all_later_view_inverse_nodes_to_delete.update(
  608. later_view_inverse_node_usages
  609. )
  610. # Step 4:
  611. # Now that we've replaced b = a.foo() with a.foo_(),
  612. # We need to replace any later usages of "b" with "a"
  613. for old in itertools.chain([node], later_view_inverse_node_usages):
  614. new = old.args[0]
  615. nodes_to_update = [
  616. n for n in old.users if n.meta["node_idx"] > node.meta["node_idx"]
  617. ]
  618. for node_to_update in nodes_to_update:
  619. def replace_arg(a):
  620. if a == old:
  621. return new
  622. return a
  623. # First, replace usages of "b" with "a"
  624. node_to_update.args = tree_map_only(
  625. Node, replace_arg, node_to_update.args
  626. )
  627. node_to_update.kwargs = tree_map_only(
  628. Node, replace_arg, node_to_update.kwargs
  629. )
  630. # Second, update our storage_to_nodes data structure.
  631. old_flattened_res = pytree.tree_leaves(old.meta["fake_result"])
  632. node_flattened_res = pytree.tree_leaves(
  633. node_to_update.meta["fake_result"]
  634. )
  635. old_res_storage = {
  636. StorageWeakRef(x._typed_storage())
  637. for x in old_flattened_res
  638. if isinstance(x, FakeTensor)
  639. }
  640. node_res_storage = {
  641. StorageWeakRef(x._typed_storage())
  642. for x in node_flattened_res
  643. if isinstance(x, FakeTensor)
  644. }
  645. # This will happen if we're updating a view op, e.g.
  646. # e.g. replacing
  647. # x = view(old)
  648. # x = view(new)
  649. # When that happens, we need to make sure to keep our
  650. # storage mapping up to date.
  651. #
  652. # We're checking for len(...) == 1 here because all view ops are guaranteed to return either a single tensor,
  653. # or multiple tensors that all share the same storage.
  654. # We can't just check equality because we might encounter FX nodes that return zero tensor outputs.
  655. if (
  656. len(old_res_storage) == 1
  657. and len(node_res_storage) == 1
  658. and old_res_storage == node_res_storage
  659. ):
  660. new_flattened_res = pytree.tree_leaves(new.meta["fake_result"])
  661. new_res_storage = {
  662. StorageWeakRef(x._typed_storage())
  663. for x in new_flattened_res
  664. if isinstance(x, FakeTensor)
  665. }
  666. if len(new_res_storage) != 1:
  667. raise AssertionError(
  668. f"Expected 1 storage, got {len(new_res_storage)}"
  669. )
  670. (new_ref,) = new_res_storage
  671. (node_ref,) = node_res_storage
  672. # Technically, "old_ref" and all its aliases will remain
  673. # in our mapping.
  674. # That should be fine though, since we deleted "old"
  675. # from the graph at this point.
  676. storage_to_nodes[node_ref].update(storage_to_nodes[new_ref])
  677. storage_to_nodes[new_ref].update(storage_to_nodes[node_ref])
  678. # Step 4: delete any _scatter nodes that we de-functionalized
  679. # Need to take care not to delete any of these nodes until after *all* modifications
  680. # to the graph are finished.
  681. for to_delete in all_later_view_inverse_nodes_to_delete:
  682. gm.graph.erase_node(to_delete)
  683. gm.recompile()
  684. return gm