virtualized.py 15 KB

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