virtualized.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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, cast, Generic, TYPE_CHECKING, TypeVar, Union
  50. from torch.utils._ordered_set import OrderedSet
  51. from .ops_handler import ( # noqa: F401
  52. DefaultHandler,
  53. KernelFormatterHandler,
  54. MockHandler,
  55. OpsHandler,
  56. ReductionType,
  57. StoreMode,
  58. WrapperHandler,
  59. )
  60. if TYPE_CHECKING:
  61. import torch
  62. from torch._inductor.choices import InductorChoices
  63. from torch._inductor.codegen.cpp_utils import LocalBufferContext
  64. from torch._inductor.debug import DebugContext
  65. from torch._inductor.graph import GraphLowering
  66. from torch._inductor.ir import ExternKernelNode
  67. from torch._inductor.loop_body import InterpreterShim
  68. from torch._subclasses import FakeTensorMode
  69. threadlocal = local()
  70. T = TypeVar("T")
  71. class NullHandler:
  72. """
  73. Sentinel indicating that a global variable is unset ala None. Typically,
  74. attempting to access the global variable before it's set is an error, but with
  75. NullHandler it won't fail until you try to access an attribute on it.
  76. """
  77. # If a virtualized value is set to _PoisonedVirtual then any attempt to get the
  78. # value will result an an exception being raised. This is useful if we want to
  79. # trap uninitialized reads of virtualized globals - for example when compiling
  80. # in a subprocess we don't want the child reading globals that weren't copied
  81. # from the parent.
  82. _PoisonedVirtual = object()
  83. class Virtualized(Generic[T]):
  84. """
  85. Implements a global variable that redirects via thread local variable
  86. (NB: construct this class to create the global variable; this is not
  87. a singleton class!)
  88. This allows us to swap in different op implementations in codegen.
  89. NB: Despite the fact that we typically call these "handlers" (e.g., NullHandler is
  90. the default value of the variable), we sometimes use these variables to
  91. store other things, like booleans.
  92. """
  93. def __init__(self, vname: str, default: Union[Callable[[], T], type[NullHandler]]):
  94. self._vname = vname
  95. self._key: str = f"__torchinductor_{vname}"
  96. self._default = default
  97. def _set_handler(self, value: T) -> AbstractContextManager[None]:
  98. prior = self._get_handler(False)
  99. setattr(threadlocal, self._key, value)
  100. @contextmanager
  101. def ctx():
  102. try:
  103. yield
  104. finally:
  105. self._set_handler(prior)
  106. return ctx()
  107. def _get_handler(self, check_poisoned: bool = True) -> T:
  108. try:
  109. value = getattr(threadlocal, self._key)
  110. if check_poisoned and value is _PoisonedVirtual:
  111. raise RuntimeError(
  112. f"Attempt to use poisoned virtualized value '{self._vname}'."
  113. )
  114. return value
  115. except AttributeError:
  116. # TODO: To be honest, I feel we probably should just error in this
  117. # case, instead of making a null handler that will probably error
  118. # when you getattr on it
  119. return self._default() # type: ignore[return-value]
  120. def __getattr__(self, name: str) -> Any:
  121. return getattr(self._get_handler(), name)
  122. class NullKernelHandler(NullHandler):
  123. """
  124. We need access `V.kernel.removed_buffers` in DeferredLine class when there
  125. is no kernel in the context. This happens when codegening the wrapper.
  126. Initialize `removed_buffers` and `inplaced_to_remove` explicitly so we don't
  127. need call 'getattr' with default value which is error prone to typo in
  128. attribute name.
  129. """
  130. def __init__(self):
  131. super().__init__()
  132. self.removed_buffers = OrderedSet[Any]()
  133. self.inplaced_to_remove = OrderedSet[Any]()
  134. self.index_dtype = "tl.int64"
  135. def get_index_dtype_as_torch_dtype(self):
  136. import torch
  137. if self.index_dtype == "tl.int64":
  138. return torch.int64
  139. elif self.index_dtype == "tl.int32":
  140. return torch.int32
  141. else:
  142. raise ValueError(f"Unknown dtype: {self.index_dtype}")
  143. _ops: Virtualized[OpsHandler[Any]] = Virtualized(
  144. "ops", cast(type[OpsHandler[Any]], MockHandler)
  145. )
  146. _graph: Virtualized[GraphLowering] = Virtualized("graph", NullHandler)
  147. _extern_kernel_nodes: Virtualized[list[ExternKernelNode]] = Virtualized(
  148. "extern_kernel_nodes", NullHandler
  149. )
  150. _real_inputs: Virtualized[list[torch.Tensor]] = Virtualized("real_inputs", NullHandler)
  151. _fake_mode: Virtualized[FakeTensorMode] = Virtualized("fake_mode", NullHandler)
  152. _kernel: Virtualized[NullKernelHandler] = Virtualized(
  153. "kernel", NullKernelHandler
  154. ) # TODO: improve type
  155. _debug: Virtualized[DebugContext] = Virtualized("debug", NullHandler)
  156. _interpreter: Virtualized[InterpreterShim] = Virtualized("interpreter", NullHandler)
  157. _aot_compilation: Virtualized[bool] = Virtualized("aot_compilation", NullHandler)
  158. _current_node: Virtualized[torch.fx.Node] = Virtualized("current_node", NullHandler)
  159. _local_buffer_context: Virtualized[LocalBufferContext] = Virtualized(
  160. "local_buffer_context", NullHandler
  161. )
  162. def _choices_default():
  163. """
  164. Lazy init the global choices handler
  165. We virtualize InductorChoices to allow changing inductor heuristics from out of tree.
  166. """
  167. from torch._inductor.choices import InductorChoices
  168. rv = InductorChoices()
  169. setattr(threadlocal, _choices._key, rv)
  170. return rv
  171. _choices: Virtualized[InductorChoices] = Virtualized("choices", _choices_default)
  172. class OpsValue:
  173. """The return type of most ops calls.
  174. This exists so we can overload magic methods, and write mathematical
  175. expressions much more fluently. So instead of
  176. ops.add(ops.mul(ops.mul(ops.sub(ops.mul(_Ap2, x), _Ap3), x), x), _1)
  177. we can write
  178. (_Ap2 * x - _Ap3) * x * x + _1
  179. """
  180. value: Any
  181. def __init__(self, value):
  182. self.value = value
  183. def __str__(self):
  184. return str(self.value)
  185. def __repr__(self):
  186. return f"OpsValue({self.value!r})"
  187. def __add__(self, other):
  188. return ops.add(self, other)
  189. def __mul__(self, other):
  190. return ops.mul(self, other)
  191. def __sub__(self, other):
  192. return ops.sub(self, other)
  193. def __neg__(self):
  194. return ops.neg(self)
  195. def __truediv__(self, other):
  196. return ops.truediv(self, other)
  197. def __floordiv__(self, other):
  198. return ops.floordiv(self, other)
  199. def __mod__(self, other):
  200. return ops.mod(self, other)
  201. def __pow__(self, other):
  202. return ops.pow(self, other)
  203. def __lt__(self, other):
  204. return ops.lt(self, other)
  205. def __le__(self, other):
  206. return ops.le(self, other)
  207. def __eq__(self, other):
  208. return ops.eq(self, other)
  209. def __ne__(self, other):
  210. return ops.ne(self, other)
  211. def __gt__(self, other):
  212. return ops.gt(self, other)
  213. def __ge__(self, other):
  214. return ops.ge(self, other)
  215. def __and__(self, other):
  216. return ops.bitwise_and(self, other)
  217. def __or__(self, other):
  218. return ops.bitwise_or(self, other)
  219. def __xor__(self, other):
  220. return ops.bitwise_xor(self, other)
  221. def __invert__(self):
  222. return ops.bitwise_not(self)
  223. def __rshfit__(self, n):
  224. return ops.bitwise_right_shift(self, n)
  225. def __lshift__(self, n):
  226. return ops.bitwise_left_shift(self, n)
  227. class OpsWrapper(DefaultHandler):
  228. """This wraps any returned IR values into an `OpsValue` instance, so that we
  229. can overload the magic methods for writing mathematical expressions fluently.
  230. """
  231. def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
  232. new_args = [OpsWrapper._unwrap(a) for a in args]
  233. new_kwargs = {k: OpsWrapper._unwrap(v) for k, v in kwargs.items()}
  234. return OpsWrapper._wrap(getattr(_ops, name)(*new_args, **new_kwargs))
  235. @staticmethod
  236. def _unwrap(x):
  237. if isinstance(x, (list, tuple)):
  238. return tuple(OpsWrapper._unwrap(v) for v in x)
  239. if isinstance(x, OpsValue):
  240. return x.value
  241. return x
  242. @staticmethod
  243. def _wrap(x):
  244. if isinstance(x, (list, tuple)):
  245. return tuple(OpsValue(v) for v in x)
  246. return OpsValue(x)
  247. @staticmethod
  248. def indirect_indexing(index, size, check=True, wrap_neg=True):
  249. # Returns a sympy value, not IR value
  250. index = OpsWrapper._unwrap(index)
  251. return _ops.indirect_indexing(index, size, check, wrap_neg)
  252. ops: OpsHandler[Any] = OpsWrapper()
  253. class _V:
  254. MockHandler = MockHandler
  255. KernelFormatterHandler = KernelFormatterHandler
  256. WrapperHandler = WrapperHandler
  257. set_ops_handler: Callable[[OpsHandler[Any]], AbstractContextManager[None]] = (
  258. _ops._set_handler
  259. )
  260. get_ops_handler: Callable[[], OpsHandler[Any]] = _ops._get_handler
  261. set_graph_handler: Callable[[GraphLowering], Any] = _graph._set_handler
  262. set_extern_kernel_nodes: Callable[[list[ExternKernelNode]], Any] = (
  263. _extern_kernel_nodes._set_handler
  264. )
  265. set_real_inputs: Callable[[Any], Any] = _real_inputs._set_handler
  266. get_real_inputs: Callable[[], Any] = _real_inputs._get_handler
  267. set_fake_mode: Callable[[Any], Any] = _fake_mode._set_handler
  268. get_fake_mode: Callable[[], Any] = _fake_mode._get_handler
  269. set_kernel_handler: Callable[[Any], Any] = _kernel._set_handler
  270. set_debug_handler: Callable[[Any], Any] = _debug._set_handler
  271. set_interpreter_handler: Callable[[Any], Any] = _interpreter._set_handler
  272. set_aot_compilation: Callable[[bool], Any] = _aot_compilation._set_handler
  273. get_aot_compilation: Callable[[], Any] = _aot_compilation._get_handler
  274. set_current_node: Callable[[Any], Any] = _current_node._set_handler
  275. get_current_node: Callable[[], Any] = _current_node._get_handler
  276. set_local_buffer_context: Callable[[Any], Any] = _local_buffer_context._set_handler
  277. get_local_buffer_context: Callable[[], Any] = _local_buffer_context._get_handler
  278. set_choices_handler: Callable[[Any], Any] = _choices._set_handler
  279. @property
  280. def ops(self) -> OpsHandler[Any]:
  281. """The operator handler specific to the current codegen task"""
  282. return _ops._get_handler()
  283. @property
  284. def graph(self) -> GraphLowering:
  285. """The graph currently being generated"""
  286. return _graph._get_handler()
  287. @property
  288. def extern_kernel_nodes(self) -> list[ExternKernelNode]:
  289. """
  290. The extern_kernel_nodes needed for the entire graph, including the
  291. subgraphs.
  292. See `ProxyExecutor Design Note` in ir.py for more details
  293. """
  294. return _extern_kernel_nodes._get_handler()
  295. @property
  296. def real_inputs(self):
  297. """non-fake example inputs"""
  298. return _real_inputs._get_handler()
  299. @property
  300. def fake_mode(self):
  301. """The graph currently being generated"""
  302. return _fake_mode._get_handler()
  303. @property
  304. def kernel(self):
  305. """The kernel currently being generated"""
  306. return _kernel._get_handler()
  307. @property
  308. def debug(self):
  309. return _debug._get_handler()
  310. @property
  311. def interpreter(self):
  312. return _interpreter._get_handler()
  313. @property
  314. def aot_compilation(self):
  315. return _aot_compilation._get_handler() is True
  316. @property
  317. def current_node(self):
  318. return _current_node._get_handler()
  319. @property
  320. def local_buffer_context(self):
  321. return _local_buffer_context._get_handler()
  322. @property
  323. def choices(self) -> InductorChoices:
  324. return _choices._get_handler()
  325. V = _V()