functions.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424
  1. # mypy: allow-untyped-defs
  2. import functools
  3. import math
  4. import operator
  5. import sys
  6. from collections.abc import Callable
  7. from typing import Optional, SupportsFloat, TYPE_CHECKING, TypeVar, Union
  8. from typing_extensions import TypeVarTuple, Unpack
  9. import sympy
  10. from sympy import S
  11. from sympy.core import sympify
  12. from sympy.core.expr import Expr
  13. from sympy.core.function import Application
  14. from sympy.core.logic import _torf, fuzzy_and, fuzzy_or
  15. from sympy.core.numbers import equal_valued
  16. from sympy.core.operations import LatticeOp, ShortCircuit
  17. from sympy.core.sorting import ordered
  18. from sympy.core.traversal import walk
  19. from sympy.printing.precedence import PRECEDENCE
  20. from sympy.utilities.iterables import sift
  21. from .numbers import int_oo
  22. if TYPE_CHECKING:
  23. from collections.abc import Iterable
  24. _T = TypeVar("_T", bound=SupportsFloat)
  25. _Ts = TypeVarTuple("_Ts")
  26. # Portions of this file are adapted from the Sympy codebase, which was
  27. # licensed as follows:
  28. #
  29. # Copyright (c) 2006-2023 SymPy Development Team
  30. #
  31. # All rights reserved.
  32. #
  33. # Redistribution and use in source and binary forms, with or without
  34. # modification, are permitted provided that the following conditions are met:
  35. #
  36. # a. Redistributions of source code must retain the above copyright notice,
  37. # this list of conditions and the following disclaimer.
  38. # b. Redistributions in binary form must reproduce the above copyright
  39. # notice, this list of conditions and the following disclaimer in the
  40. # documentation and/or other materials provided with the distribution.
  41. # c. Neither the name of SymPy nor the names of its contributors
  42. # may be used to endorse or promote products derived from this software
  43. # without specific prior written permission.
  44. #
  45. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  46. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  47. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  48. # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
  49. # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  50. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  51. # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  52. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  53. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  54. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  55. # DAMAGE.
  56. __all__ = [
  57. "FloorDiv",
  58. "ModularIndexing",
  59. "Where",
  60. "PythonMod",
  61. "Mod",
  62. "CleanDiv",
  63. "CeilToInt",
  64. "FloorToInt",
  65. "CeilDiv",
  66. "IntTrueDiv",
  67. "FloatTrueDiv",
  68. "LShift",
  69. "RShift",
  70. "IsNonOverlappingAndDenseIndicator",
  71. "TruncToFloat",
  72. "TruncToInt",
  73. "RoundToInt",
  74. "RoundDecimal",
  75. "ToFloat",
  76. "FloatPow",
  77. "PowByNatural",
  78. "Identity",
  79. ]
  80. def _is_symbols_binary_summation(expr: sympy.Expr) -> bool:
  81. # No need to check that two args are not the same, since expr is pr-optimized but we do it anyway.
  82. return (
  83. expr.is_Add
  84. and len(expr._args) == 2
  85. and expr._args[0].is_symbol
  86. and expr._args[1].is_symbol
  87. and expr._args[0] is not expr._args[1]
  88. )
  89. def _keep_float(
  90. f: Callable[[Unpack[_Ts]], _T],
  91. ) -> Callable[[Unpack[_Ts]], Union[_T, sympy.Float]]:
  92. @functools.wraps(f)
  93. def inner(*args: Unpack[_Ts]) -> Union[_T, sympy.Float]:
  94. r: Union[_T, sympy.Float] = f(*args)
  95. if any(isinstance(a, sympy.Float) for a in args) and not isinstance(
  96. r, sympy.Float
  97. ):
  98. r = sympy.Float(float(r))
  99. return r
  100. return inner
  101. def fuzzy_eq(x: Optional[bool], y: Optional[bool]) -> Optional[bool]:
  102. if None in (x, y):
  103. return None
  104. return x == y
  105. def simple_floordiv_gcd(p: sympy.Basic, q: sympy.Basic) -> sympy.Basic:
  106. """
  107. Fast path for sympy.gcd, using a simple factoring strategy.
  108. We try to rewrite p and q in the form n*e*p1 + n*e*p2 and n*e*q0,
  109. where n is the greatest common integer factor and e is the largest
  110. syntactic common factor (i.e., common sub-expression) in p and q.
  111. Then the gcd returned is n*e, cancelling which we would be left with
  112. p1 + p2 and q0.
  113. Note that further factoring of p1 + p2 and q0 might be possible with
  114. sympy.factor (which uses domain-specific theories). E.g., we are unable
  115. to find that x*y + x + y + 1 is divisible by x + 1. More generally,
  116. when q is of the form q1 + q2 (instead of being already factored) it
  117. might be necessary to fall back on sympy.gcd.
  118. """
  119. def integer_coefficient(x: sympy.Basic) -> int:
  120. integer_coefficients: list[int] = [
  121. abs(int(arg))
  122. for arg in sympy.Mul.make_args(x)
  123. if isinstance(arg, (int, sympy.Integer))
  124. ]
  125. return math.prod(integer_coefficients)
  126. def integer_factor(expr: sympy.Basic) -> int:
  127. integer_factors: Iterable[int] = map(
  128. integer_coefficient, sympy.Add.make_args(expr)
  129. )
  130. return functools.reduce(math.gcd, integer_factors)
  131. gcd: int = math.gcd(integer_factor(p), integer_factor(q))
  132. p, q = p / gcd, q / gcd # type: ignore[operator, assignment] # remove in py3.12
  133. base_splits: list[tuple[sympy.Basic, ...]] = list(
  134. map(sympy.Mul.make_args, sympy.Add.make_args(p))
  135. )
  136. divisor_split: tuple[sympy.Basic, ...] = sympy.Mul.make_args(q)
  137. for x in divisor_split:
  138. if all(x in base_split for base_split in base_splits):
  139. gcd = gcd * x # type: ignore[operator] # remove in py3.12
  140. return gcd # type: ignore[return-value] # remove in py3.12
  141. # It would be nice to have assertions on whether or not inputs is_integer
  142. # However, with bugs like https://github.com/sympy/sympy/issues/26620 sympy
  143. # sometimes inconsistently reports floats an integers.
  144. #
  145. # What we can assume from sympy is that if something is an int, it
  146. # definitely is is_integer, but if it is a float it may or may not
  147. # be is_integer. So we are unable to do strong asserts that things
  148. # are NOT integers.
  149. # TODO: In Triton, // rounds to zero, but in Python, it is floor division.
  150. # When we can prove both arguments are non-negative, we should just have a
  151. # GenericFloorDiv (name pending) which can codegen efficiently in Python/C,
  152. # and then PythonFloorDiv and CIntDiv which have the appropriate rounding
  153. # semantics.
  154. #
  155. # Right now, FloorDiv de facto changes behavior if arguments are negative or
  156. # not, this can potentially cause correctness issues.
  157. class FloorDiv(sympy.Function):
  158. """
  159. We maintain this so that:
  160. 1. We can use divisibility guards to simplify FloorDiv(a, b) to a / b.
  161. 2. Printing out the expression is nicer (compared to say, representing a//b as (a - a % b) / b)
  162. NB: This is Python-style floor division, round to -Inf
  163. """
  164. nargs: tuple[int, ...] = (2,)
  165. precedence: int = 35 # lower precedence than add
  166. is_integer: bool = True
  167. @property
  168. def base(self) -> sympy.Basic:
  169. return self.args[0]
  170. @property
  171. def divisor(self) -> sympy.Basic:
  172. return self.args[1]
  173. def _sympystr(self, printer: sympy.printing.StrPrinter) -> str:
  174. base = printer.parenthesize(self.base, PRECEDENCE["Atom"] - 0.5)
  175. divisor = printer.parenthesize(self.divisor, PRECEDENCE["Atom"] - 0.5)
  176. return f"({base}//{divisor})"
  177. # Automatic evaluation.
  178. # https://docs.sympy.org/latest/guides/custom-functions.html#best-practices-for-eval
  179. @classmethod
  180. def eval(
  181. cls, base: sympy.Integer, divisor: sympy.Integer
  182. ) -> Union[sympy.Basic, None]:
  183. # python test/test_dynamic_shapes.py -k TestDimConstraints.test_dim_constraints_solve_full
  184. # Assert triggered by inequality solver
  185. # assert base.is_integer, base
  186. # assert divisor.is_integer, divisor
  187. # We don't provide the same error message as in Python because SymPy
  188. # makes it difficult to check the types.
  189. if divisor.is_zero:
  190. raise ZeroDivisionError("division by zero")
  191. if base in (int_oo, -int_oo, sympy.oo, -sympy.oo) and divisor in (
  192. int_oo,
  193. -int_oo,
  194. sympy.oo,
  195. -sympy.oo,
  196. ):
  197. return sympy.nan
  198. if base is sympy.nan or divisor is sympy.nan:
  199. return sympy.nan
  200. if base.is_zero:
  201. return sympy.S.Zero
  202. if base.is_integer and equal_valued(divisor, 1):
  203. return base
  204. if base.is_integer and equal_valued(divisor, -1):
  205. return sympy.Mul(base, -1)
  206. if (
  207. isinstance(base, sympy.Number)
  208. and isinstance(divisor, sympy.Number)
  209. and (
  210. base in (int_oo, -int_oo, sympy.oo, -sympy.oo)
  211. or divisor in (int_oo, -int_oo, sympy.oo, -sympy.oo)
  212. )
  213. ):
  214. r = float(base) / float(divisor)
  215. if r == math.inf:
  216. return int_oo
  217. elif r == -math.inf:
  218. return -int_oo
  219. elif math.isnan(r):
  220. return sympy.nan
  221. else:
  222. return sympy.Integer(math.floor(r))
  223. if isinstance(base, sympy.Integer) and isinstance(divisor, sympy.Integer):
  224. return sympy.Integer(int(base) // int(divisor))
  225. if isinstance(base, FloorDiv):
  226. return FloorDiv(base.args[0], base.args[1] * divisor)
  227. # Expands (x + y) // b into x // b + y // b.
  228. # This only works if floor is an identity, i.e. x / b is an integer.
  229. if isinstance(divisor, sympy.Integer):
  230. quotients = 0
  231. terms = []
  232. for term in sympy.Add.make_args(base):
  233. quotient = term / divisor
  234. if quotient.is_integer:
  235. terms.append(term)
  236. quotients += quotient
  237. if len(terms) != 0:
  238. # Passing evaluate = False since expression will be optimized during the subtraction post its construction.
  239. return (
  240. FloorDiv(base - sympy.Add(*terms, evaluate=False), divisor)
  241. + quotients
  242. )
  243. try:
  244. gcd = simple_floordiv_gcd(base, divisor)
  245. if equal_valued(gcd, 1) and isinstance(divisor, sympy.Add):
  246. gcd = sympy.gcd(base, divisor)
  247. if not equal_valued(gcd, 1):
  248. return FloorDiv(
  249. sympy.simplify(base / gcd), sympy.simplify(divisor / gcd)
  250. )
  251. except sympy.PolynomialError:
  252. pass # https://github.com/pytorch/pytorch/issues/108276
  253. return None
  254. def _ccode(self, printer):
  255. base = printer.parenthesize(self.base, PRECEDENCE["Atom"] - 0.5)
  256. divisor = printer.parenthesize(self.divisor, PRECEDENCE["Atom"] - 0.5)
  257. return f"floor({base}/{divisor})"
  258. class ModularIndexing(sympy.Function):
  259. """
  260. ModularIndexing(a, b, c) => (a // b) % c where % is the C modulus
  261. """
  262. nargs: tuple[int, ...] = (3,)
  263. is_integer: bool = True
  264. precedence: int = 35 # lower precedence than add
  265. @classmethod
  266. def eval(
  267. cls, base: sympy.Integer, divisor: sympy.Integer, modulus: sympy.Integer
  268. ) -> Optional[sympy.Basic]:
  269. if base == 0 or modulus == 1:
  270. return sympy.S.Zero
  271. if (
  272. isinstance(base, sympy.Integer)
  273. and isinstance(divisor, sympy.Integer)
  274. and isinstance(modulus, sympy.Integer)
  275. ):
  276. return (base // divisor) % modulus
  277. try:
  278. if divisor != 1:
  279. gcd = sympy.gcd(base, divisor)
  280. if gcd != 1:
  281. return ModularIndexing(
  282. sympy.simplify(base / gcd),
  283. sympy.simplify(divisor / gcd),
  284. modulus,
  285. )
  286. except sympy.PolynomialError:
  287. pass # https://github.com/pytorch/pytorch/issues/108276
  288. if isinstance(base, sympy.Add):
  289. new_terms: list[sympy.Integer] = []
  290. all_positive: bool = True
  291. for term in base.args:
  292. if sympy.gcd(term, modulus * divisor) != modulus * divisor:
  293. if (isinstance(term, sympy.Integer) and term < 0) or (
  294. isinstance(term, sympy.Mul)
  295. and isinstance(term.args[0], sympy.Integer)
  296. and term.args[0] < 0
  297. ):
  298. # workaround for https://github.com/triton-lang/triton/issues/619,
  299. # if there are negative terms, // produces wrong result
  300. # TODO if https://github.com/triton-lang/triton/issues/619 is fixed
  301. # this optimization would become valid
  302. all_positive = False
  303. break
  304. else:
  305. new_terms.append(term)
  306. if len(new_terms) != len(base.args) and all_positive:
  307. return ModularIndexing(sum(new_terms), divisor, modulus)
  308. if isinstance(base, FloorDiv):
  309. return ModularIndexing(base.args[0], base.args[1] * divisor, modulus)
  310. return None
  311. def _eval_is_nonnegative(self) -> Optional[bool]:
  312. p, q = self.args[:2]
  313. return fuzzy_eq(p.is_nonnegative, q.is_nonnegative) # type: ignore[attr-defined]
  314. class Where(sympy.Function):
  315. """
  316. Good ol' ternary operator
  317. """
  318. nargs: tuple[int, ...] = (3,)
  319. precedence: int = 35 # lower precedence than add
  320. def _eval_is_integer(self) -> Optional[bool]:
  321. return True if self.args[1].is_integer and self.args[2].is_integer else None # type: ignore[attr-defined]
  322. def _eval_is_nonnegative(self) -> Optional[bool]:
  323. return (
  324. True
  325. if self.args[1].is_nonnegative and self.args[2].is_nonnegative # type: ignore[attr-defined]
  326. else None
  327. )
  328. def _eval_is_positive(self) -> Optional[bool]:
  329. return True if self.args[1].is_positive and self.args[2].is_positive else None # type: ignore[attr-defined]
  330. @classmethod
  331. def eval(
  332. cls, c: sympy.Basic, p: sympy.Basic, q: sympy.Basic
  333. ) -> Optional[sympy.Basic]:
  334. if c == sympy.true:
  335. return p
  336. elif c == sympy.false:
  337. return q
  338. return None
  339. # Python-style modulus: take sign from RHS
  340. class PythonMod(sympy.Function):
  341. nargs: tuple[int, ...] = (2,)
  342. precedence: int = 35 # lower precedence than add
  343. is_integer: bool = True
  344. @classmethod
  345. def eval(cls, p: sympy.Expr, q: sympy.Expr) -> Optional[sympy.Expr]:
  346. # python test/dynamo/test_export.py -k ExportTests.test_trivial_constraint
  347. # Triggered by sympy.solvers.inequalities.reduce_inequalities
  348. # assert p.is_integer, p
  349. # assert q.is_integer, q
  350. if q.is_zero:
  351. raise ZeroDivisionError("Modulo by zero")
  352. # Three cases:
  353. # 1. p == 0
  354. # 2. p is either q or -q
  355. # 3. p is integer and q == 1
  356. if p is S.Zero or p in (q, -q) or q == 1:
  357. return S.Zero
  358. # Evaluate if they are both literals.
  359. if q.is_Number and p.is_Number:
  360. return p % q
  361. # If q == 2, it's a matter of whether p is odd or even.
  362. if q.is_Number and q == 2:
  363. if p.is_even:
  364. return S.Zero
  365. if p.is_odd:
  366. return S.One
  367. # If p is a multiple of q.
  368. r = p / q
  369. if r.is_integer:
  370. return S.Zero
  371. # If p < q and its ratio is positive, then:
  372. # - floor(p / q) = 0
  373. # - p % q = p - floor(p / q) * q = p
  374. less = p < q
  375. if less.is_Boolean and bool(less) and r.is_positive:
  376. return p
  377. if sympy.Mod(p, q) == 0:
  378. return S.Zero
  379. return None
  380. # NB: args[1] for PythonMod
  381. def _eval_is_nonnegative(self) -> Optional[bool]:
  382. return True if self.args[1].is_positive else None # type: ignore[attr-defined]
  383. def _eval_is_nonpositive(self) -> Optional[bool]:
  384. return True if self.args[1].is_negative else None # type: ignore[attr-defined]
  385. def _ccode(self, printer):
  386. p = printer.parenthesize(self.args[0], PRECEDENCE["Atom"] - 0.5)
  387. q = printer.parenthesize(self.args[1], PRECEDENCE["Atom"] - 0.5)
  388. abs_q = str(q) if self.args[1].is_positive else f"abs({q})"
  389. return f"({p} % {q}) < 0 ? {p} % {q} + {abs_q} : {p} % {q}"
  390. # Generic modulus: only defined on non-negative arguments
  391. class Mod(sympy.Function):
  392. nargs = (2,)
  393. precedence: int = 35 # lower precedence than add
  394. is_integer = True
  395. is_nonnegative = True
  396. @classmethod
  397. def eval(cls, p, q):
  398. # This was adapted from: sympy/core/mod.py
  399. # Triggered by
  400. # python test/test_dynamic_shapes.py -k TestDimConstraints.test_dim_constraints_solve_full
  401. # assert p.is_integer, p
  402. # assert q.is_integer, q
  403. if q.is_zero:
  404. raise ZeroDivisionError("Modulo by zero")
  405. # Three cases:
  406. # 1. p == 0
  407. # 2. p is either q or -q
  408. # 3. p is integer and q == 1
  409. if p is S.Zero or p in (q, -q) or q == 1:
  410. return S.Zero
  411. # Evaluate if they are both literals.
  412. if q.is_Number and p.is_Number:
  413. assert p >= 0, p
  414. assert q >= 1, q
  415. return p % q
  416. # If q == 2, it's a matter of whether p is odd or even.
  417. if q.is_Number and q == 2:
  418. if p.is_even:
  419. return S.Zero
  420. if p.is_odd:
  421. return S.One
  422. # If p is a multiple of q.
  423. r = p / q
  424. if r.is_integer:
  425. return S.Zero
  426. # If p < q and its ratio is positive, then:
  427. # - floor(p / q) = 0
  428. # - p % q = p - floor(p / q) * q = p
  429. less = p < q
  430. if less.is_Boolean and bool(less) and r.is_positive:
  431. return p
  432. class CleanDiv(FloorDiv):
  433. """
  434. Div where we can assume no rounding.
  435. This is to enable future optimizations.
  436. """
  437. # Don't use sympy ceiling/floor as they will attempt simplifications involving
  438. # frac
  439. class CeilToInt(sympy.Function):
  440. is_integer = True
  441. @classmethod
  442. def eval(cls, number):
  443. # assert number.is_integer is not True, number
  444. if number in (sympy.oo, int_oo):
  445. return int_oo
  446. if number in (-sympy.oo, -int_oo):
  447. return -int_oo
  448. if isinstance(number, sympy.Number):
  449. return sympy.Integer(math.ceil(float(number)))
  450. def _ccode(self, printer):
  451. number = printer.parenthesize(self.args[0], self.args[0].precedence - 0.5)
  452. return f"ceil({number})"
  453. class FloorToInt(sympy.Function):
  454. is_integer = True
  455. @classmethod
  456. def eval(cls, number):
  457. if number in (sympy.oo, int_oo):
  458. return int_oo
  459. if number in (-sympy.oo, int_oo):
  460. return -int_oo
  461. if isinstance(number, sympy.Integer):
  462. return number
  463. if isinstance(number, sympy.Number):
  464. return sympy.Integer(math.floor(float(number)))
  465. class CeilDiv(sympy.Function):
  466. """
  467. Div used in indexing that rounds up.
  468. """
  469. is_integer = True
  470. def __new__(cls, base, divisor):
  471. base = sympy.sympify(base)
  472. divisor = sympy.sympify(divisor)
  473. if sympy.gcd(base, divisor) == divisor:
  474. return CleanDiv(base, divisor)
  475. else:
  476. return FloorDiv(base + (divisor - 1), divisor)
  477. class LShift(sympy.Function):
  478. is_integer = True
  479. @classmethod
  480. def eval(cls, base, shift):
  481. if shift < 0:
  482. raise ValueError("negative shift count")
  483. return base * 2**shift
  484. class RShift(sympy.Function):
  485. is_integer = True
  486. @classmethod
  487. def eval(cls, base, shift):
  488. if shift < 0:
  489. raise ValueError("negative shift count")
  490. return FloorDiv(base, 2**shift)
  491. class MinMaxBase(Expr, LatticeOp): # type: ignore[misc]
  492. def __new__(cls, *original_args, **assumptions):
  493. from sympy.core.parameters import global_parameters
  494. evaluate = assumptions.pop("evaluate", global_parameters.evaluate)
  495. args = (sympify(arg) for arg in original_args)
  496. # See the comment in _satisfy_unique_summations_symbols.
  497. unique_summations_symbols = (
  498. None
  499. if not evaluate
  500. else cls._satisfy_unique_summations_symbols(original_args)
  501. )
  502. if evaluate:
  503. try:
  504. # first standard filter, for cls.zero and cls.identity
  505. # also reshape Max(a, Max(b, c)) to Max(a, b, c)
  506. args = frozenset(cls._new_args_filter(args)) # type: ignore[assignment]
  507. except ShortCircuit:
  508. return cls.zero # type: ignore[attr-defined]
  509. # No need to run _collapse_arguments and _find_localzeros, see the comment
  510. # in _satisfy_unique_summations_symbols.
  511. if unique_summations_symbols is None:
  512. # remove redundant args that are easily identified
  513. args = cls._collapse_arguments(args, **assumptions)
  514. # find local zeros
  515. args = cls._find_localzeros(args, **assumptions)
  516. args = frozenset(args)
  517. if not args:
  518. return cls.identity # type: ignore[attr-defined]
  519. if len(args) == 1:
  520. return list(args).pop()
  521. # base creation
  522. obj = Expr.__new__(cls, *ordered(args), **assumptions)
  523. obj._argset = args
  524. obj.unique_summations_symbols = unique_summations_symbols
  525. return obj
  526. @classmethod
  527. def _satisfy_unique_summations_symbols(
  528. cls, args
  529. ) -> Optional[set[sympy.core.symbol.Symbol]]:
  530. """
  531. One common case in some models is building expressions of the form
  532. max(max(max(a+b...), c+d), e+f) which is simplified to max(a+b, c+d, e+f, ...).
  533. For such expressions, we call the Max constructor X times (once for each nested
  534. max) and the expression gets flattened.
  535. An expensive cost in constructing those expressions is running _collapse_arguments
  536. and _find_localzeros. However, those two optimizations are unnecessary when the args
  537. to max are all of the form a+b, c+d, ..etc where each term uses a unique set of symbols.
  538. This function is used to detect such properties of the expressions we are building
  539. and if so inform that we do not need to run those optimizations. To detect those,
  540. we store a property in the expression that tells that this expression is a min/max
  541. operation over terms that use unique symbols "unique_summations_symbols". This property
  542. also memoize the set of symbols used in all the terms to make it faster to detect this
  543. property inductively.
  544. When we apply max to add a new term, all we need to do is check if the new term uses
  545. unique symbols (with respect to existing terms and itself).
  546. Example:
  547. t = Max(a+b, c+d) ==> satisfies the property
  548. Max(t, h+j) ==> h,j not in [a,b,c,d] => satisfy the property.
  549. The function returns None if the new expression does not satisfy the unique_summations_symbols
  550. property. Otherwise, it returns a new set of unique symbols.
  551. """
  552. if len(args) != 2:
  553. return None
  554. (lhs, rhs) = (
  555. (args[1], args[0])
  556. if isinstance(args[1], MinMaxBase)
  557. else (args[0], args[1])
  558. )
  559. if not _is_symbols_binary_summation(rhs):
  560. return None
  561. # base case max(a+b, c+d) ==> satisfies the property if a+b and c+d use unique symbols.
  562. if _is_symbols_binary_summation(lhs):
  563. return cls._unique_symbols(args)
  564. # inductive case max(t, h+j) ==> satisfies the property if h, j not in t.unique_summations_symbols
  565. if isinstance(lhs, MinMaxBase):
  566. lhs_unique_summations_symbols = getattr(
  567. lhs, "unique_summations_symbols", None
  568. )
  569. if lhs_unique_summations_symbols is not None:
  570. return cls._unique_symbols([rhs], lhs_unique_summations_symbols)
  571. return None
  572. @classmethod
  573. def _unique_symbols(
  574. cls, args, initial_set: Optional[set[sympy.core.symbol.Symbol]] = None
  575. ) -> Optional[set[sympy.core.symbol.Symbol]]:
  576. """
  577. Return seen_symbols if all atoms in all args are all unique symbols,
  578. else returns None. initial_set can be used to represent initial value for seen_symbols
  579. """
  580. seen_symbols = set() if initial_set is None else initial_set
  581. for arg in args:
  582. for element in arg.atoms():
  583. if not isinstance(element, sympy.core.symbol.Symbol):
  584. return None
  585. elif element in seen_symbols:
  586. return None
  587. else:
  588. seen_symbols.add(element)
  589. return seen_symbols
  590. @classmethod
  591. def _collapse_arguments(cls, args, **assumptions):
  592. """Remove redundant args.
  593. Examples
  594. ========
  595. >>> from sympy import Min, Max
  596. >>> from sympy.abc import a, b, c, d, e
  597. Any arg in parent that appears in any
  598. parent-like function in any of the flat args
  599. of parent can be removed from that sub-arg:
  600. >>> Min(a, Max(b, Min(a, c, d)))
  601. Min(a, Max(b, Min(c, d)))
  602. If the arg of parent appears in an opposite-than parent
  603. function in any of the flat args of parent that function
  604. can be replaced with the arg:
  605. >>> Min(a, Max(b, Min(c, d, Max(a, e))))
  606. Min(a, Max(b, Min(a, c, d)))
  607. """
  608. if not args:
  609. return args
  610. args = list(ordered(args))
  611. if cls is Min:
  612. other = Max
  613. else:
  614. other = Min # type: ignore[assignment]
  615. # find global comparable max of Max and min of Min if a new
  616. # value is being introduced in these args at position 0 of
  617. # the ordered args
  618. if args[0].is_number:
  619. sifted = mins, maxs = [], [] # type: ignore[var-annotated]
  620. for i in args:
  621. for v in walk(i, Min, Max):
  622. if v.args[0].is_comparable:
  623. sifted[isinstance(v, Max)].append(v)
  624. small = Min.identity
  625. for i in mins:
  626. v = i.args[0]
  627. if v.is_number and (v < small) == True: # noqa: E712
  628. small = v
  629. big = Max.identity
  630. for i in maxs:
  631. v = i.args[0]
  632. if v.is_number and (v > big) == True: # noqa: E712
  633. big = v
  634. # at the point when this function is called from __new__,
  635. # there may be more than one numeric arg present since
  636. # local zeros have not been handled yet, so look through
  637. # more than the first arg
  638. if cls is Min:
  639. for arg in args:
  640. if not arg.is_number:
  641. break
  642. if (arg < small) == True: # noqa: E712
  643. small = arg
  644. elif cls == Max:
  645. for arg in args:
  646. if not arg.is_number:
  647. break
  648. if (arg > big) == True: # noqa: E712
  649. big = arg
  650. T = None
  651. if cls is Min:
  652. if small != Min.identity:
  653. other = Max
  654. T = small
  655. elif big != Max.identity:
  656. other = Min # type: ignore[assignment]
  657. T = big
  658. if T is not None:
  659. # remove numerical redundancy
  660. for i in range(len(args)):
  661. a = args[i]
  662. if isinstance(a, other):
  663. a0 = a.args[0]
  664. if ( # noqa: E712
  665. (a0 > T) if other == Max else (a0 < T) # noqa: E712
  666. ) == True: # noqa: E712
  667. args[i] = cls.identity # type: ignore[attr-defined]
  668. # remove redundant symbolic args
  669. def do(ai, a):
  670. if not isinstance(ai, (Min, Max)):
  671. return ai
  672. cond = a in ai.args
  673. if not cond:
  674. return ai.func(*[do(i, a) for i in ai.args], evaluate=False)
  675. if isinstance(ai, cls):
  676. return ai.func(*[do(i, a) for i in ai.args if i != a], evaluate=False)
  677. return a
  678. for i, a in enumerate(args):
  679. args[i + 1 :] = [do(ai, a) for ai in args[i + 1 :]]
  680. # factor out common elements as for
  681. # Min(Max(x, y), Max(x, z)) -> Max(x, Min(y, z))
  682. # and vice versa when swapping Min/Max -- do this only for the
  683. # easy case where all functions contain something in common;
  684. # trying to find some optimal subset of args to modify takes
  685. # too long
  686. def factor_minmax(args):
  687. is_other = lambda arg: isinstance(arg, other) # noqa: E731
  688. other_args, remaining_args = sift(args, is_other, binary=True)
  689. if not other_args:
  690. return args
  691. # Min(Max(x, y, z), Max(x, y, u, v)) -> {x,y}, ({z}, {u,v})
  692. arg_sets = [set(arg.args) for arg in other_args]
  693. common = set.intersection(*arg_sets)
  694. if not common:
  695. return args
  696. new_other_args = list(common)
  697. arg_sets_diff = [arg_set - common for arg_set in arg_sets]
  698. # If any set is empty after removing common then all can be
  699. # discarded e.g. Min(Max(a, b, c), Max(a, b)) -> Max(a, b)
  700. if all(arg_sets_diff):
  701. other_args_diff = [other(*s, evaluate=False) for s in arg_sets_diff]
  702. new_other_args.append(cls(*other_args_diff, evaluate=False))
  703. other_args_factored = other(*new_other_args, evaluate=False)
  704. return remaining_args + [other_args_factored]
  705. if len(args) > 1:
  706. args = factor_minmax(args)
  707. return args
  708. @classmethod
  709. def _new_args_filter(cls, arg_sequence):
  710. """
  711. Generator filtering args.
  712. first standard filter, for cls.zero and cls.identity.
  713. Also reshape ``Max(a, Max(b, c))`` to ``Max(a, b, c)``,
  714. and check arguments for comparability
  715. """
  716. for arg in arg_sequence:
  717. # pre-filter, checking comparability of arguments
  718. if (
  719. not isinstance(arg, Expr)
  720. or arg.is_extended_real is False
  721. or (arg.is_number and not arg.is_comparable)
  722. ):
  723. raise ValueError(f"The argument '{arg}' is not comparable.")
  724. if arg == cls.zero: # type: ignore[attr-defined]
  725. raise ShortCircuit(arg)
  726. elif arg == cls.identity: # type: ignore[attr-defined]
  727. continue
  728. elif arg.func == cls:
  729. yield from arg.args
  730. else:
  731. yield arg
  732. @classmethod
  733. def _find_localzeros(cls, values, **options):
  734. """
  735. Sequentially allocate values to localzeros.
  736. When a value is identified as being more extreme than another member it
  737. replaces that member; if this is never true, then the value is simply
  738. appended to the localzeros.
  739. Unlike the sympy implementation, we only look for zero and one, we don't
  740. do generic is connected test pairwise which is slow
  741. """
  742. # First, collapse all numeric arguments
  743. other_values = set()
  744. num_value = None
  745. for arg in values:
  746. if arg.is_Number:
  747. if num_value is None:
  748. num_value = arg
  749. else:
  750. if cls is Max:
  751. num_value = max(num_value, arg)
  752. elif cls is Min:
  753. num_value = min(num_value, arg)
  754. else:
  755. raise AssertionError(f"impossible {cls}")
  756. else:
  757. other_values.add(arg)
  758. # Special cases when there is only one symbolic value
  759. if num_value is None:
  760. return other_values
  761. if len(other_values) == 0:
  762. return {num_value}
  763. if len(other_values) == 1:
  764. other_value = next(iter(other_values))
  765. if num_value in (0.0, 0) and other_value.is_nonnegative:
  766. return other_values if cls is Max else {num_value}
  767. if num_value == 1 and other_value.is_positive:
  768. return other_values if cls is Max else {num_value}
  769. other_values.add(num_value)
  770. return other_values
  771. _eval_is_algebraic = lambda s: _torf(i.is_algebraic for i in s.args) # noqa: E731
  772. _eval_is_antihermitian = lambda s: _torf( # noqa: E731
  773. i.is_antihermitian
  774. for i in s.args # noqa: E731
  775. ) # noqa: E731
  776. _eval_is_commutative = lambda s: _torf( # noqa: E731
  777. i.is_commutative
  778. for i in s.args # noqa: E731
  779. ) # noqa: E731
  780. _eval_is_complex = lambda s: _torf(i.is_complex for i in s.args) # noqa: E731
  781. _eval_is_composite = lambda s: _torf(i.is_composite for i in s.args) # noqa: E731
  782. _eval_is_even = lambda s: _torf(i.is_even for i in s.args) # noqa: E731
  783. _eval_is_finite = lambda s: _torf(i.is_finite for i in s.args) # noqa: E731
  784. _eval_is_hermitian = lambda s: _torf(i.is_hermitian for i in s.args) # noqa: E731
  785. _eval_is_imaginary = lambda s: _torf(i.is_imaginary for i in s.args) # noqa: E731
  786. _eval_is_infinite = lambda s: _torf(i.is_infinite for i in s.args) # noqa: E731
  787. _eval_is_integer = lambda s: _torf(i.is_integer for i in s.args) # noqa: E731
  788. _eval_is_irrational = lambda s: _torf(i.is_irrational for i in s.args) # noqa: E731
  789. _eval_is_negative = lambda s: _torf(i.is_negative for i in s.args) # noqa: E731
  790. _eval_is_noninteger = lambda s: _torf(i.is_noninteger for i in s.args) # noqa: E731
  791. _eval_is_nonnegative = lambda s: _torf( # noqa: E731
  792. i.is_nonnegative
  793. for i in s.args # noqa: E731
  794. ) # noqa: E731
  795. _eval_is_nonpositive = lambda s: _torf( # noqa: E731
  796. i.is_nonpositive
  797. for i in s.args # noqa: E731
  798. ) # noqa: E731
  799. _eval_is_nonzero = lambda s: _torf(i.is_nonzero for i in s.args) # noqa: E731
  800. _eval_is_odd = lambda s: _torf(i.is_odd for i in s.args) # noqa: E731
  801. _eval_is_polar = lambda s: _torf(i.is_polar for i in s.args) # noqa: E731
  802. _eval_is_positive = lambda s: _torf(i.is_positive for i in s.args) # noqa: E731
  803. _eval_is_prime = lambda s: _torf(i.is_prime for i in s.args) # noqa: E731
  804. _eval_is_rational = lambda s: _torf(i.is_rational for i in s.args) # noqa: E731
  805. _eval_is_real = lambda s: _torf(i.is_real for i in s.args) # noqa: E731
  806. _eval_is_extended_real = lambda s: _torf( # noqa: E731
  807. i.is_extended_real
  808. for i in s.args # noqa: E731
  809. ) # noqa: E731
  810. _eval_is_transcendental = lambda s: _torf( # noqa: E731
  811. i.is_transcendental
  812. for i in s.args # noqa: E731
  813. ) # noqa: E731
  814. _eval_is_zero = lambda s: _torf(i.is_zero for i in s.args) # noqa: E731
  815. class Max(MinMaxBase, Application): # type: ignore[misc]
  816. r"""
  817. Return, if possible, the maximum value of the list.
  818. """
  819. zero = S.Infinity
  820. identity = S.NegativeInfinity
  821. def _eval_is_positive(self): # type:ignore[override]
  822. return fuzzy_or(a.is_positive for a in self.args) # type: ignore[attr-defined]
  823. def _eval_is_nonnegative(self): # type:ignore[override]
  824. return fuzzy_or(a.is_nonnegative for a in self.args) # type: ignore[attr-defined]
  825. def _eval_is_negative(self): # type:ignore[override]
  826. return fuzzy_and(a.is_negative for a in self.args)
  827. class Min(MinMaxBase, Application): # type: ignore[misc]
  828. """
  829. Return, if possible, the minimum value of the list.
  830. """
  831. zero = S.NegativeInfinity
  832. identity = S.Infinity
  833. def _eval_is_positive(self): # type:ignore[override]
  834. return fuzzy_and(a.is_positive for a in self.args) # type: ignore[attr-defined]
  835. def _eval_is_nonnegative(self): # type:ignore[override]
  836. return fuzzy_and(a.is_nonnegative for a in self.args) # type: ignore[attr-defined]
  837. def _eval_is_negative(self): # type:ignore[override]
  838. return fuzzy_or(a.is_negative for a in self.args)
  839. def safe_pow(base, exp):
  840. sign = 1
  841. if base < 0:
  842. base = -base
  843. sign = 1 if exp % 2 == 0 else -1
  844. return sign * _safe_pow(base, exp)
  845. # Prevent people from overflowing pow
  846. def _safe_pow(base, exponent):
  847. if exponent < 0:
  848. raise ValueError("Exponent must be non-negative.")
  849. if exponent == 0:
  850. return 1
  851. half_exp = safe_pow(base, exponent // 2)
  852. if half_exp is int_oo:
  853. return int_oo
  854. # TODO: microoptimization is to avoid overflowing into arbitrary precision
  855. # and detect overflow prior to doing operations
  856. result = half_exp * half_exp
  857. if result > sys.maxsize:
  858. return int_oo
  859. if exponent % 2 == 1:
  860. result *= base
  861. if result > sys.maxsize:
  862. return int_oo
  863. return result
  864. class PowByNatural(sympy.Function):
  865. is_integer = True
  866. precedence: int = 50 # precedence of mul
  867. @classmethod
  868. def eval(cls, base, exp):
  869. if isinstance(base, sympy.Integer) and isinstance(exp, sympy.Integer):
  870. r = safe_pow(base, exp)
  871. if r in (-int_oo, int_oo):
  872. return r
  873. return sympy.Integer(r)
  874. if isinstance(exp, sympy.Integer):
  875. # Rely on regular sympy Pow for this (note that iterated
  876. # multiplication turns into a Pow anyway, you can't escape!!)
  877. return sympy.Pow(base, exp)
  878. if exp in (int_oo, sympy.oo):
  879. if base.is_nonnegative:
  880. return int_oo
  881. elif base.is_negative:
  882. return sympy.zoo # this is apparently what (-2)**sympy.oo does
  883. # NB: do NOT translate into sympy.Pow, we will lose knowledge that exp
  884. # is a natural number if we do
  885. # base is assumed to be nonnegative, thereby prevent complex numbers from
  886. # occurring
  887. class FloatPow(sympy.Function):
  888. is_real = True
  889. precedence: int = 60 # precedence of pow
  890. @classmethod
  891. def eval(cls, base, exp):
  892. # NB: These test sympy.Number, not sympy.Float, because:
  893. # - Sometimes we may have sympy.oo or int_oo, and that's not a Float
  894. # (but coerces to math.Inf)
  895. # - Sometimes Float(0.0) will unpredictably decay to Integer(0),
  896. # but we should still accept it in floatey contexts
  897. if isinstance(base, sympy.Number) and isinstance(exp, sympy.Number):
  898. return sympy.Float(float(base) ** float(exp))
  899. # NB: do not do any nontrivial reasoning
  900. # Overloaded to be compatible with regular Python.
  901. # https://github.com/pytorch/pytorch/issues/90900
  902. #
  903. # In particular, sympy division is willing to simplify x/x == 1
  904. # where 1 is an integer, but this must be a float if x was float.
  905. class FloatTrueDiv(sympy.Function):
  906. is_real = True
  907. precedence: int = 35 # lower precedence than add
  908. @classmethod
  909. def eval(cls, base, divisor):
  910. # assert base.is_integer is not True, base
  911. # assert divisor.is_integer is not True, divisor
  912. if divisor.is_zero:
  913. raise ZeroDivisionError("division by zero")
  914. if isinstance(base, sympy.Number) and isinstance(divisor, sympy.Number):
  915. return sympy.Float(float(base) / float(divisor))
  916. # Overloaded to be compatible with regular Python. We distinguish this from
  917. # FloatTrueDiv, because the code generation has to be different for this case:
  918. # Python has a fancy algorithm for integer true division that isn't just
  919. # "promote both arguments to float and use float division", so you need to
  920. # codegen it differently. While technically you can work it out from the
  921. # types of the input, this is often inconvenient to do in Inductor codegen,
  922. # so just have a different operator
  923. # NB: Right now, Inductor codegen doesn't implement this correctly lol
  924. class IntTrueDiv(sympy.Function):
  925. is_real = True
  926. precedence: int = 35 # lower precedence than add
  927. @classmethod
  928. def eval(cls, base, divisor):
  929. if divisor.is_zero:
  930. raise ZeroDivisionError("division by zero")
  931. if (
  932. isinstance(base, sympy.Number)
  933. and isinstance(divisor, sympy.Number)
  934. and (
  935. base in (int_oo, -int_oo, sympy.oo, -sympy.oo)
  936. or divisor in (int_oo, -int_oo, sympy.oo, -sympy.oo)
  937. )
  938. ):
  939. # Don't have to worry about precision here, you're getting zero or
  940. # inf from the division
  941. return sympy.Float(float(base) / float(divisor))
  942. if isinstance(base, sympy.Integer) and isinstance(divisor, sympy.Integer):
  943. return sympy.Float(int(base) / int(divisor))
  944. def _ccode(self, printer):
  945. base = printer.parenthesize(self.args[0], PRECEDENCE["Atom"] - 0.5)
  946. divisor = printer.parenthesize(self.args[1], PRECEDENCE["Atom"] - 0.5)
  947. return f"((int){base}/(int){divisor})"
  948. # TODO: As an indicator, this != 0 implies == 1 (and vice versa).
  949. # Because we do not have the ability to guard on the stride permutation
  950. # at the moment, it is hard to make further inferences when this is true,
  951. # as although we know the tensor is contiguous in *some* layout, we don't
  952. # know which one (however, you could, for example, make the inference that
  953. # reshaping this to a 1D tensor can be guard-free.)
  954. class IsNonOverlappingAndDenseIndicator(sympy.Function):
  955. is_integer = True
  956. @classmethod
  957. def eval(cls, *args):
  958. assert len(args) % 2 == 0
  959. dim = len(args) // 2
  960. sizes = args[0:dim]
  961. strides = args[dim:]
  962. # sym_node imported in torch.__init__. Local import to avoid an import cycle
  963. from torch.fx.experimental.symbolic_shapes import (
  964. eval_is_non_overlapping_and_dense,
  965. )
  966. if all(isinstance(a, sympy.Integer) for a in args):
  967. return eval_is_non_overlapping_and_dense(
  968. [int(a) for a in sizes], [int(a) for a in strides]
  969. )
  970. if dim == 1:
  971. # Manually implement the rank one short circuit
  972. if strides[0].is_Number and strides[0] == 1:
  973. return 1
  974. if sizes[0].is_Number and sizes[0] < 2:
  975. return 1
  976. # return 0 case covered by case above
  977. # TODO: Inability to access size-obliviousness sucks: if we have a
  978. # size oblivious test on a size-like unbacked SymInt, we could
  979. # confidently return zero when we have a size-like u0 stride
  980. # and a size-like u1 size. Maybe a fancy ValueRanges analysis for
  981. # this function could help figure this out.
  982. if all(isinstance(a, sympy.Integer) for a in strides):
  983. assert dim != 0
  984. # When all strides are integral, we can sort, and the size for the
  985. # largest stride doesn't matter and can be arbitrarily symbolic
  986. s_sizes, s_strides = zip(
  987. *sorted(zip(sizes, strides, strict=False), key=operator.itemgetter(1)),
  988. strict=False,
  989. )
  990. # Put something arbitrary in the max size spot, it'll be ignored
  991. if all(isinstance(a, sympy.Integer) for a in s_sizes[:-1]):
  992. s_sizes = s_sizes[:-1] + (42,)
  993. # We can reuse the regular eval, because it is invariant to
  994. # permutation of dimensions
  995. return eval_is_non_overlapping_and_dense(
  996. [int(a) for a in s_sizes], [int(a) for a in s_strides]
  997. )
  998. return None
  999. # NB: this is inconsistent with math.trunc in Python
  1000. class TruncToFloat(sympy.Function):
  1001. is_real = True
  1002. @classmethod
  1003. def eval(cls, number):
  1004. # assert number.is_integer is not True, number
  1005. if isinstance(number, sympy.Number):
  1006. # NB: It is safe to use truncation to integer, which is what
  1007. # math.trunc does, as Python integers are arbitrary precision and
  1008. # so we are guaranteed not to lose precision when we do this
  1009. return sympy.Float(math.trunc(float(number)))
  1010. class TruncToInt(sympy.Function):
  1011. is_integer = True
  1012. @classmethod
  1013. def eval(cls, number):
  1014. # assert number.is_integer is not True, number
  1015. if number in (sympy.oo, int_oo):
  1016. return int_oo
  1017. if number in (-sympy.oo, -int_oo):
  1018. return -int_oo
  1019. if isinstance(number, sympy.Number):
  1020. return sympy.Integer(math.trunc(float(number)))
  1021. # This is float -> int
  1022. class RoundToInt(sympy.Function):
  1023. is_integer = True
  1024. @classmethod
  1025. def eval(cls, number):
  1026. # assert number.is_integer is not True, number
  1027. if number is sympy.oo:
  1028. return int_oo
  1029. if number is -sympy.oo:
  1030. return -int_oo
  1031. if isinstance(number, sympy.Number):
  1032. return sympy.Integer(round(float(number), 0))
  1033. # To get float -> int, Python style round semantics.
  1034. #
  1035. # x = PyFloat_AsDouble(self);
  1036. # if (o_ndigits == Py_None) {
  1037. # /* single-argument round or with None ndigits:
  1038. # * round to nearest integer */
  1039. # rounded = round(x);
  1040. # if (fabs(x-rounded) == 0.5)
  1041. # /* halfway case: round to even */
  1042. # rounded = 2.0*round(x/2.0);
  1043. # return PyLong_FromDouble(rounded);
  1044. # }
  1045. # NB: Like Round, this only ever returns floats. ndigits cannot be None
  1046. class RoundDecimal(sympy.Function):
  1047. is_real = True
  1048. @classmethod
  1049. def eval(cls, number, ndigits):
  1050. # assert number.is_integer is not True, number
  1051. if isinstance(number, sympy.Number) and isinstance(ndigits, sympy.Integer):
  1052. return sympy.Float(round(float(number), int(ndigits)))
  1053. class ToFloat(sympy.Function):
  1054. is_real = True
  1055. @classmethod
  1056. def eval(cls, number):
  1057. if number in [sympy.oo, -sympy.oo]:
  1058. return number
  1059. if isinstance(number, sympy.Integer):
  1060. return sympy.Float(int(number))
  1061. if number is int_oo:
  1062. return sympy.oo
  1063. if number is -int_oo:
  1064. return -sympy.oo
  1065. class Identity(sympy.Function):
  1066. """
  1067. Prevents expansion and other optimizations
  1068. """
  1069. precedence = 10
  1070. def __repr__(self): # type: ignore[override]
  1071. return f"Identity({self.args[0]})"
  1072. def _eval_is_real(self):
  1073. return self.args[0].is_real
  1074. def _eval_is_integer(self):
  1075. return self.args[0].is_integer # type: ignore[attr-defined]
  1076. def _eval_expand_identity(self, **hints):
  1077. # Removes the identity op.
  1078. return self.args[0]
  1079. def __int__(self) -> int:
  1080. return int(self.args[0])
  1081. def __float__(self) -> float:
  1082. return float(self.args[0])
  1083. def make_opaque_unary_fn(name):
  1084. class OpaqueUnaryFn(sympy.Function):
  1085. """
  1086. Unlike the builtin sympy functions on real numbers like sympy.sqrt,
  1087. these equivalents do not do any nontrivial reasoning besides
  1088. constant propagation. This helps avoid performing transformations
  1089. that are valid for real numbers but are invalid for floating point;
  1090. in particular, while we are willing to make optimizations that change
  1091. numerics for Tensor compute, we are NOT willing to make optimizations
  1092. that change numerics for size compute.
  1093. """
  1094. _torch_handler_name = name
  1095. _torch_unpickler = make_opaque_unary_fn
  1096. @classmethod
  1097. def eval(cls, a):
  1098. if isinstance(a, (sympy.Integer, sympy.Float)):
  1099. # Python converts to float64 before computing, c.f.
  1100. # >>> math.sin(2**53+1)
  1101. # -0.848925964814655
  1102. # >>> math.sin(float(2**53+1))
  1103. # -0.848925964814655
  1104. try:
  1105. return sympy.Float(getattr(math, name)(float(a)))
  1106. # Just use sympy semantics for infinity/overflow, you might get some
  1107. # weird objects but ask silly questions, get silly answers
  1108. except OverflowError:
  1109. return getattr(sympy, name)(a)
  1110. elif a in [sympy.oo, -sympy.oo, sympy.zoo, -sympy.zoo, int_oo, -int_oo]:
  1111. if a is int_oo:
  1112. a = sympy.oo
  1113. if a is -int_oo:
  1114. a = -sympy.oo
  1115. if name == "log2":
  1116. return sympy.log(a, 2)
  1117. return getattr(sympy, name)(a)
  1118. return None
  1119. nm = "OpaqueUnaryFn_" + name
  1120. OpaqueUnaryFn.__name__ = nm
  1121. OpaqueUnaryFn.__qualname__ = nm
  1122. return OpaqueUnaryFn
  1123. # Keep in sync with math_op_names in torch/fx/experimental/sym_node.py
  1124. OpaqueUnaryFn_sqrt = make_opaque_unary_fn("sqrt")
  1125. OpaqueUnaryFn_cos = make_opaque_unary_fn("cos")
  1126. OpaqueUnaryFn_cosh = make_opaque_unary_fn("cosh")
  1127. OpaqueUnaryFn_sin = make_opaque_unary_fn("sin")
  1128. OpaqueUnaryFn_sinh = make_opaque_unary_fn("sinh")
  1129. OpaqueUnaryFn_tan = make_opaque_unary_fn("tan")
  1130. OpaqueUnaryFn_tanh = make_opaque_unary_fn("tanh")
  1131. OpaqueUnaryFn_asin = make_opaque_unary_fn("asin")
  1132. OpaqueUnaryFn_acos = make_opaque_unary_fn("acos")
  1133. OpaqueUnaryFn_atan = make_opaque_unary_fn("atan")
  1134. OpaqueUnaryFn_exp = make_opaque_unary_fn("exp")
  1135. OpaqueUnaryFn_log = make_opaque_unary_fn("log")
  1136. OpaqueUnaryFn_asinh = make_opaque_unary_fn("asinh")
  1137. OpaqueUnaryFn_log2 = make_opaque_unary_fn("log2")
  1138. def make_opaque_bitwise_fn(name, real_op_name):
  1139. if name == "bitwise_and":
  1140. prec = PRECEDENCE["BitwiseAnd"]
  1141. elif name == "bitwise_or":
  1142. prec = PRECEDENCE["BitwiseOr"]
  1143. else:
  1144. raise AssertionError(f"unrecognized {name}")
  1145. class BitwiseFn(sympy.Function):
  1146. _torch_handler_name = name
  1147. precedence: int = prec
  1148. _torch_unpickler = functools.partial(
  1149. make_opaque_bitwise_fn, real_op_name=real_op_name
  1150. )
  1151. @classmethod
  1152. def eval(cls, a, b):
  1153. if a.is_Boolean and b.is_Boolean:
  1154. return getattr(operator, real_op_name)(a, b)
  1155. if a.is_Boolean:
  1156. a = sympy.Integer(1 if a else 0)
  1157. if b.is_Boolean:
  1158. b = sympy.Integer(1 if b else 0)
  1159. if isinstance(a, (sympy.Integer, int)) and isinstance(
  1160. b, (sympy.Integer, int)
  1161. ):
  1162. return sympy.Integer(getattr(operator, real_op_name)(int(a), int(b)))
  1163. return None
  1164. nm = "BitwiseFn_" + name
  1165. BitwiseFn.__name__ = nm
  1166. BitwiseFn.__qualname__ = nm
  1167. return BitwiseFn
  1168. BitwiseFn_bitwise_and = make_opaque_bitwise_fn("bitwise_and", "and_")
  1169. BitwiseFn_bitwise_or = make_opaque_bitwise_fn("bitwise_or", "or_")