ops_handler.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. # mypy: allow-untyped-defs
  2. import itertools
  3. from typing import (
  4. Any,
  5. Callable,
  6. Dict,
  7. Generic,
  8. Literal,
  9. Optional,
  10. Tuple,
  11. TypeVar,
  12. Union,
  13. )
  14. from typing_extensions import Protocol
  15. from unittest.mock import patch
  16. import sympy
  17. import torch
  18. import torch.utils._pytree as pytree
  19. from .utils import IndentedBuffer, reduction_num_outputs, sympy_index_symbol, sympy_str
  20. T = TypeVar("T")
  21. StoreMode = Optional[Literal["atomic_add"]]
  22. ReductionType = Literal[
  23. "argmax",
  24. "argmin",
  25. "welford_reduce",
  26. "welford_combine",
  27. "any",
  28. "max",
  29. "min",
  30. "prod",
  31. "sum",
  32. "xor_sum",
  33. ]
  34. def _arg_str(a) -> str:
  35. if isinstance(a, sympy.Expr):
  36. return sympy_str(a)
  37. return str(a)
  38. # NB: This is not done as a parent class, because our ops handlers
  39. # implementations make heavy use of __getattr__ magic, and pre-existing
  40. # stubs for methods would interfere with this mechanism.
  41. #
  42. # TODO: A superclass that does desugaring for operations like
  43. # reciprocal/square might be useful.
  44. class OpsHandler(Protocol[T]):
  45. """
  46. Protocol describing the set of valid operations on ``torch._inductor.virtualized.ops``,
  47. as well as the contract for op handlers. The type T signifies the domain
  48. of the abstract analysis AKA what all of the functions return / take as arguments
  49. anywhere compute occurs.
  50. While these operators are typically dtype polymorphic (e.g., you can use mul
  51. on both integers and floats), they do NOT do promotion and usually return the
  52. same dtype as the input. You are expected to have handled type promotion
  53. during ATen decompositions. Most operators correspond exactly to pointwise
  54. operations as defined by torch, so when in doubt about semantics, check the
  55. corresponding torch documentation. These are all scalar operations (so they
  56. are defined to operate on a single element at a time.)
  57. For convenience, many operators take a src_dtype which indicates what the dtype
  58. of the input argument is. Although in principle this can be derived by an
  59. analysis, providing this for ops where it is useful helps avoid having to repeatedly
  60. recompute dtype in code generation.
  61. Note that this often describes a class of static methods, for stateless
  62. ops handlers.
  63. Handlers are often defined using ``__getattr__`` metaprogramming, which means
  64. that you cannot declare that a type implements a protocol by inheriting from
  65. it (as the type stubs count as attribute declarations and impede the getattr
  66. magic method from being called). Instead, define a function that casts an
  67. argument of your type to the protocol, which is sufficient to induce mypy to
  68. test that the protocol is implemented correctly. Search for ``_typecheck_``
  69. in this file to see some examples. If you see an obscure error where a
  70. class doesn't implement a Protocol, but mypy doesn't say why, check to see
  71. that ``__getattr__`` is typed correctly (typically, it is not possible to
  72. type ``__getattr__`` without typing it as ``Callable[..., Any]``)
  73. """
  74. def constant(self, value: Union[bool, float, int], dtype: torch.dtype) -> T:
  75. """Produces a scalar constant of type dtype."""
  76. ...
  77. def load_seed(self, name: str, offset: T):
  78. """Computes inductor_prims.lookup_seed."""
  79. ...
  80. def rand(self, seed: T, offset: T) -> T:
  81. """Computes inductor_prims.random with mode="rand". offset has dtype int32."""
  82. ...
  83. def randn(self, seed: T, offset: T) -> T:
  84. """Computes inductor_prims.random with mode="randn". offset has dtype int32."""
  85. ...
  86. def randint64(self, seed: T, offset: T, low: T, high: T) -> T:
  87. """Computes inductor_prims.randint. offset has dtype int32."""
  88. ...
  89. def masked(self, mask: T, body: Callable[[], T], other: T) -> T:
  90. """
  91. Computes body, but only perform loads/stores if the boolean mask
  92. evaluates to true. For example, you would use this if you needed to
  93. perform an indirect load that may not be valid on some elements;
  94. without masking, invalid accesses can cause IMAs. When mask is true,
  95. the result is the result of body; otherwise it is other.
  96. Contrast this with ops.where, which can multiplex between two values
  97. that have been unconditionally computed.
  98. """
  99. ...
  100. def where(self, condition: T, input: T, other: T) -> T:
  101. """
  102. Computes torch.where: when condition is true, return input; otherwise return other.
  103. """
  104. ...
  105. def index_expr(self, expr: sympy.Expr, dtype: torch.dtype) -> T:
  106. """
  107. Converts a sympy expression into a scalar of type dtype. expr is typically
  108. an indexing expression, thus the name; however, it can also be used in
  109. non-indexing situations.
  110. """
  111. ...
  112. def to_dtype(
  113. self, x: T, dtype: torch.dtype, src_dtype: Optional[torch.dtype] = None
  114. ) -> T:
  115. """
  116. Convert x to dtype. src_dtype can be optionally set to specify what the original
  117. dtype of x was, which can improve code generation (used by torch to(dtype=dtype)).
  118. """
  119. ...
  120. def trunc_to_int(self, x: T, dtype: torch.dtype) -> T:
  121. """
  122. Convert x to dtype with truncation semantics (similar to how the int
  123. constructor works in Python). In Inductor codegen, this just decays
  124. to trunc and then to_dtype, but this composite operation helps
  125. roundtrips for Sympy evaluation.
  126. dtype is taken as an explicit parameter because the desired output
  127. dtype is typically the index dtype, which may vary between int32 and
  128. int64 depending on if we've shown that all the indexing operations can
  129. be done in int32.
  130. """
  131. ...
  132. def ceil_to_int(self, x: T, dtype: torch.dtype) -> T:
  133. """
  134. Convert x to dtype with ceiling semantics. See also trunc_to_int.
  135. """
  136. ...
  137. def floor_to_int(self, x: T, dtype: torch.dtype) -> T:
  138. """
  139. Convert x to dtype with ceiling semantics. See also trunc_to_int.
  140. """
  141. ...
  142. def round_to_int(self, x: T, dtype: torch.dtype) -> T:
  143. """
  144. Convert x to dtype with round-to-even semantics. See also trunc_to_int.
  145. """
  146. ...
  147. def to_dtype_bitcast(self, x: T, dtype: torch.dtype, src_dtype: torch.dtype) -> T:
  148. """
  149. Reinterpret cast x to dtype (reinterpreting the bits in memory as another dtype.)
  150. src_dtype must be the original type of x.
  151. """
  152. ...
  153. def identity(self, x: T) -> T:
  154. """
  155. Returns x as is. This is used to trigger CSE.
  156. """
  157. ...
  158. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  159. # These operations are only available in a "kernel" context. Check
  160. # torch._inductor.codegen.common.CSEProxy for their typical implementation
  161. # in op handler (routing to their respective implementations in the kernel
  162. # handler)
  163. #
  164. # Importantly, inside a kernel, indexing and mask variables are available
  165. # in scope, which are typically used by sympy.Expr indexing.
  166. def indirect_indexing(
  167. self, x: T, size: sympy.Expr, check: bool = True
  168. ) -> sympy.Expr:
  169. """
  170. Convert an integral x into a sympy.Expr that can be subsequently used in
  171. indexing computation. 'size' represents an upper bound on the what valid
  172. indexes can be; when 'check' is True, we check that the x is in bounds.
  173. NB: This is typically mandatory to implement for any analysis, because you
  174. MUST return a valid sympy.Expr of some sort (even if it's a meaningless symbol).
  175. """
  176. ...
  177. def load(self, name: str, index: sympy.Expr) -> T:
  178. """
  179. Load from the memory location 'name', offset by some indexing expression 'index'.
  180. """
  181. ...
  182. def store(
  183. self,
  184. name: str,
  185. index: sympy.Expr,
  186. value: T,
  187. mode: StoreMode = None,
  188. ) -> None:
  189. """
  190. Store 'value' to the memory location 'name' offset by 'expr'. If
  191. specified, 'mode' can require the store to be an atomic addition.
  192. """
  193. ...
  194. # TODO: Better explain how the "collective" semantics of these ops;
  195. # remember that the input value is a scalar, you can't reduce on it in the
  196. # traditional sense!
  197. def reduction(
  198. self,
  199. dtype: torch.dtype,
  200. src_dtype: torch.dtype,
  201. reduction_type: ReductionType,
  202. value: T,
  203. ) -> Union[T, Tuple[T, ...]]:
  204. """
  205. Perform a 'reduction_type' reduction on 'value' of dtype 'src_dtype',
  206. using 'dtype' as the accumulation dtype for the reduction. The result
  207. is an intermediate computation which should be stored to the final
  208. location using 'ops.store_reduction'.
  209. Valid reduction types are . For Welford reduction types, this
  210. function returns multiple outputs; consult reduction_num_outputs to
  211. determine the amount in metaprogramming applications.
  212. """
  213. ...
  214. # TODO: in practice, this seems to actually return None, but not returning
  215. # a T makes common __getattr__ idioms not type correctly. Figure out if
  216. # this should be returning something.
  217. def store_reduction(self, name: str, index: sympy.Expr, value: T) -> T:
  218. """
  219. Store the fully accumulated result of 'reduction' to the memory
  220. location 'name' offset by 'expr'.
  221. """
  222. ...
  223. def scan(
  224. self,
  225. dtypes: Tuple[torch.dtype, ...],
  226. combine_fn: Callable[[Tuple[T, ...], Tuple[T, ...]], Tuple[T, ...]],
  227. values: Tuple[T, ...],
  228. ) -> Tuple[T, ...]:
  229. """
  230. Perform an associative scan on 'value'.
  231. """
  232. # TODO: Improve the description with some pseudocode
  233. ...
  234. def bucketize(
  235. self,
  236. values: T,
  237. offsets_name: str,
  238. offsets_size: sympy.Expr,
  239. indexing_dtype: torch.dtype,
  240. right: bool,
  241. ) -> T:
  242. # See [Note: Inductor bucketize op]
  243. ...
  244. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  245. # The following ops have semantics that correspond exactly to the torch
  246. # operation with the same corresponding name.
  247. def abs(self, x0: T) -> T:
  248. ...
  249. def exp(self, x0: T) -> T:
  250. ...
  251. def exp2(self, x0: T) -> T:
  252. ...
  253. def expm1(self, x0: T) -> T:
  254. ...
  255. def sqrt(self, x0: T) -> T:
  256. ...
  257. def relu(self, x0: T) -> T:
  258. ...
  259. def minimum(self, x0: T, x1: T) -> T:
  260. ...
  261. def maximum(self, x0: T, x1: T) -> T:
  262. ...
  263. def cos(self, x0: T) -> T:
  264. ...
  265. def sin(self, x0: T) -> T:
  266. ...
  267. def lgamma(self, x0: T) -> T:
  268. ...
  269. def erf(self, x0: T) -> T:
  270. ...
  271. def cosh(self, x0: T) -> T:
  272. ...
  273. def sinh(self, x0: T) -> T:
  274. ...
  275. def acos(self, x0: T) -> T:
  276. ...
  277. def acosh(self, x0: T) -> T:
  278. ...
  279. def asin(self, x0: T) -> T:
  280. ...
  281. def asinh(self, x0: T) -> T:
  282. ...
  283. def atan2(self, x0: T, x1: T) -> T:
  284. ...
  285. def atan(self, x0: T) -> T:
  286. ...
  287. def atanh(self, x0: T) -> T:
  288. ...
  289. def copysign(self, x0: T, x1: T) -> T:
  290. ...
  291. def erfc(self, x0: T) -> T:
  292. ...
  293. def erfinv(self, x0: T) -> T:
  294. ...
  295. def frexp(self, x0: T):
  296. ...
  297. def hypot(self, x0: T, x1: T) -> T:
  298. ...
  299. def log10(self, x0: T) -> T:
  300. ...
  301. def log2(self, x0: T) -> T:
  302. ...
  303. def nextafter(self, x0: T, x1: T) -> T:
  304. ...
  305. def logical_and(self, x0: T, x1: T) -> T:
  306. ...
  307. def logical_not(self, x0: T) -> T:
  308. ...
  309. def logical_or(self, x0: T, x1: T) -> T:
  310. ...
  311. def logical_xor(self, x0: T, x1: T) -> T:
  312. ...
  313. def bitwise_and(self, x0: T, x1: T) -> T:
  314. ...
  315. def bitwise_not(self, x0: T) -> T:
  316. ...
  317. def bitwise_or(self, x0: T, x1: T) -> T:
  318. ...
  319. def bitwise_xor(self, x0: T, x1: T) -> T:
  320. ...
  321. def bitwise_left_shift(self, x0: T, x1: T) -> T:
  322. ...
  323. def bitwise_right_shift(self, x0: T, x1: T) -> T:
  324. ...
  325. def rsqrt(self, x0: T) -> T:
  326. ...
  327. def log1p(self, x0: T) -> T:
  328. ...
  329. def tan(self, x0: T) -> T:
  330. ...
  331. def tanh(self, x0: T) -> T:
  332. ...
  333. def sigmoid(self, x0: T) -> T:
  334. ...
  335. def signbit(self, x0: T) -> T:
  336. ...
  337. def fmod(self, x0: T, x1: T) -> T:
  338. ...
  339. def log(self, x0: T) -> T:
  340. ...
  341. def isinf(self, x0: T) -> T:
  342. ...
  343. def isnan(self, x0: T) -> T:
  344. ...
  345. # NB: this returns a float, like the torch operation
  346. # This rounds half to even to break ties
  347. def round(self, x0: T) -> T:
  348. ...
  349. # NB: this returns a float, like the torch operation
  350. def floor(self, x0: T) -> T:
  351. ...
  352. def sign(self, x0: T) -> T:
  353. ...
  354. # NB: this returns a float, like the torch operation
  355. def trunc(self, x0: T) -> T:
  356. ...
  357. # NB: this returns a float, like the torch operation
  358. def ceil(self, x0: T) -> T:
  359. ...
  360. def neg(self, x0: T) -> T:
  361. ...
  362. def reciprocal(self, x0: T) -> T:
  363. ...
  364. def eq(self, x0: T, x1: T) -> T:
  365. ...
  366. def ne(self, x0: T, x1: T) -> T:
  367. ...
  368. def lt(self, x0: T, x1: T) -> T:
  369. ...
  370. def gt(self, x0: T, x1: T) -> T:
  371. ...
  372. def le(self, x0: T, x1: T) -> T:
  373. ...
  374. def ge(self, x0: T, x1: T) -> T:
  375. ...
  376. def add(self, x0: T, x1: T) -> T:
  377. ...
  378. def sub(self, x0: T, x1: T) -> T:
  379. ...
  380. def mul(self, x0: T, x1: T) -> T:
  381. ...
  382. # NB: this returns a float, like the torch operation
  383. def pow(self, x0: T, x1: T) -> T:
  384. ...
  385. def and_(self, x0: T, x1: T) -> T:
  386. ...
  387. def or_(self, x0: T, x1: T) -> T:
  388. ...
  389. def xor(self, x0: T, x1: T) -> T:
  390. ...
  391. # These are metaprogrammed by MockHandler._init_cls
  392. def lshift(self, x0: T, x1: T) -> T:
  393. ...
  394. def rshift(self, x0: T, x1: T) -> T:
  395. ...
  396. def getitem(self, x0: T, x1: T) -> T:
  397. # TODO: this is probably just illegal lol
  398. ...
  399. def matmul(self, x0: T, x1: T) -> T:
  400. # TODO: this is probably just illegal lol
  401. ...
  402. def invert(self, x0: T) -> T:
  403. ...
  404. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  405. # These are "special" operators. These only exist if the target
  406. # language actually supports the operator. Keep this in sync with
  407. # pointwise_overrides_data.
  408. def airy_ai(self, x: T) -> T:
  409. ...
  410. def bessel_j0(self, x: T) -> T:
  411. ...
  412. def bessel_j1(self, x: T) -> T:
  413. ...
  414. def bessel_y0(self, x: T) -> T:
  415. ...
  416. def bessel_y1(self, x: T) -> T:
  417. ...
  418. def digamma(self, x: T) -> T:
  419. ...
  420. def erfcx(self, x: T) -> T:
  421. ...
  422. def fma(self, x: T, y: T, z: T) -> T:
  423. ...
  424. def igamma(self, x: T, y: T) -> T:
  425. ...
  426. def igammac(self, x: T, y: T) -> T:
  427. ...
  428. def gammainc(self, x: T, y: T) -> T:
  429. ...
  430. def gammaincc(self, x: T, y: T) -> T:
  431. ...
  432. def i0(self, x: T) -> T:
  433. ...
  434. def i0e(self, x: T) -> T:
  435. ...
  436. def i1(self, x: T) -> T:
  437. ...
  438. def i1e(self, x: T) -> T:
  439. ...
  440. def log_ndtr(self, x: T) -> T:
  441. ...
  442. def modified_bessel_i0(self, x: T) -> T:
  443. ...
  444. def modified_bessel_i1(self, x: T) -> T:
  445. ...
  446. def modified_bessel_k0(self, x: T) -> T:
  447. ...
  448. def modified_bessel_k1(self, x: T) -> T:
  449. ...
  450. def ndtr(self, x: T) -> T:
  451. ...
  452. def ndtri(self, x: T) -> T:
  453. ...
  454. def polygamma(self, x: T, y: T) -> T:
  455. ...
  456. def scaled_modified_bessel_k0(self, x: T) -> T:
  457. ...
  458. def scaled_modified_bessel_k1(self, x: T) -> T:
  459. ...
  460. def spherical_bessel_j0(self, x: T) -> T:
  461. ...
  462. def zeta(self, x: T, y: T) -> T:
  463. ...
  464. def chebyshev_polynomial_t(self, x: T, y: T) -> T:
  465. ...
  466. def chebyshev_polynomial_u(self, x: T, y: T) -> T:
  467. ...
  468. def chebyshev_polynomial_v(self, x: T, y: T) -> T:
  469. ...
  470. def chebyshev_polynomial_w(self, x: T, y: T) -> T:
  471. ...
  472. def legendre_polynomial_p(self, x: T, y: T) -> T:
  473. ...
  474. def shifted_chebyshev_polynomial_t(self, x: T, y: T) -> T:
  475. ...
  476. def shifted_chebyshev_polynomial_u(self, x: T, y: T) -> T:
  477. ...
  478. def shifted_chebyshev_polynomial_v(self, x: T, y: T) -> T:
  479. ...
  480. def shifted_chebyshev_polynomial_w(self, x: T, y: T) -> T:
  481. ...
  482. def hermite_polynomial_h(self, x: T, y: T) -> T:
  483. ...
  484. def hermite_polynomial_he(self, x: T, y: T) -> T:
  485. ...
  486. def laguerre_polynomial_l(self, x: T, y: T) -> T:
  487. ...
  488. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  489. # These operators are a bit special, because they are conventionally
  490. # natively supported in both Python and C, but the semantics differ so
  491. # care must be taken
  492. def truncdiv(self, x0: T, x1: T) -> T:
  493. """C-style trunc division between integers only. Computes the true
  494. division of two numbers and rounds the result to zero.
  495. """
  496. ...
  497. def floordiv(self, x0: T, x1: T) -> T:
  498. """Python-style floor division between integers only. Computes the
  499. true division of two numbers and floors the result. If you want
  500. floor division for floats, do regular truediv and floor the result.
  501. """
  502. ...
  503. def truediv(self, x0: T, x1: T) -> T:
  504. """True division between floats. Integer inputs are NOT valid. To
  505. do Python-style (int, int) -> float division, use int_truediv"""
  506. ...
  507. def int_truediv(self, x0: T, x1: T) -> T:
  508. """True division between integers. This is NOT the same as promoting
  509. to float and doing integer division, there is a bespoke algorithm for
  510. doing the division in higher precision than the above.
  511. """
  512. ...
  513. def div(self, x0: T, x1: T) -> T:
  514. """TODO: to be removed. This renders as / no matter what the backend is
  515. which is incoherent."""
  516. ...
  517. def mod(self, x0: T, x1: T) -> T:
  518. """C-style modulus, take sign from LHS (x0)."""
  519. ...
  520. def remainder(self, x0: T, x1: T) -> T:
  521. """Python-style modulus, take sign from RHS (x1)."""
  522. ...
  523. def round_decimal(self, x0: T, x1: T) -> T:
  524. """Python-style round with decimal argument"""
  525. ...
  526. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  527. # In CUDA, optimized implementations of other mathematical operations are
  528. # offered separately via libdevice for double precision computation (in
  529. # Triton, these go to tl.math rather than tl). We lower to these
  530. # operators when doing FP64 on CUDA. Note that some operators
  531. # unconditional go to tl.math.
  532. #
  533. # TODO(ezyang): Is this really the best way to do this? What if we have
  534. # abs internally route to tl.math automatically when given a double
  535. # precision input? One reason is that when doing codegen, we often don't
  536. # know what the dtype of the inputs are! (In principle we do know, but
  537. # for many analyses it's not conveniently available.)
  538. def libdevice_abs(self, x0: T) -> T:
  539. ...
  540. def libdevice_exp(self, x0: T) -> T:
  541. ...
  542. def libdevice_sqrt(self, x0: T) -> T:
  543. ...
  544. def libdevice_cos(self, x0: T) -> T:
  545. ...
  546. def libdevice_sin(self, x0: T) -> T:
  547. ...
  548. def libdevice_sigmoid(self, x0: T) -> T:
  549. ...
  550. def libdevice_log(self, x0: T) -> T:
  551. ...
  552. class NoopHandler:
  553. def __getattr__(self, name):
  554. if name == "name":
  555. return "NoopHandler"
  556. def inner(*args, **kwargs):
  557. return None
  558. return inner
  559. @staticmethod
  560. def masked(mask, body, other) -> None:
  561. return None
  562. @staticmethod
  563. def frexp(x) -> Tuple[None, None]:
  564. return (None, None)
  565. @staticmethod
  566. def scan(dtypes, combine_fn, values) -> Tuple[None, ...]:
  567. return tuple(None for i in range(len(values)))
  568. @staticmethod
  569. def indirect_indexing(index_var, size, check=True) -> sympy.Symbol:
  570. return sympy.Integer(0)
  571. # Use mypy to check protocol implemented correctly
  572. def _typecheck_NoopHandler(h: NoopHandler) -> OpsHandler[None]:
  573. return h
  574. class MockHandler:
  575. def __getattr__(self, name):
  576. if name == "name":
  577. return "MockHandler"
  578. def inner(*args, **kwargs):
  579. fargs = [_arg_str(a) for a in args]
  580. fargs.extend(f"{k}={v}" for k, v in kwargs.items())
  581. return f"ops.{name}({', '.join(fargs)})"
  582. return inner
  583. @staticmethod
  584. def masked(mask, body, other) -> str:
  585. return f"ops.masked({mask}, {body()}, {other})"
  586. @staticmethod
  587. def frexp(x):
  588. return (f"ops.frexp({x})[0]", f"ops.frexp({x})[1]")
  589. @staticmethod
  590. def scan(dtypes, combine_fn, values):
  591. return tuple(
  592. f"ops.scan({dtypes}, {combine_fn}, {values})[{i}]"
  593. for i in range(len(values))
  594. )
  595. @staticmethod
  596. def indirect_indexing(index_var, size, check=True) -> sympy.Symbol:
  597. return sympy_index_symbol(str(index_var))
  598. @classmethod
  599. def _init_cls(cls):
  600. def make_handler(format_string):
  601. @staticmethod # type: ignore[misc]
  602. def inner(*args):
  603. return format_string.format(*args)
  604. return inner
  605. for name, format_string in {
  606. "add": "{} + {}",
  607. "sub": "{} - {}",
  608. "mul": "{} * {}",
  609. "floordiv": "{} // {}",
  610. "truediv": "{} / {}",
  611. "mod": "{} % {}", # careful, depending on target semantics varies
  612. "pow": "{} ** {}",
  613. "lshift": "{} << {}",
  614. "rshift": "{} >> {}",
  615. "and_": "{} & {}",
  616. "or_": "{} | {}",
  617. "xor": "{} ^ {}",
  618. "eq": "{} == {}",
  619. "ne": "{} != {}",
  620. "lt": "{} < {}",
  621. "gt": "{} > {}",
  622. "le": "{} <= {}",
  623. "ge": "{} >= {}",
  624. "neg": "-{}",
  625. }.items():
  626. setattr(cls, name, make_handler(format_string))
  627. MockHandler._init_cls()
  628. # Use mypy to check protocol implemented correctly
  629. def _typecheck_MockHandler(h: MockHandler) -> OpsHandler[str]:
  630. return h
  631. class KernelFormatterHandler:
  632. def __init__(self, parent_handler):
  633. self.parent_handler = parent_handler
  634. self.output = IndentedBuffer(1)
  635. self.var_counter = itertools.count()
  636. @staticmethod
  637. def ir_to_string(ir_fn, index, rindex=None) -> str:
  638. from .ir import FlexibleLayout
  639. from .virtualized import V
  640. args = [index, rindex] if rindex is not None else [index]
  641. names = ["index", "rindex"] if rindex is not None else ["index"]
  642. formatter = KernelFormatterHandler(MockHandler())
  643. with formatter.output.indent(-1):
  644. formatter.output.writeline(f"def inner_fn({', '.join(names)}):")
  645. for name, arg in zip(names, args):
  646. if arg:
  647. lhs = ", ".join(
  648. [
  649. str("_" if isinstance(v, (int, sympy.Integer)) else v)
  650. for v in arg
  651. ]
  652. )
  653. formatter.output.writeline(f"{lhs} = {name}")
  654. with V.set_ops_handler(formatter), patch.object(
  655. FlexibleLayout, "allow_indexing", True
  656. ):
  657. result = ir_fn(*args)
  658. return formatter.getvalue(result)
  659. def __getattr__(self, name) -> Callable[..., Any]:
  660. def inner(*args, **kwargs):
  661. line = getattr(self.parent_handler, name)(*args, **kwargs)
  662. if name == "indirect_indexing":
  663. return line
  664. def write(line):
  665. # replace line with a new variable name
  666. varname = f"tmp{next(self.var_counter)}"
  667. self.output.writeline(f"{varname} = {line}")
  668. return varname
  669. return pytree.tree_map(write, line)
  670. return inner
  671. def reduction(
  672. self,
  673. dtype: torch.dtype,
  674. src_dtype: torch.dtype,
  675. reduction_type: ReductionType,
  676. value: Union[str, Tuple[str, ...]],
  677. ) -> Union[str, Tuple[str, ...]]:
  678. line = self.parent_handler.reduction(dtype, src_dtype, reduction_type, value)
  679. num_values = reduction_num_outputs(reduction_type)
  680. varnames = [f"tmp{next(self.var_counter)}" for _ in range(num_values)]
  681. self.output.writeline(f"{','.join(varnames)} = {line}")
  682. return tuple(varnames) if num_values > 1 else varnames[0]
  683. def getvalue(self, result):
  684. self.output.writeline(f"return {result}")
  685. return self.output.getvalue()
  686. # Use mypy to check protocol implemented correctly
  687. def _typecheck_KernelFormatterHandler(h: KernelFormatterHandler) -> OpsHandler[str]:
  688. return h
  689. class WrapperHandler(Generic[T]):
  690. def __init__(self, inner: OpsHandler[T]):
  691. self._inner = inner
  692. def __getattr__(self, item):
  693. return getattr(self._inner, item)
  694. # Use mypy to check protocol implemented correctly
  695. def _typecheck_WrapperHandler(h: WrapperHandler[T]) -> OpsHandler[T]:
  696. return h
  697. class OpCounterCSE:
  698. """Shim to count how many ops are used"""
  699. def __init__(self, inner):
  700. super().__init__()
  701. self.parent_handler = inner
  702. self.op_count = 0
  703. self.var_names = {}
  704. def __getattr__(self, name):
  705. def inner(*args, **kwargs):
  706. val = getattr(self.parent_handler, name)(*args, **kwargs)
  707. if name == "indirect_indexing":
  708. return val
  709. def count(val):
  710. if val not in self.var_names:
  711. varname = f"tmp{self.op_count}"
  712. self.op_count += 1
  713. self.var_names[val] = varname
  714. return varname
  715. else:
  716. return self.var_names[val]
  717. return pytree.tree_map(count, val)
  718. return inner
  719. def _typecheck_OpCounterCSE(h: OpCounterCSE) -> OpsHandler[str]:
  720. return h
  721. class ExtractConstantsHandler(NoopHandler):
  722. def __init__(self, device):
  723. self.device = device
  724. def constant(self, value: Any, dtype: torch.dtype) -> "torch._inductor.ir.Constant":
  725. from torch._inductor import ir
  726. return ir.Constant(value=value, dtype=dtype, device=self.device)
  727. def _typecheck_ExtractConstantsHandler(h: ExtractConstantsHandler) -> OpsHandler[Any]:
  728. return h
  729. class SimpleCSEHandler(WrapperHandler[T]):
  730. """Wraps the underlying handler with a CSE pass
  731. NOTE: Compared to codegen level CSE this is simplified as it
  732. doesn't support stores which require load cache invalidation.
  733. """
  734. def __init__(self, inner: OpsHandler[T]):
  735. super().__init__(inner)
  736. self.cse_cache: Dict[str, Union[T, Tuple[T, ...]]] = {}
  737. self.mock = MockHandler()
  738. def indirect_indexing(self, *args, **kwargs) -> sympy.Expr:
  739. return super().indirect_indexing(*args, **kwargs) # type: ignore[misc]
  740. def store(self, *args, **kwargs) -> T:
  741. raise NotImplementedError("store not implemented")
  742. def store_reduction(self, *args, **kwargs) -> T:
  743. raise NotImplementedError("store not implemented")
  744. def __getattr__(self, name) -> Callable[..., Any]:
  745. def inner(*args, **kwargs):
  746. key = getattr(self.mock, name)(*args, **kwargs)
  747. val = self.cse_cache.get(key)
  748. if val is not None:
  749. return val
  750. val = getattr(self._inner, name)(*args, **kwargs)
  751. self.cse_cache[key] = val
  752. return val
  753. return inner
  754. def _typecheck_SimpleCSEHandler(h: SimpleCSEHandler[Any]) -> OpsHandler[Any]:
  755. return h