python.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. # mypy: allow-untyped-defs
  2. import itertools
  3. import unittest.mock
  4. from collections.abc import Iterator
  5. from contextlib import contextmanager
  6. from typing import Callable, TypeVar, Union
  7. from typing_extensions import ParamSpec
  8. import torch
  9. import torch._C
  10. import torch._ops
  11. import torch.utils._python_dispatch
  12. import torch.utils._pytree as pytree
  13. from torch._C import DispatchKey
  14. __all__ = ["enable_python_dispatcher", "no_python_dispatcher", "enable_pre_dispatch"]
  15. no_python_dispatcher = torch._C._DisablePythonDispatcher
  16. enable_python_dispatcher = torch._C._EnablePythonDispatcher
  17. enable_pre_dispatch = torch._C._EnablePreDispatch
  18. CROSSREF_FUNCTIONALIZE = False
  19. _P = ParamSpec("_P")
  20. _T = TypeVar("_T")
  21. def all_py_loaded_overloads() -> Iterator[torch._ops.OpOverload]:
  22. """
  23. Warning: the set of overloads this will report is very subtle. It is precisely
  24. the set of torch.ops functions that have actually been accessed from Python
  25. (e.g., we actually called torch.ops.aten.blah at some point. This is DIFFERENT
  26. from the set of registered operators, which will in general be a larger set,
  27. as this would include all operators which we ran C++ static initializers or
  28. Python operator registration on. This does not eagerly populate the list on
  29. torch.ops.aten; this list is lazy!
  30. In other words, this is good for traversing over everything that has an
  31. OpOverload object allocated in Python. We use it for cache invalidation, but
  32. don't rely on this list being complete.
  33. Note that even if we did report all C++ registered overloads, this isn't guaranteed
  34. to be complete either, as a subsequent lazy load of a library which triggers more
  35. registrations could add more things to the set.
  36. """
  37. for ns in torch.ops:
  38. packets = getattr(torch.ops, ns)
  39. for op_name in packets:
  40. packet = getattr(packets, op_name)
  41. for overload in packet:
  42. yield getattr(packet, overload)
  43. @contextmanager
  44. def suspend_functionalization():
  45. f_tls = torch._C._dispatch_tls_is_dispatch_key_included(
  46. torch._C.DispatchKey.Functionalize
  47. )
  48. f_rv = torch._C._functionalization_reapply_views_tls()
  49. if f_tls:
  50. torch._disable_functionalization()
  51. try:
  52. yield
  53. finally:
  54. if f_tls:
  55. torch._enable_functionalization(reapply_views=f_rv)
  56. def check_tensor_metadata_matches(nv, rv, desc):
  57. assert callable(desc)
  58. assert nv.size() == rv.size(), f"{desc()}: sizes {nv.size()} != {rv.size()}"
  59. assert nv.dtype == rv.dtype, f"{desc()}: dtype {nv.dtype} != {rv.dtype}"
  60. same_strides, idx = torch._prims_common.check_significant_strides(
  61. nv, rv, only_cuda=False
  62. )
  63. assert same_strides, (
  64. f"{desc()}: strides {nv.stride()} != {rv.stride()} (mismatch at index {idx})"
  65. )
  66. def check_metadata_matches(n, r, desc):
  67. assert callable(desc)
  68. n_vals, _n_spec = pytree.tree_flatten(n)
  69. r_vals, _r_spec = pytree.tree_flatten(r)
  70. # TODO: test the specs match; empirically sometimes we have a tuple
  71. # on one side and a list on the other
  72. assert len(n_vals) == len(r_vals), f"{len(n_vals)} != {len(r_vals)}"
  73. for i, nv, rv in zip(range(len(n_vals)), n_vals, r_vals):
  74. if not isinstance(rv, torch.Tensor):
  75. continue
  76. check_tensor_metadata_matches(nv, rv, lambda: f"{desc()} output {i}")
  77. class Lit:
  78. def __init__(self, s):
  79. self.s = s
  80. def __repr__(self):
  81. return self.s
  82. def _fmt(a: object) -> object:
  83. if isinstance(a, torch.Tensor):
  84. return Lit(
  85. f"torch.empty_strided({tuple(a.size())}, {a.stride()}, dtype={a.dtype})"
  86. )
  87. else:
  88. return a
  89. def make_crossref_functionalize(
  90. op: torch._ops.OpOverload[_P, _T], final_key: DispatchKey
  91. ) -> Union[Callable[_P, _T], DispatchKey]:
  92. from torch._subclasses.fake_tensor import FakeTensorMode
  93. # This case is pretty weird, suppress it for now
  94. if op == torch.ops.aten.lift_fresh.default:
  95. return final_key
  96. def handler(*args: _P.args, **kwargs: _P.kwargs) -> _T:
  97. fake_mode = FakeTensorMode()
  98. def fakeify_defun(t):
  99. if isinstance(t, torch.Tensor):
  100. if torch._is_functional_tensor(t):
  101. r = torch._from_functional_tensor(t)
  102. # NB: This assumes that the inner tensor sizes/strides match
  103. # the outer tensor sizes/strides. This doesn't necessarily have to
  104. # be the case, see discussion at
  105. # https://github.com/pytorch/pytorch/pull/87610/files/401ddeda1d769bedc88a12de332c7357b60e51a4#r1007264456
  106. assert t.size() == r.size()
  107. assert t.stride() == r.stride()
  108. else:
  109. r = t
  110. # TODO: suppress guards
  111. return fake_mode.from_tensor(r)
  112. return t
  113. def maybe_detach(t):
  114. if isinstance(t, torch.Tensor):
  115. return t.detach()
  116. else:
  117. return t
  118. # TODO: This probably does the wrong thing if you're running other
  119. # substantive modes with the normal op outside here
  120. with (
  121. torch.utils._python_dispatch._disable_current_modes(),
  122. suspend_functionalization(),
  123. ):
  124. f_args, f_kwargs = pytree.tree_map(fakeify_defun, (args, kwargs))
  125. orig_f_args, orig_f_kwargs = pytree.tree_map(
  126. maybe_detach, (f_args, f_kwargs)
  127. )
  128. with fake_mode:
  129. f_r = op(*f_args, **f_kwargs)
  130. r = op._op_dk(final_key, *args, **kwargs)
  131. def desc():
  132. fmt_args = ", ".join(
  133. itertools.chain(
  134. (repr(pytree.tree_map(_fmt, a)) for a in orig_f_args),
  135. (
  136. f"{k}={pytree.tree_map(_fmt, v)}"
  137. for k, v in orig_f_kwargs.items()
  138. ),
  139. )
  140. )
  141. return f"{op}({fmt_args})"
  142. check_metadata_matches(f_r, r, desc)
  143. return r
  144. return handler
  145. # NB: enabling this is slow, don't do it in a hot loop. This is purely
  146. # for debugging purposes.
  147. @contextmanager
  148. def enable_crossref_functionalize():
  149. for op in all_py_loaded_overloads():
  150. op._uncache_dispatch(torch._C.DispatchKey.Functionalize)
  151. try:
  152. with (
  153. enable_python_dispatcher(),
  154. unittest.mock.patch("torch._dispatch.python.CROSSREF_FUNCTIONALIZE", True),
  155. ):
  156. yield
  157. finally:
  158. for op in all_py_loaded_overloads():
  159. op._uncache_dispatch(torch._C.DispatchKey.Functionalize)