functions.py 54 KB

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