_python_dispatch.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. # mypy: allow-untyped-defs
  2. import contextlib
  3. import functools
  4. import warnings
  5. from collections import deque
  6. from collections.abc import Sequence
  7. from dataclasses import dataclass
  8. from typing import Optional, overload, Protocol, Union
  9. from typing_extensions import TypeIs
  10. import torch
  11. import torchgen
  12. import torchgen.model
  13. from torch._C import (
  14. _get_dispatch_stack_at,
  15. _len_torch_dispatch_stack,
  16. _pop_torch_dispatch_stack,
  17. _push_on_torch_dispatch_stack,
  18. DispatchKey,
  19. )
  20. # TODO: Limitations and things about enable_torch_dispatch_mode we should fix before exposing it:
  21. # - We need a better user-facing api for _DisableTorchDispatch that
  22. # is able to selectively disable __torch_dispatch__ of a particular class.
  23. # - It doesn't work with the tensor constructors (torch.tensor, torch.Tensor)
  24. # - Better name (see https://github.com/pytorch/pytorch/pull/63496#discussion_r694091694)
  25. _is_in_torch_dispatch_mode = False
  26. _is_in_non_infra_torch_dispatch_mode = False
  27. # If inside any mode that has ignore_compile_internals() = False
  28. _is_in_any_mode_without_ignore_compile_internals = False
  29. def is_in_torch_dispatch_mode(include_infra_modes=True) -> bool:
  30. return (
  31. _is_in_torch_dispatch_mode
  32. if include_infra_modes
  33. else _is_in_non_infra_torch_dispatch_mode
  34. )
  35. def is_in_any_mode_without_ignore_compile_internals() -> bool:
  36. return _is_in_any_mode_without_ignore_compile_internals
  37. class TorchDispatchMode:
  38. """
  39. A ``TorchDispatchMode`` allows you to override the meaning of all
  40. ``__torch_dispatch__`` overrideable functions within a dynamic scope,
  41. without having to actually create a tensor subclass or manually
  42. monkey-patch functions in the PyTorch API. Some common situations
  43. where you should use a mode:
  44. * You want to override the meaning of factory functions, or other
  45. functions that do not otherwise take a tensor as an argument
  46. (these cannot be overridden with tensor subclasses).
  47. * You want to override the behavior of all functions without needing
  48. to wrap your inputs in tensor subclasses; e.g., if you are just
  49. interested in logging intermediate computations.
  50. * You want to control the order of execution of various tensor
  51. subclasses explicitly, rather than implicitly via the return of
  52. ``NotImplemented``.
  53. Independent subclasses of :class:`TorchDispatchMode` are compositional:
  54. modes can be pushed onto a stack using ``with MyMode():``.
  55. When you call functions in the PyTorch API inside your
  56. ``__torch_dispatch__`` implementation, by default, they will forward on to
  57. the next mode on the mode stack. If you want recursively call back into
  58. your current ``__torch_dispatch__`` implementation, either explicitly
  59. invoke ``self.__torch_dispatch__(...)``, or use the context manager
  60. ``__torch_dispatch__(self)`` to make PyTorch
  61. API self-referential (beware of infinite loops, in this case!)
  62. """
  63. # - When False, custom torch dispatch mode will error out explicitly when a hop
  64. # is called under the mode.
  65. # - When True, custom torch dispatch mode's __torch_dispatch__ will be triggered.
  66. # Mode authors can implement how the mode interacts with higher order operators.
  67. supports_higher_order_operators = False
  68. def __init__(self, _dispatch_key=None):
  69. if _dispatch_key is not None:
  70. assert isinstance(_dispatch_key, torch._C.DispatchKey)
  71. self.__dict__["_dispatch_key"] = _dispatch_key
  72. self.old_dispatch_mode_flags: deque[bool] = deque()
  73. self.old_non_infra_dispatch_mode_flags: deque[bool] = deque()
  74. self.old_without_ignore_compile_internals_dispatch_mode_flags: deque[bool] = (
  75. deque()
  76. )
  77. def _lazy_init_old_dispatch_mode_flags(self):
  78. if not hasattr(self, "old_dispatch_mode_flags"):
  79. self.old_dispatch_mode_flags: deque[bool] = deque() # type: ignore[no-redef]
  80. if not hasattr(self, "old_non_infra_dispatch_mode_flags"):
  81. self.old_non_infra_dispatch_mode_flags: deque[bool] = deque() # type: ignore[no-redef]
  82. if not hasattr(
  83. self, "old_without_ignore_compile_internals_dispatch_mode_flags"
  84. ):
  85. self.old_without_ignore_compile_internals_dispatch_mode_flags: deque[ # type: ignore[no-redef]
  86. bool
  87. ] = deque()
  88. def __torch_dispatch__(self, func, types, args=(), kwargs=None):
  89. raise NotImplementedError
  90. def __enter__(self):
  91. global _is_in_torch_dispatch_mode
  92. global _is_in_non_infra_torch_dispatch_mode
  93. global _is_in_any_mode_without_ignore_compile_internals
  94. # Previously, there wasn't any state in this class' constructor
  95. # super calls were added to existing modes, but for any new modes
  96. # this will replicate the previous behavior of not strictly needing
  97. # to call super().__init__()
  98. self._lazy_init_old_dispatch_mode_flags()
  99. self.old_dispatch_mode_flags.append(_is_in_torch_dispatch_mode)
  100. _is_in_torch_dispatch_mode = True
  101. self.old_non_infra_dispatch_mode_flags.append(
  102. _is_in_non_infra_torch_dispatch_mode
  103. )
  104. _is_in_non_infra_torch_dispatch_mode = (
  105. _is_in_non_infra_torch_dispatch_mode or not self.is_infra_mode()
  106. )
  107. self.old_without_ignore_compile_internals_dispatch_mode_flags.append(
  108. _is_in_any_mode_without_ignore_compile_internals
  109. )
  110. _is_in_any_mode_without_ignore_compile_internals = (
  111. _is_in_any_mode_without_ignore_compile_internals
  112. or not self.ignore_compile_internals()
  113. )
  114. _push_mode(self)
  115. return self
  116. def __exit__(self, exc_type, exc_val, exc_tb):
  117. mb_dk_or_mode_key = self.__dict__.get("_dispatch_key", None)
  118. if mb_dk_or_mode_key is None:
  119. # Today, mode keys are not used at all in the per-dispatch-key-mode logic (for pre-dispatch)
  120. # We should probably revisit this.
  121. mb_dk_or_mode_key = self.__dict__.get("_mode_key", None)
  122. global _is_in_torch_dispatch_mode
  123. _is_in_torch_dispatch_mode = self.old_dispatch_mode_flags.pop()
  124. global _is_in_non_infra_torch_dispatch_mode
  125. _is_in_non_infra_torch_dispatch_mode = (
  126. self.old_non_infra_dispatch_mode_flags.pop()
  127. )
  128. global _is_in_any_mode_without_ignore_compile_internals
  129. _is_in_any_mode_without_ignore_compile_internals = (
  130. self.old_without_ignore_compile_internals_dispatch_mode_flags.pop()
  131. )
  132. _pop_mode(mb_dk_or_mode_key)
  133. @classmethod
  134. def push(cls, *args, **kwargs):
  135. warnings.warn(
  136. "`Mode.push()` is no longer necessary and can be replaced with just `with Mode()`"
  137. )
  138. instance = cls(*args, **kwargs)
  139. return instance
  140. @classmethod
  141. def is_infra_mode(cls):
  142. return False
  143. @classmethod
  144. def ignore_compile_internals(cls):
  145. """Ignore operators that are compiled via torch.compile.
  146. If ``True``, then this TorchDispatchMode ignores operators that
  147. are optimized by :func:`torch.compile`. Mechanically, this involves
  148. turning off the TorchDispatchMode throughout the whole compilation process,
  149. and turning it back on for the runtime of the compiled artifact(s).
  150. For example,
  151. @torch.compile
  152. def f(x):
  153. return x.sin().cos()
  154. with LoggingMode():
  155. f(x)
  156. The above example will not log anything if
  157. ``LoggingMode.ignore_compile_internals()`` is True.
  158. torch.compile will fuse sin() and cos() into a single operation
  159. and this TorchDispatchMode will not be passed sin and cos.
  160. If ``False`` (default), :func:`torch.compile` will respect
  161. the eager semantics of passing this TorchDispatchMode all
  162. operators that would have run during eager execution.
  163. The way this will usually happen is that :func:`torch.compile`
  164. will just fallback to eager-mode PyTorch.
  165. """
  166. if cls.is_infra_mode():
  167. return True
  168. return False
  169. def _get_current_dispatch_mode():
  170. stack_len = _len_torch_dispatch_stack()
  171. # Return a user mode on the stack if there are any
  172. if stack_len > 0:
  173. return _get_dispatch_stack_at(stack_len - 1)
  174. return None
  175. def _detect_infra_mode(key):
  176. assert key in [
  177. torch._C._TorchDispatchModeKey.FUNCTIONAL,
  178. torch._C._TorchDispatchModeKey.PROXY,
  179. ]
  180. from torch._ops import _get_dispatch_mode_pre_dispatch
  181. pre_dispatch_mode = _get_dispatch_mode_pre_dispatch(key)
  182. post_dispatch_mode = torch._C._get_dispatch_mode(key)
  183. assert (pre_dispatch_mode is None) or (post_dispatch_mode is None)
  184. if pre_dispatch_mode is None:
  185. return post_dispatch_mode
  186. return pre_dispatch_mode
  187. def _unset_infra_mode(key):
  188. from torch._ops import _get_dispatch_mode_pre_dispatch, unset_mode_pre_dispatch
  189. pre_dispatch_mode = _get_dispatch_mode_pre_dispatch(key)
  190. post_dispatch_mode = torch._C._get_dispatch_mode(key)
  191. if pre_dispatch_mode and post_dispatch_mode:
  192. raise AssertionError(
  193. "Can't have active infra mode on both pre and post dispatch mode stack"
  194. )
  195. if pre_dispatch_mode:
  196. mode = unset_mode_pre_dispatch(key)
  197. return mode
  198. if post_dispatch_mode:
  199. return torch._C._unset_dispatch_mode(key)
  200. def _disable_infra_mode(key):
  201. assert key in (
  202. torch._C._TorchDispatchModeKey.FUNCTIONAL,
  203. torch._C._TorchDispatchModeKey.PROXY,
  204. )
  205. mode_unset = _unset_infra_mode(key)
  206. try:
  207. yield mode_unset
  208. finally:
  209. if mode_unset is not None:
  210. _push_mode(mode_unset)
  211. def _get_current_dispatch_mode_stack():
  212. stack_len = _len_torch_dispatch_stack()
  213. return [_get_dispatch_stack_at(i) for i in range(stack_len)]
  214. def _push_mode(mode: TorchDispatchMode):
  215. k = mode._dispatch_key if hasattr(mode, "_dispatch_key") else None
  216. assert k is None or k == torch._C.DispatchKey.PreDispatch
  217. if k is None:
  218. _push_on_torch_dispatch_stack(mode)
  219. return
  220. from torch._ops import _set_mode_pre_dispatch, get_cached_ops
  221. # See Note [Not Caching Per-Dispatch-Key Mode Handlers]
  222. # Clear the cache of every op that has been used so far, for this particular key.
  223. ks = torch._C._functionality_to_backend_keys(k)
  224. for op in get_cached_ops():
  225. for key in ks:
  226. op._uncache_dispatch(key)
  227. _set_mode_pre_dispatch(mode)
  228. def _pop_mode(k: Optional[Union[DispatchKey, torch._C._TorchDispatchModeKey]] = None):
  229. if k == torch._C.DispatchKey.PreDispatch: # type: ignore[attr-defined]
  230. from torch._ops import _pop_mode_from_pre_dispatch
  231. return _pop_mode_from_pre_dispatch()
  232. if k is None or isinstance(k, torch._C._TorchDispatchModeKey):
  233. return _pop_torch_dispatch_stack(k)
  234. @contextlib.contextmanager
  235. def _pop_mode_temporarily(k: Optional[DispatchKey] = None):
  236. old = _pop_mode(k)
  237. try:
  238. yield old
  239. finally:
  240. _push_mode(old)
  241. @contextlib.contextmanager
  242. def _disable_current_modes():
  243. from torch._ops import (
  244. _len_torch_dispatch_stack_pre_dispatch,
  245. _pop_mode_from_pre_dispatch,
  246. )
  247. from torch._subclasses.functional_tensor import FunctionalTensorMode
  248. from torch._subclasses.schema_check_mode import SchemaCheckMode
  249. from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode
  250. mode_len_pre_dispatch = _len_torch_dispatch_stack_pre_dispatch()
  251. old_pre_dispatch_modes = [
  252. _pop_mode_from_pre_dispatch() for _ in range(mode_len_pre_dispatch)
  253. ]
  254. has_proxy_mode_in_pre_dispatch = False
  255. has_functional_mode_in_pre_dispatch = False
  256. has_schema_check_mode_in_pre_dispatch = False
  257. for i in old_pre_dispatch_modes:
  258. if isinstance(i, ProxyTorchDispatchMode):
  259. has_proxy_mode_in_pre_dispatch = True
  260. if isinstance(i, FunctionalTensorMode):
  261. has_functional_mode_in_pre_dispatch = True
  262. if isinstance(i, SchemaCheckMode):
  263. has_schema_check_mode_in_pre_dispatch = True
  264. mode_len = _len_torch_dispatch_stack()
  265. old_modes = [_pop_mode() for _ in range(mode_len)]
  266. for old in old_modes:
  267. if (
  268. isinstance(old, FunctionalTensorMode)
  269. and has_functional_mode_in_pre_dispatch
  270. ):
  271. raise AssertionError(
  272. "Can't have FunctionalMode available both in PreDispatch and Python Key"
  273. )
  274. if isinstance(old, ProxyTorchDispatchMode) and has_proxy_mode_in_pre_dispatch:
  275. raise AssertionError(
  276. "Can't have ProxyTorchDispatchMode available both in PreDispatch and Python Key"
  277. )
  278. if isinstance(old, SchemaCheckMode) and has_schema_check_mode_in_pre_dispatch:
  279. raise AssertionError(
  280. "Can't have SchemaCheckMode available both in PreDispatch and Python Key"
  281. )
  282. # Manually disable proxy and fake modes, if any are active
  283. try:
  284. yield old_pre_dispatch_modes + old_modes
  285. finally:
  286. for mode in reversed(old_modes):
  287. _push_mode(mode)
  288. for mode in reversed(old_pre_dispatch_modes):
  289. _push_mode(mode)
  290. class BaseTorchDispatchMode(TorchDispatchMode):
  291. def __torch_dispatch__(self, func, types, args=(), kwargs=None):
  292. if kwargs is None:
  293. kwargs = {}
  294. return func(*args, **kwargs)
  295. # Subtypes which have __tensor_flatten__ and __tensor_unflatten__.
  296. class TensorWithFlatten(Protocol):
  297. def __tensor_flatten__(self) -> tuple[Sequence[str], object]: ...
  298. @staticmethod
  299. def __tensor_unflatten__(
  300. inner_tensors: int, flatten_spec: int, outer_size: int, outer_stride: int
  301. ) -> torch.Tensor: ...
  302. # It would be really nice to be able to say that the return of
  303. # is_traceable_wrapper_subclass() is Intersection[torch.Tensor,
  304. # TensorWithFlatten] - but that doesn't exist.
  305. shape: torch._C.Size
  306. @overload
  307. def stride(self, dim: None = None) -> tuple[int, ...]: ...
  308. @overload
  309. def stride(self, dim: int) -> int: ...
  310. @overload
  311. def size(self, dim: None = None) -> tuple[int, ...]: ...
  312. @overload
  313. def size(self, dim: int) -> int: ...
  314. def storage_offset(self) -> int: ...
  315. def dim(self) -> int: ...
  316. @overload
  317. def to(
  318. self,
  319. dtype: torch.types._dtype,
  320. non_blocking: bool = False,
  321. copy: bool = False,
  322. *,
  323. memory_format: Optional[torch.memory_format] = None,
  324. ) -> torch.Tensor: ...
  325. @overload
  326. def to(
  327. self,
  328. device: Optional["torch._prims_common.DeviceLikeType"] = None,
  329. dtype: Optional[torch.types._dtype] = None,
  330. non_blocking: bool = False,
  331. copy: bool = False,
  332. *,
  333. memory_format: Optional[torch.memory_format] = None,
  334. ) -> torch.Tensor: ...
  335. @overload
  336. def to(
  337. self,
  338. other: torch.Tensor,
  339. non_blocking: bool = False,
  340. copy: bool = False,
  341. *,
  342. memory_format: Optional[torch.memory_format] = None,
  343. ) -> torch.Tensor: ...
  344. def is_traceable_wrapper_subclass(t: object) -> TypeIs[TensorWithFlatten]:
  345. """
  346. Returns whether or not a tensor subclass that implements __torch_dispatch__
  347. is 'traceable' with torch.compile.
  348. In order for a tensor subclass to support TorchDispatchMode-style tracing in PT2,
  349. It must implement two magic methods: __tensor_flatten__ and __tensor_unflatten__.
  350. It is also expected to obey some restrictions around traceability and aliasing:
  351. * The subclass's __torch_dispatch__() implementation should desugar into pytorch
  352. dispatcher operations that can be traced into a graph.
  353. * The subclass should use return_and_correct_aliasing(). This is needed today to make
  354. sure that torch.compile does the right thing in a few cases around input mutation
  355. and output aliasing.
  356. Expected magic method signatures:
  357. attrs, ctx = t.__tensor_flatten__()
  358. attrs: list of attribute name strings for inner tensors
  359. ctx: dict containing any other subclass-specific metadata needed for unflattening
  360. t = MySubClass.__tensor_unflatten__(inner_tensors, ctx, outer_size, outer_stride)
  361. inner_tensors: dict mapping attribute name -> tensor for each inner tensor
  362. ctx: dict with subclass metadata in the form that __tensor_flatten__() produces
  363. outer_size: expected (possibly symbolic) size that the returned subclass
  364. instance should have. Note that this arg is useful for certain subclasses
  365. that require the shape info to be constructed. In most cases, this arg can be
  366. safely ignored.
  367. outer_stride: expected (possibly symbolic) stride that the returned subclass
  368. instance should have. Note that this arg is useful for certain subclasses
  369. that require the stride info to be constructed. In most cases, this arg can be
  370. safely ignored.
  371. """
  372. is_subclass = isinstance(t, torch.Tensor) and type(t) is not torch.Tensor
  373. return (
  374. is_subclass
  375. and hasattr(t, "__tensor_flatten__")
  376. and hasattr(t, "__tensor_unflatten__")
  377. )
  378. def is_traceable_wrapper_subclass_type(t: type) -> TypeIs[type[TensorWithFlatten]]:
  379. """Same as above, but takes a type argument instead of an instance."""
  380. return (
  381. issubclass(t, torch.Tensor)
  382. and t is not torch.Tensor
  383. and hasattr(t, "__tensor_flatten__")
  384. and hasattr(t, "__tensor_unflatten__")
  385. )
  386. def transform_subclass(t, callback, outer_size=None, outer_stride=None):
  387. """
  388. Given a traceable, wrapper tensor subclass ``t`` that implements
  389. ``__torch_dispatch__`` and holds some inner tensors,
  390. and a callback of type ``Callable[[str, torch.Tensor], torch.Tensor]``,
  391. `transform_subclass` will construct a fresh instance of the wrapper tensor subclass.
  392. It will do so by grabbing each inner tensor attribute from the wrapper,
  393. passing them into ``callback`` to get a transformed tensor,
  394. and putting each transformed tensor into the fresh tensor subclass instance.
  395. Note: this function will not handle ensuring that the fresh subclass
  396. gets the same (autograd, and aliasing) metadata as the original tensor.
  397. This is generally handled in other subsystems like AOTAutograd.
  398. """
  399. outer_size = outer_size if outer_size is not None else t.size()
  400. outer_stride = outer_stride if outer_stride is not None else t.stride()
  401. attrs, ctx = t.__tensor_flatten__()
  402. transformed_tensors_dict = {}
  403. for attr in attrs:
  404. transformed_tensors_dict[attr] = callback(attr, getattr(t, attr))
  405. sub = type(t).__tensor_unflatten__(
  406. transformed_tensors_dict, ctx, outer_size, outer_stride
  407. )
  408. # NB: Purposefully guard here to simplify the inner / outer symbols.
  409. # Using sym_eq() for symbolic comparison can result in an expression that's too
  410. # difficult to guard on, so we use == here.
  411. assert sub.shape == outer_size, (
  412. f"Expected return value from {type(t)}__tensor_unflatten__() to have "
  413. f"shape equal to {outer_size}, but got: {sub.shape}"
  414. )
  415. assert sub.stride() == outer_stride, (
  416. f"Expected return value from {type(t)}__tensor_unflatten__() to have "
  417. f"stride equal to {outer_stride}, but got: {sub.stride()}"
  418. )
  419. return sub
  420. def _correct_storage_aliasing(func, schema_info, args, outs):
  421. """
  422. Given: an OpOverload, a SchemaInfo (cached information from torchgen about schema),
  423. and the inputs/outputs to the OpOverload,
  424. this function checks to see if func is a view operator
  425. (by checking if any of the outputs in the op's schema
  426. are immutable aliases of inputs).
  427. If so, this function manually aliases the storage of the output tensor
  428. with its corresponding input tensor alias.
  429. It does this by unsafely overwriting the storage field of the output tensor
  430. to be the same storage as the input.
  431. """
  432. assert isinstance(func, torch._ops.OpOverload)
  433. assert isinstance(args, tuple)
  434. assert isinstance(outs, (list, tuple))
  435. def alias_non_inplace_storage(arg, ret):
  436. # This is hopefully a reasonable assert:
  437. # subclasses that rely on this API for output aliasing
  438. # should always return wrapper tensor subclasses for us to manually alias.
  439. # in theory if a subclass that needs this API wants to sometimes return
  440. # plain tensors, we could remove the assert and just not perform the aliasing,
  441. # but it seems safer to learn more about this case first.
  442. #
  443. # Performance note: This is all just to assert that the argument and result
  444. # types match, checking that is cheaper than is_traceable_wrapper_subclass_type,
  445. # and multiple returns are relatively unlikely, so just check up front!
  446. arg_type = type(arg)
  447. ret_type = type(ret)
  448. if arg_type is not ret_type and (
  449. is_traceable_wrapper_subclass_type(arg_type)
  450. or is_traceable_wrapper_subclass_type(ret_type)
  451. ):
  452. ret_list = ret if isinstance(ret, list) else [ret]
  453. for r in ret_list:
  454. assert type(arg) == type(
  455. r
  456. ), f"""Called {str(func)} with input of type {type(arg)}
  457. and output of type {type(ret)}. But expected types to match."""
  458. # Need to call a non-dispatcher helper, because we explicitly do **not**
  459. # want our subclass to intercept the set_() call.
  460. # instead, our subclass should directly have its storage swapped out.
  461. # we **explicitly** don't want to reset the sizes on ret, if the storage implies a size change.
  462. # Why?
  463. # The purpose of this API is *not* to change the size/strides of our output- we assume it's already correct.
  464. # We just want to "fix up" the storage aliasing, without modifying or output's metadata.
  465. # Example: out = inp.expand(inp.shape[0], inp.shape[0])
  466. # This requires swapping the storage of out to be the same as inp,
  467. # but we do *not* want it to change the sizes/strides that were compute for out.
  468. if isinstance(ret, list):
  469. for r in ret:
  470. torch._functionalize_unsafe_set(r, arg)
  471. else:
  472. assert isinstance(ret, torch.Tensor), f"type: {type(ret)}"
  473. torch._functionalize_unsafe_set(ret, arg)
  474. for arg_idx, schema_arg in enumerate(schema_info.args):
  475. for return_idx, schema_out in enumerate(schema_info.outs):
  476. is_read_only_alias_match = (
  477. schema_arg.alias_set & schema_out.alias_set
  478. ) and not schema_arg.is_write
  479. if is_read_only_alias_match:
  480. alias_non_inplace_storage(args[arg_idx], outs[return_idx])
  481. # This abstracts over the fact that in return_and_correct_aliasing,
  482. # we sometimes use torchgen schema parsing (for aten ops, since torchscript's schema parsing is sometimes buggy),
  483. # and sometimes use torchscript schema parsing (for custom ops, for which torchgen parsing is untested).
  484. @dataclass
  485. class AliasInfo:
  486. alias_set: set[str]
  487. is_write: bool
  488. name: Optional[str]
  489. @dataclass
  490. class SchemaInfo:
  491. args: list[AliasInfo]
  492. outs: list[AliasInfo]
  493. # NOTE[SchemaInfo int_tags]: This has nothing to do with aliasing, but we take
  494. # advantage of our existing caching of data for each OpOverload to paper over an
  495. # efficiency problem with pybind11::enum_ (which currently is used to implement
  496. # torch.Tag): a scan over a list of pybind enums using `in` is inefficient because
  497. # each element must be converted to int with the __int__ method, which incurs a lot
  498. # of overhead. Converting to int once and caching removes this per-op overhead.
  499. int_tags: list[int]
  500. # Given an OpOverload, returns schema information on it.
  501. # This is cached for efficiency, since it can involve running torchgen
  502. @functools.cache
  503. def get_alias_info(func) -> SchemaInfo:
  504. # For ATen ops: use torchgen (since torchscript parser doesn't handle alias annotations
  505. # properly for some ops that output tensorlists)
  506. if func.namespace == "aten":
  507. torchgen_schema_str = str(func._schema)
  508. assert torchgen_schema_str.startswith("aten::")
  509. # remove the aten:: namespace, which is added by the torchscript parser,
  510. # and torchgen doesn't know how to handle
  511. torchgen_schema_str = torchgen_schema_str[6:]
  512. import re
  513. # the torchscript parser ends up converting int[2]=1 into int[2]=[1, 1],
  514. # which torchgen chokes on.
  515. torchgen_schema_str = re.sub(r"=\[[0, ]+\]", "=0", torchgen_schema_str)
  516. torchgen_schema_str = re.sub(r"=\[[1, ]+\]", "=1", torchgen_schema_str)
  517. # for aten::rot90 / aten:fft_*
  518. torchgen_schema_str = re.sub(
  519. r"=\[(-?[0-9]+), (-?[0-9]+)\]", r"=[\1,\2]", torchgen_schema_str
  520. )
  521. torchgen_schema = torchgen.model.FunctionSchema.parse(torchgen_schema_str)
  522. arg_schemas = [
  523. AliasInfo(
  524. alias_set=(
  525. set() if a.annotation is None else set(a.annotation.alias_set)
  526. ),
  527. is_write=a.annotation is not None and a.annotation.is_write,
  528. name=a.name,
  529. )
  530. for a in torchgen_schema.arguments.flat_all
  531. ]
  532. out_schemas = [
  533. AliasInfo(
  534. alias_set=(
  535. set() if a.annotation is None else set(a.annotation.alias_set)
  536. ),
  537. is_write=a.annotation is not None and a.annotation.is_write,
  538. name=a.name,
  539. )
  540. for a in torchgen_schema.returns
  541. ]
  542. else:
  543. # For non-aten ops, torchgen is untested so we rely on torchscript schema parsing
  544. arg_schemas = [
  545. AliasInfo(
  546. alias_set=(
  547. set() if a.alias_info is None else set(a.alias_info.before_set)
  548. ),
  549. is_write=a.alias_info is not None and a.alias_info.is_write,
  550. name=a.name,
  551. )
  552. for a in func._schema.arguments
  553. ]
  554. out_schemas = [
  555. AliasInfo(
  556. alias_set=(
  557. set() if a.alias_info is None else set(a.alias_info.before_set)
  558. ),
  559. is_write=a.alias_info is not None and a.alias_info.is_write,
  560. name=a.name,
  561. )
  562. for a in func._schema.returns
  563. ]
  564. schema_info = SchemaInfo(
  565. args=arg_schemas, outs=out_schemas, int_tags=[int(x) for x in func.tags]
  566. )
  567. return schema_info
  568. # See NOTE[SchemaInfo int_tags] above.
  569. _TORCH_TAG_INPLACE_VIEW_INT = int(torch.Tag.inplace_view) # type: ignore[call-overload]
  570. def return_and_correct_aliasing(func, args, kwargs, out):
  571. """
  572. This function should be used by wrapper tensor ``__torch_dispatch__`` subclasses
  573. that would like to work with torch.compile. It ensures that the subclass
  574. properly implements the aliasing behavior of every op,
  575. which is needed for correctness in AOTAutograd.
  576. This function will handle:
  577. * When we see a view op, we will alias the storages of any
  578. input and output tensor subclasses
  579. * When we see an inplace or out= op, we will directly
  580. return the corresponding input tensor, instead of returning
  581. a (potentially) fresh output tensor.
  582. """
  583. # Caching here because torchgen parsing is definitely not fast, and this function is called
  584. # once for every op in the graph during functionalization.
  585. schema_info = get_alias_info(func)
  586. def get_write_alias(x):
  587. alias_set = x.alias_set
  588. if not alias_set or not x.is_write:
  589. return None
  590. # torchscript allows for complicated alias sets, but our dispatcher ops only really involve simple aliasing
  591. assert len(alias_set) == 1
  592. # timeit says next(iter(alias_set)) is faster than list(alias_set)[0] even for
  593. # set of size 1 on Python 3.13.
  594. return next(iter(alias_set))
  595. def get_arg_from_alias(output_alias, schema_info, args, kwargs):
  596. new_args, new_kwargs = torch.fx.operator_schemas.normalize_function( # type: ignore[misc]
  597. func, args=args, kwargs=kwargs
  598. )
  599. arg_indices = [
  600. i for i, a in enumerate(schema_info.args) if output_alias in a.alias_set
  601. ]
  602. # For any dispatcher op with an output alias, we expect it to map to exactly one alias in the schema's input arguments.
  603. assert len(arg_indices) == 1
  604. idx = arg_indices[0]
  605. arg_info = schema_info.args[idx]
  606. if arg_info.name is not None and arg_info.name in new_kwargs:
  607. return new_kwargs[arg_info.name]
  608. return new_args[idx]
  609. # Fix up the storages of any outs so that they point to the same storage as the input,
  610. # if func is a view op.
  611. _correct_storage_aliasing(
  612. func, schema_info, args, (out,) if not isinstance(out, tuple) else out
  613. )
  614. # For inplace_view ops in particular, we'll try hard to make sure that the wrapper subclass's
  615. # metadata is set correctly.
  616. # See NOTE[SchemaInfo int_tags] above.
  617. if _TORCH_TAG_INPLACE_VIEW_INT in schema_info.int_tags:
  618. # no_dispatch() to make sure that we secretly change the metadata on the wrapper,
  619. # but don't end up dispatching the op anywhere else.
  620. mutated_args = [
  621. x
  622. for i, x in enumerate(args)
  623. if get_write_alias(schema_info.args[i]) is not None
  624. ]
  625. # Assumption: we have a very small number of inplace_view ops that follow a strict schema:
  626. # there is only a single argument that gets its metadata mutated.
  627. assert len(mutated_args) == 1
  628. # This check exists because we generally *do* want to update the metadata of any wrapper subclasses,
  629. # but FunctionalTensor is special: it overrides all size/stride calls to plumb to the inner tensor.
  630. # so we don't actually need to update the metadata (and attempting to do so causes errors)
  631. from torch._subclasses.functional_tensor import FunctionalTensor
  632. if not isinstance(mutated_args[0], FunctionalTensor):
  633. with torch.utils._mode_utils.no_dispatch():
  634. # See Note: [Fake Tensor Dispatch Keys]
  635. # we're borrowing the way it modifies dispatch key TLS.
  636. meta_in_tls = torch._C._meta_in_tls_dispatch_include()
  637. torch._C._set_meta_in_tls_dispatch_include(True)
  638. try:
  639. func(*args, **kwargs)
  640. finally:
  641. torch._C._set_meta_in_tls_dispatch_include(meta_in_tls)
  642. # Next: we need to make sure to return inputs directly, if the output is a mutable alias (e.g. add_()).
  643. # Compute write aliases once instead of repeatedly.
  644. schema_info_outs_write_aliases = [get_write_alias(r) for r in schema_info.outs]
  645. # simple case: none of our outputs have mutable aliases, so we can return the output as-is
  646. if not any(x is not None for x in schema_info_outs_write_aliases):
  647. return out
  648. # simplifying assumption: we don't have **any** ops with return types like "-> (Tensor(a!), Tensor)"
  649. if not all(x is not None for x in schema_info_outs_write_aliases):
  650. raise RuntimeError("Unsupported schema: " + str(func._schema))
  651. if len(schema_info_outs_write_aliases) == 1:
  652. return get_arg_from_alias(
  653. schema_info_outs_write_aliases[0], schema_info, args, kwargs
  654. )
  655. # In the multi-return case, all aten ops return a tuple / list, so cast accordingly.
  656. outs_to_return = type(out)(
  657. [
  658. (get_arg_from_alias(write_alias, schema_info, args, kwargs))
  659. for write_alias in schema_info_outs_write_aliases
  660. ]
  661. )
  662. return outs_to_return