virtualized.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. # mypy: allow-untyped-defs
  2. """
  3. This file provides a number of "global" variables/handlers that are actually
  4. thread local and dynamically scoped, with Inductor patching them to various
  5. implementations depending on the situation.
  6. These handlers are interacted with in a fairly stylized way. Typically,
  7. we will import V from this module::
  8. from .virtualized import V
  9. Various handlers are accessible as attributes on this module; for example,
  10. you might access ``V.graph.sizevars.size_hint`` to resolve a size hint associated with
  11. a number.
  12. There are a few distinct usage patterns for virtualized global variables:
  13. 1. Implicit argument passing. Examples: ``V.current_node``, ``V.aot_compilation``.
  14. Use ``V.set_current_node`` to change what the current node is while we're
  15. executing some region of code, so code inside that region can query ``V.current_node``
  16. to find out what it is. This is often more convenient than manually threading
  17. the current node as an argument through all call stacks.
  18. 2. Per-compilation global state. Examples: ``V.fake_mode``, ``V.graph``. For a
  19. given ``compile_fx`` invocation, these typically don't change, but they are
  20. associated with some internal state so they cannot just be global functions.
  21. We install these objects at the beginning of compilation and then you can
  22. conveniently access them without having to pass them around.
  23. 3. Alternate define-by-run interpretations. Examples: ``V.ops``, ``V.kernel``.
  24. A commonly used IR in Inductor is define-by-run: instead of maintaining
  25. explicit syntax data structures, we instead represent loop bodies as
  26. callable functions, which internally invoke operations defined on
  27. ``V.ops``. To perform semantic analysis, print or code generate these
  28. operations, we dynamically patch ``V.ops`` with an alternate handler with
  29. the intended semantics and then run the callable function. For example, to
  30. extract out a traditional (FX) graph representation of the define-by-run
  31. IR, simply install a handler that records each ``ops`` call to a graph.
  32. TODO: Define a parent class / protocol that defines all of the operations
  33. V.ops is expected to support.
  34. It is typically an error to access a virtualized global without having installed
  35. an appropriate handler (you will get a NullHandler), although in some cases we
  36. provide a default implementation.
  37. One last thing: although most virtualized globals are accessed via ``V``, ``ops`` is
  38. ubiquitous enough to have its own top level variable, so you will typically see
  39. ``ops.constant(...)`` rather than ``V.ops.constant(...)``. In fact, these are not
  40. equivalent; the former interface supports arithmetic overloads like ``x + y``
  41. instead of forcing ``ops.add(x, y)``, so it should be preferred.
  42. Some operators are seemingly unused, but they are implicitly used by ops_wrapper.
  43. In particular, we typically have an operator for every basic pointwise PyTorch operation
  44. supported.
  45. """
  46. from __future__ import annotations
  47. from contextlib import AbstractContextManager, contextmanager
  48. from threading import local
  49. from typing import Any, Callable, Generic, List, Type, TYPE_CHECKING, TypeVar, Union
  50. from .ops_handler import ( # noqa: F401
  51. KernelFormatterHandler,
  52. MockHandler,
  53. OpsHandler,
  54. ReductionType,
  55. StoreMode,
  56. WrapperHandler,
  57. )
  58. if TYPE_CHECKING:
  59. import torch
  60. from torch._inductor.debug import DebugContext
  61. from torch._inductor.graph import GraphLowering
  62. from torch._inductor.ir import InterpreterShim
  63. from torch._subclasses import FakeTensorMode
  64. threadlocal = local()
  65. T = TypeVar("T")
  66. class NullHandler:
  67. """
  68. Sentinel indicating that a global variable is unset ala None. Typically,
  69. attempting to access the global variable before it's set is an error, but with
  70. NullHandler it won't fail until you try to access an attribute on it.
  71. """
  72. pass
  73. class Virtualized(Generic[T]):
  74. """
  75. Implements a global variable that redirects via thread local variable
  76. (NB: construct this class to create the global variable; this is not
  77. a singleton class!)
  78. This allows us to swap in different op implementations in codegen.
  79. NB: Despite the fact that we typically call these "handlers" (e.g., NullHandler is
  80. the default value of the variable), we sometimes use these variables to
  81. store other things, like booleans.
  82. """
  83. def __init__(self, vname: str, default: Union[Callable[[], T], Type[NullHandler]]):
  84. self._key: str = f"__torchinductor_{vname}"
  85. self._default = default
  86. def _set_handler(self, value: T) -> AbstractContextManager[None]:
  87. prior = self._get_handler()
  88. setattr(threadlocal, self._key, value)
  89. @contextmanager
  90. def ctx():
  91. try:
  92. yield
  93. finally:
  94. self._set_handler(prior)
  95. return ctx()
  96. def _get_handler(self) -> T:
  97. try:
  98. return getattr(threadlocal, self._key)
  99. except AttributeError:
  100. # TODO: To be honest, I feel we probably should just error in this
  101. # case, instead of making a null handler that will probably error
  102. # when you getattr on it
  103. return self._default() # type: ignore[return-value]
  104. def __getattr__(self, name: str) -> Any:
  105. return getattr(self._get_handler(), name)
  106. class NullKernelHandler(NullHandler):
  107. """
  108. We need access `V.kernel.removed_buffers` in DeferredLine class when there
  109. is no kernel in the context. This happens when codegening the wrapper.
  110. Initialize `removed_buffers` and `inplaced_to_remove` explicitly so we don't
  111. need call 'getattr' with default value which is error prone to typo in
  112. attribute name.
  113. """
  114. def __init__(self):
  115. super().__init__()
  116. self.removed_buffers = set()
  117. self.inplaced_to_remove = set()
  118. self.index_dtype = "tl.int64"
  119. _ops: Virtualized[OpsHandler[Any]] = Virtualized("ops", MockHandler)
  120. _graph: Virtualized[GraphLowering] = Virtualized("graph", NullHandler)
  121. _real_inputs: Virtualized[List[torch.Tensor]] = Virtualized("real_inputs", NullHandler)
  122. _fake_mode: Virtualized[FakeTensorMode] = Virtualized("fake_mode", NullHandler)
  123. _kernel: Virtualized[NullKernelHandler] = Virtualized(
  124. "kernel", NullKernelHandler
  125. ) # TODO: improve type
  126. _debug: Virtualized[DebugContext] = Virtualized("debug", NullHandler)
  127. _interpreter: Virtualized[InterpreterShim] = Virtualized("interpreter", NullHandler)
  128. _aot_compilation: Virtualized[bool] = Virtualized("aot_compilation", NullHandler)
  129. _current_node: Virtualized[torch.fx.Node] = Virtualized("current_node", NullHandler)
  130. class OpsValue:
  131. """The return type of most ops calls.
  132. This exists so we can overload magic methods, and write mathematical
  133. expressions much more fluently. So instead of
  134. ops.add(ops.mul(ops.mul(ops.sub(ops.mul(_Ap2, x), _Ap3), x), x), _1)
  135. we can write
  136. (_Ap2 * x - _Ap3) * x * x + _1
  137. """
  138. value: Any
  139. def __init__(self, value):
  140. self.value = value
  141. def __str__(self):
  142. return str(self.value)
  143. def __repr__(self):
  144. return f"OpsValue({self.value!r})"
  145. def __add__(self, other):
  146. return ops.add(self, other)
  147. def __mul__(self, other):
  148. return ops.mul(self, other)
  149. def __sub__(self, other):
  150. return ops.sub(self, other)
  151. def __neg__(self):
  152. return ops.neg(self)
  153. def __truediv__(self, other):
  154. return ops.truediv(self, other)
  155. def __floordiv__(self, other):
  156. return ops.floordiv(self, other)
  157. def __mod__(self, other):
  158. return ops.mod(self, other)
  159. def __pow__(self, other):
  160. return ops.pow(self, other)
  161. def __lt__(self, other):
  162. return ops.lt(self, other)
  163. def __le__(self, other):
  164. return ops.le(self, other)
  165. def __eq__(self, other):
  166. return ops.eq(self, other)
  167. def __ne__(self, other):
  168. return ops.ne(self, other)
  169. def __gt__(self, other):
  170. return ops.gt(self, other)
  171. def __ge__(self, other):
  172. return ops.ge(self, other)
  173. def __and__(self, other):
  174. return ops.bitwise_and(self, other)
  175. def __or__(self, other):
  176. return ops.bitwise_or(self, other)
  177. def __xor__(self, other):
  178. return ops.bitwise_xor(self, other)
  179. def __invert__(self):
  180. return ops.bitwise_not(self)
  181. def __rshfit__(self, n):
  182. return ops.bitwise_right_shift(self, n)
  183. def __lshift__(self, n):
  184. return ops.bitwise_left_shift(self, n)
  185. class OpsWrapper:
  186. """This wraps any returned IR values into an `OpsValue` instance, so that we
  187. can overload the magic methods for writing mathematical expressions fluently.
  188. """
  189. def __getattr__(self, name):
  190. def inner(*args, **kwargs):
  191. new_args = [OpsWrapper._unwrap(a) for a in args]
  192. new_kwargs = {k: OpsWrapper._unwrap(v) for k, v in kwargs.items()}
  193. return OpsWrapper._wrap(getattr(_ops, name)(*new_args, **new_kwargs))
  194. return inner
  195. @staticmethod
  196. def _unwrap(x):
  197. if isinstance(x, (list, tuple)):
  198. return tuple(OpsWrapper._unwrap(v) for v in x)
  199. if isinstance(x, OpsValue):
  200. return x.value
  201. return x
  202. @staticmethod
  203. def _wrap(x):
  204. if isinstance(x, (list, tuple)):
  205. return tuple(OpsValue(v) for v in x)
  206. return OpsValue(x)
  207. @staticmethod
  208. def indirect_indexing(index, size, check=True):
  209. # Returns a sympy value, not IR value
  210. index = OpsWrapper._unwrap(index)
  211. return _ops.indirect_indexing(index, size, check)
  212. ops = OpsWrapper()
  213. class _V:
  214. MockHandler = MockHandler
  215. KernelFormatterHandler = KernelFormatterHandler
  216. WrapperHandler = WrapperHandler
  217. set_ops_handler: Callable[[Any], Any] = _ops._set_handler
  218. get_ops_handler: Callable[[], Any] = _ops._get_handler
  219. set_graph_handler: Callable[[GraphLowering], Any] = _graph._set_handler
  220. set_real_inputs: Callable[[Any], Any] = _real_inputs._set_handler
  221. get_real_inputs: Callable[[], Any] = _real_inputs._get_handler
  222. set_fake_mode: Callable[[Any], Any] = _fake_mode._set_handler
  223. get_fake_mode: Callable[[], Any] = _fake_mode._get_handler
  224. set_kernel_handler: Callable[[Any], Any] = _kernel._set_handler
  225. set_debug_handler: Callable[[Any], Any] = _debug._set_handler
  226. set_interpreter_handler: Callable[[Any], Any] = _interpreter._set_handler
  227. set_aot_compilation: Callable[[bool], Any] = _aot_compilation._set_handler
  228. get_aot_compilation: Callable[[], Any] = _aot_compilation._get_handler
  229. set_current_node: Callable[[Any], Any] = _current_node._set_handler
  230. get_current_node: Callable[[], Any] = _current_node._get_handler
  231. @property
  232. def ops(self) -> OpsHandler[Any]:
  233. """The operator handler specific to the current codegen task"""
  234. return _ops._get_handler()
  235. @property
  236. def graph(self) -> GraphLowering:
  237. """The graph currently being generated"""
  238. return _graph._get_handler()
  239. @property
  240. def real_inputs(self):
  241. """non-fake example inputs"""
  242. return _real_inputs._get_handler()
  243. @property
  244. def fake_mode(self):
  245. """The graph currently being generated"""
  246. return _fake_mode._get_handler()
  247. @property
  248. def kernel(self):
  249. """The kernel currently being generated"""
  250. return _kernel._get_handler()
  251. @property
  252. def debug(self):
  253. return _debug._get_handler()
  254. @property
  255. def interpreter(self):
  256. return _interpreter._get_handler()
  257. @property
  258. def aot_compilation(self):
  259. return _aot_compilation._get_handler()
  260. @property
  261. def current_node(self):
  262. return _current_node._get_handler()
  263. V = _V()