model.py 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903
  1. from __future__ import annotations
  2. import dataclasses
  3. import itertools
  4. import re
  5. from dataclasses import dataclass
  6. from enum import auto, Enum
  7. from typing import TYPE_CHECKING
  8. from typing_extensions import assert_never
  9. from torchgen.utils import NamespaceHelper, OrderedSet
  10. if TYPE_CHECKING:
  11. from collections.abc import Callable, Iterator, Sequence
  12. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
  13. #
  14. # DATA MODEL
  15. #
  16. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
  17. #
  18. # Some general principles for our data model.
  19. #
  20. # - Stop using C++ data types as the internal data representation
  21. # format. Instead, the internal data structures are centered
  22. # around JIT schema representation. This avoid a big problem
  23. # with the old codegen where we read in all the types from
  24. # native_functions.yaml and then immediately had to retranslate
  25. # them into C++ types.
  26. #
  27. # - More semantic data representation. Instead of representing
  28. # everything as dicts and strings, we define dataclasses for
  29. # every interesting entity the code generation has to deal with.
  30. # These dataclasses have strong semantic invariants: for example,
  31. # we generally require them to roundtrip losslessly into the
  32. # form they were parsed from. These structures are immutable
  33. # and you're expected to populate information once during
  34. # construction.
  35. # Represent a source location; used for better error reporting
  36. @dataclass(frozen=True)
  37. class Location:
  38. file: str
  39. line: int
  40. def __str__(self) -> str:
  41. return f"{self.file}:{self.line}"
  42. # Valid values of the 'variants' field in native_functions.yaml
  43. class Variant(Enum):
  44. function = auto()
  45. method = auto()
  46. # Default kernel namespace
  47. DEFAULT_KERNEL_NAMESPACE = "at::native"
  48. # NOTE: Keep the list in sync with `DispatchKey` in c10/core/DispatchKey.h
  49. BACKEND_COMPONENTS = [
  50. "CPU",
  51. "CUDA",
  52. "HIP",
  53. "XLA",
  54. "MTIA",
  55. "MPS",
  56. "IPU",
  57. "XPU",
  58. "HPU",
  59. "VE",
  60. "Lazy",
  61. "Meta",
  62. "PrivateUse1",
  63. "PrivateUse2",
  64. "PrivateUse3",
  65. ]
  66. FUNCTIONALITY_KEYS = [
  67. "",
  68. "Quantized",
  69. "Sparse",
  70. "SparseCsr",
  71. "NestedTensor",
  72. "Autograd",
  73. ]
  74. # This list guards dispatches that can be used in derivatives.yaml
  75. # For now we omit AutogradFunctionality and AutogradOther
  76. AUTOGRAD_KEYS = ["AutogradNestedTensor"] + [
  77. "Autograd" + component for component in BACKEND_COMPONENTS
  78. ]
  79. FRAGMENT_NAMESPACES = {"quantized", "quantized_decomposed"}
  80. # This doesn't have to be in sync with the header, it only needs to contain
  81. # entries that we actually use in the codegen or want pyi entries for
  82. class DispatchKey(Enum):
  83. Undefined = 0
  84. CatchAll = Undefined
  85. FPGA = auto()
  86. MAIA = auto()
  87. Vulkan = auto()
  88. Metal = auto()
  89. MKLDNN = auto()
  90. OpenGL = auto()
  91. OpenCL = auto()
  92. IDEEP = auto()
  93. CustomRNGKeyId = auto()
  94. MkldnnCPU = auto()
  95. Sparse = auto()
  96. SparseCsr = auto()
  97. NestedTensor = auto()
  98. Dense = auto()
  99. PythonTLSSnapshot = auto()
  100. PreDispatch = auto()
  101. PythonDispatcher = auto()
  102. Python = auto()
  103. FuncTorchDynamicLayerBackMode = auto()
  104. ZeroTensor = auto()
  105. Conjugate = auto()
  106. Negative = auto()
  107. BackendSelect = auto()
  108. Named = auto()
  109. AutogradOther = auto()
  110. AutogradFunctionality = auto()
  111. AutogradNestedTensor = auto()
  112. Tracer = auto()
  113. Autocast = auto()
  114. AutocastCPU = auto()
  115. AutocastCUDA = auto()
  116. Batched = auto()
  117. VmapMode = auto()
  118. FuncTorchGradWrapper = auto()
  119. FuncTorchBatched = auto()
  120. BatchedNestedTensor = auto()
  121. FuncTorchVmapMode = auto()
  122. FuncTorchDynamicLayerFrontMode = auto()
  123. Functionalize = auto()
  124. TESTING_ONLY_GenericWrapper = auto()
  125. TESTING_ONLY_GenericMode = auto()
  126. ADInplaceOrView = auto()
  127. Autograd = auto()
  128. CompositeImplicitAutograd = auto()
  129. CompositeImplicitAutogradNestedTensor = auto()
  130. CompositeExplicitAutograd = auto()
  131. CompositeExplicitAutogradNonFunctional = auto()
  132. FuncTorchBatchedDecomposition = auto()
  133. # BEGIN autogenerated
  134. CPU = auto()
  135. CUDA = auto()
  136. HIP = auto()
  137. XLA = auto()
  138. MTIA = auto()
  139. MPS = auto()
  140. IPU = auto()
  141. XPU = auto()
  142. HPU = auto()
  143. VE = auto()
  144. Lazy = auto()
  145. Meta = auto()
  146. PrivateUse1 = auto()
  147. PrivateUse2 = auto()
  148. PrivateUse3 = auto()
  149. QuantizedCPU = auto()
  150. QuantizedCUDA = auto()
  151. QuantizedHIP = auto()
  152. QuantizedXLA = auto()
  153. QuantizedMTIA = auto()
  154. QuantizedMPS = auto()
  155. QuantizedIPU = auto()
  156. QuantizedXPU = auto()
  157. QuantizedHPU = auto()
  158. QuantizedVE = auto()
  159. QuantizedLazy = auto()
  160. QuantizedMeta = auto()
  161. QuantizedPrivateUse1 = auto()
  162. QuantizedPrivateUse2 = auto()
  163. QuantizedPrivateUse3 = auto()
  164. SparseCPU = auto()
  165. SparseCUDA = auto()
  166. SparseHIP = auto()
  167. SparseXLA = auto()
  168. SparseMTIA = auto()
  169. SparseMPS = auto()
  170. SparseIPU = auto()
  171. SparseXPU = auto()
  172. SparseHPU = auto()
  173. SparseVE = auto()
  174. SparseLazy = auto()
  175. SparseMeta = auto()
  176. SparsePrivateUse1 = auto()
  177. SparsePrivateUse2 = auto()
  178. SparsePrivateUse3 = auto()
  179. SparseCsrCPU = auto()
  180. SparseCsrCUDA = auto()
  181. SparseCsrHIP = auto()
  182. SparseCsrXLA = auto()
  183. SparseCsrMTIA = auto()
  184. SparseCsrMPS = auto()
  185. SparseCsrIPU = auto()
  186. SparseCsrXPU = auto()
  187. SparseCsrHPU = auto()
  188. SparseCsrVE = auto()
  189. SparseCsrLazy = auto()
  190. SparseCsrMeta = auto()
  191. SparseCsrPrivateUse1 = auto()
  192. SparseCsrPrivateUse2 = auto()
  193. SparseCsrPrivateUse3 = auto()
  194. NestedTensorCPU = auto()
  195. NestedTensorCUDA = auto()
  196. NestedTensorHIP = auto()
  197. NestedTensorXLA = auto()
  198. NestedTensorMTIA = auto()
  199. NestedTensorMPS = auto()
  200. NestedTensorIPU = auto()
  201. NestedTensorXPU = auto()
  202. NestedTensorHPU = auto()
  203. NestedTensorVE = auto()
  204. NestedTensorLazy = auto()
  205. NestedTensorMeta = auto()
  206. NestedTensorPrivateUse1 = auto()
  207. NestedTensorPrivateUse2 = auto()
  208. NestedTensorPrivateUse3 = auto()
  209. AutogradCPU = auto()
  210. AutogradCUDA = auto()
  211. AutogradHIP = auto()
  212. AutogradXLA = auto()
  213. AutogradMTIA = auto()
  214. AutogradMPS = auto()
  215. AutogradIPU = auto()
  216. AutogradXPU = auto()
  217. AutogradHPU = auto()
  218. AutogradVE = auto()
  219. AutogradLazy = auto()
  220. AutogradMeta = auto()
  221. AutogradPrivateUse1 = auto()
  222. AutogradPrivateUse2 = auto()
  223. AutogradPrivateUse3 = auto()
  224. # END autogenerated
  225. def __str__(self) -> str:
  226. return self.name
  227. def lower(self) -> str:
  228. return str(self).lower()
  229. @staticmethod
  230. def parse(value: str) -> DispatchKey:
  231. for k, v in DispatchKey.__members__.items():
  232. if k == value:
  233. return v
  234. raise AssertionError(f"unknown dispatch key {value}")
  235. class _TorchDispatchModeKey(Enum):
  236. FAKE = auto()
  237. PROXY = auto()
  238. FUNCTIONAL = auto()
  239. def codegen_per_backend_entries() -> str:
  240. r: list[str] = []
  241. for fk in FUNCTIONALITY_KEYS:
  242. r.extend(f" {fk}{bc} = auto()" for bc in BACKEND_COMPONENTS)
  243. return "\n".join(r)
  244. for fk in FUNCTIONALITY_KEYS:
  245. for bc in BACKEND_COMPONENTS:
  246. if not hasattr(DispatchKey, fk + bc):
  247. r = codegen_per_backend_entries()
  248. print(r)
  249. raise RuntimeError(
  250. f"Missing {fk}{bc} from DispatchKey enum. Here is the autogenerated list we expect to have:\n\n{r}"
  251. )
  252. STRUCTURED_DISPATCH_KEYS = {
  253. DispatchKey.MPS,
  254. DispatchKey.CUDA,
  255. DispatchKey.CPU,
  256. DispatchKey.XPU,
  257. DispatchKey.MTIA,
  258. }
  259. UFUNC_DISPATCH_KEYS = {DispatchKey.CUDA, DispatchKey.CPU}
  260. # Set of supported dispatch keys
  261. dispatch_keys = [
  262. DispatchKey.CPU,
  263. DispatchKey.SparseCPU,
  264. DispatchKey.SparseCsrCPU,
  265. DispatchKey.MkldnnCPU,
  266. DispatchKey.CUDA,
  267. DispatchKey.MPS,
  268. DispatchKey.XPU,
  269. DispatchKey.SparseXPU,
  270. DispatchKey.SparseCsrXPU,
  271. DispatchKey.SparseCUDA,
  272. DispatchKey.SparseCsrCUDA,
  273. DispatchKey.SparseMPS,
  274. DispatchKey.SparseCsrMPS,
  275. DispatchKey.QuantizedCPU,
  276. DispatchKey.QuantizedCUDA,
  277. DispatchKey.CompositeImplicitAutograd,
  278. DispatchKey.CompositeImplicitAutogradNestedTensor,
  279. DispatchKey.CompositeExplicitAutograd,
  280. DispatchKey.CompositeExplicitAutogradNonFunctional,
  281. DispatchKey.NestedTensorCPU,
  282. DispatchKey.NestedTensorCUDA,
  283. DispatchKey.NestedTensorXPU,
  284. DispatchKey.NestedTensorHPU,
  285. # Meta is a magic key: it is automatically generated for structured
  286. # kernels
  287. DispatchKey.Meta,
  288. DispatchKey.SparseMeta,
  289. DispatchKey.SparseCsrMeta,
  290. DispatchKey.QuantizedMeta,
  291. DispatchKey.NestedTensorMeta,
  292. DispatchKey.ZeroTensor,
  293. DispatchKey.MTIA,
  294. ]
  295. # Dispatch keys that "support all backends". These codegen slightly differently
  296. # then backend specific keys.
  297. def is_generic_dispatch_key(dk: DispatchKey) -> bool:
  298. return dk in {
  299. DispatchKey.CompositeExplicitAutograd,
  300. DispatchKey.CompositeExplicitAutogradNonFunctional,
  301. DispatchKey.CompositeImplicitAutograd,
  302. DispatchKey.CompositeImplicitAutogradNestedTensor,
  303. }
  304. # CUDA specific dispatch keys
  305. def is_cuda_dispatch_key(dk: DispatchKey) -> bool:
  306. return dk in {
  307. DispatchKey.CUDA,
  308. DispatchKey.QuantizedCUDA,
  309. DispatchKey.SparseCUDA,
  310. DispatchKey.SparseCsrCUDA,
  311. DispatchKey.NestedTensorCUDA,
  312. DispatchKey.AutogradCUDA,
  313. }
  314. # XPU specific dispatcy keys
  315. def is_xpu_dispatch_key(dk: DispatchKey) -> bool:
  316. return dk in {
  317. DispatchKey.XPU,
  318. DispatchKey.QuantizedXPU,
  319. DispatchKey.SparseXPU,
  320. DispatchKey.SparseCsrXPU,
  321. DispatchKey.NestedTensorXPU,
  322. DispatchKey.AutogradXPU,
  323. }
  324. # Structured kernel generation is only supported for certain key types;
  325. # otherwise use old-style
  326. def is_structured_dispatch_key(dk: DispatchKey) -> bool:
  327. return dk in STRUCTURED_DISPATCH_KEYS
  328. def is_ufunc_dispatch_key(dk: DispatchKey) -> bool:
  329. # For now, ufunc dispatch keys coincide with structured keys
  330. return dk in UFUNC_DISPATCH_KEYS
  331. dispatch_device_map = {is_cuda_dispatch_key: "cuda", is_xpu_dispatch_key: "xpu"}
  332. # This is oddly named ScalarType and not DType for symmetry with C++
  333. class ScalarType(Enum):
  334. Byte = auto()
  335. Char = auto()
  336. Short = auto()
  337. Int = auto()
  338. Long = auto()
  339. Half = auto()
  340. Float = auto()
  341. Double = auto()
  342. ComplexHalf = auto()
  343. ComplexFloat = auto()
  344. ComplexDouble = auto()
  345. Bool = auto()
  346. BFloat16 = auto()
  347. Float8_e5m2 = auto()
  348. Float8_e5m2fnuz = auto()
  349. Float8_e4m3fn = auto()
  350. Float8_e4m3fnuz = auto()
  351. Float8_e8m0fnu = auto()
  352. def __str__(self) -> str:
  353. return self.name
  354. @staticmethod
  355. def maybe_parse(value: str) -> ScalarType | None:
  356. for k, v in ScalarType.__members__.items():
  357. if k == value:
  358. return v
  359. return None
  360. @staticmethod
  361. def parse(value: str) -> ScalarType:
  362. mb_r = ScalarType.maybe_parse(value)
  363. assert mb_r is not None, f"unknown dtype {value}"
  364. return mb_r
  365. @staticmethod
  366. def parse_set(values: str) -> OrderedSet[ScalarType]:
  367. dtypes: OrderedSet[ScalarType] = OrderedSet()
  368. for value in values.split(", "):
  369. if value in DTYPE_CLASSES:
  370. dtypes.update(DTYPE_CLASSES[value])
  371. else:
  372. dtypes.add(ScalarType.parse(value))
  373. return dtypes
  374. DTYPE_CLASSES: dict[str, OrderedSet[ScalarType]] = {}
  375. # NB: Integral doesn't include boolean
  376. DTYPE_CLASSES["Integral"] = OrderedSet(
  377. [
  378. ScalarType.Byte,
  379. ScalarType.Char,
  380. ScalarType.Int,
  381. ScalarType.Long,
  382. ScalarType.Short,
  383. ]
  384. )
  385. # NB: Floating doesn't include low precision types
  386. DTYPE_CLASSES["Floating"] = OrderedSet([ScalarType.Float, ScalarType.Double])
  387. DTYPE_CLASSES["Complex"] = OrderedSet(
  388. [ScalarType.ComplexFloat, ScalarType.ComplexDouble]
  389. )
  390. DTYPE_CLASSES["All"] = DTYPE_CLASSES["Integral"] | DTYPE_CLASSES["Floating"]
  391. DTYPE_CLASSES["AllAndComplex"] = DTYPE_CLASSES["All"] | DTYPE_CLASSES["Complex"]
  392. DTYPE_CLASSES["FloatingAndComplex"] = (
  393. DTYPE_CLASSES["Floating"] | DTYPE_CLASSES["Complex"]
  394. )
  395. # Represents the valid entries for ufunc_inner_loop in native_functions.yaml.
  396. # NB: if you add a new UfuncKey, you will teach torchgen.dest.ufunc how
  397. # to process it. Most logic will ignore keys they don't understand, so your
  398. # new key will get silently ignored until you hook in logic to deal with it.
  399. class UfuncKey(Enum):
  400. # These are low level keys that represent exactly one particular
  401. # instantiation of the kernel produced by codegen
  402. CUDAFunctor = auto()
  403. CUDAFunctorOnOther = auto()
  404. CUDAFunctorOnSelf = auto()
  405. CPUScalar = auto()
  406. CPUVector = auto()
  407. # These are the ones users will usually specify, and
  408. # implicitly "fill in" the low level keys
  409. ScalarOnly = auto() # CUDA*, CPUScalar
  410. Generic = auto() # CUDA*, CPU*
  411. def __str__(self) -> str:
  412. return self.name
  413. @staticmethod
  414. def parse(value: str) -> UfuncKey:
  415. for k, v in UfuncKey.__members__.items():
  416. if k == value:
  417. return v
  418. raise AssertionError(f"unknown ufunc key {value}")
  419. class DeviceCheckType(Enum):
  420. NoCheck = 0
  421. ExactSame = 1
  422. class ViewSchemaKind(Enum):
  423. aliasing = auto()
  424. aliasing_inplace = auto()
  425. non_aliasing = auto()
  426. # The basic input to the code generation is native_functions.yaml.
  427. # The name "native", BTW, comes from the distinction between native
  428. # functions and legacy TH functions. The legacy TH functions are gone,
  429. # but the "native" descriptor has stuck.
  430. #
  431. # NativeFunction models a single entry in native_functions.yaml. Its
  432. # fields roughly correspond to what you would see in the YAML itself,
  433. # but after canonicalization and parsing has occurred.
  434. #
  435. # You can see some of the overall design patterns for how we setup
  436. # dataclasses in this class, but we will defer a complete discussion
  437. # of this at FunctionSchema.
  438. @dataclass(frozen=True)
  439. class NativeFunction:
  440. # The namespace for this operator. For example, if we have "at::add"
  441. # then the namespace would be "at". This enables ops to be registered
  442. # through the same DSL with a custom namespace. If not specified, the
  443. # default namespace would be "at".
  444. namespace: str
  445. # The function schema of the operator in question. This schema
  446. # has been parsed; see FunctionSchema for more about its structure.
  447. # (This type is quoted as we are forward referencing a type
  448. # defined later in the file. I opted for this ordering of the
  449. # classes for expository clarity.)
  450. func: FunctionSchema
  451. # Whether or not to generate mutable tensor arguments like regular
  452. # ones
  453. use_const_ref_for_mutable_tensors: bool
  454. # Whether or not to omit automatic generation of a DeviceGuard
  455. device_guard: bool
  456. # How to emit automatic generation of device check
  457. device_check: DeviceCheckType
  458. # What python module to put the function in
  459. python_module: str | None
  460. # TODO: figure out what this does
  461. category_override: str | None
  462. # If no variants are specified in native_functions.yaml, this is
  463. # assumed to be {'function'}.
  464. variants: set[Variant]
  465. # Whether or not we should skip generating registrations for
  466. # this kernel. This is a bit of a double-edged sword, as manual
  467. # registrations don't participate in codegen-based selective build!
  468. manual_kernel_registration: bool
  469. # Whether or not to skip generating TensorMethod/Functions bindings
  470. # for this kernel. Technically, this doesn't actually skip generating
  471. # the binding; instead, the binding gets generated to __dispatch_{funcname}
  472. # so you can make use of the normal binding if you need it.
  473. manual_cpp_binding: bool
  474. # The location in the YAML file were this native function entry was
  475. # defined. This is for conveniently reporting error messages!
  476. loc: Location
  477. # A list of operators that are expected to be auto-generated for this NativeFunction.
  478. # Note: This list isn't actually directly used by the codegen to generate anything.
  479. # Instead, the codegen figures out what operators to generate purely based off of
  480. # function schema, and uses the autogen declarations to error check.
  481. # We expect every NativeFunction that gets auto-generated be explicitly called out
  482. # in native_functions.yaml
  483. autogen: list[OperatorName]
  484. # If non-empty, this kernel is subject to ufunc codegen.
  485. # Sorted by ufunc_key
  486. ufunc_inner_loop: dict[UfuncKey, UfuncInnerLoop]
  487. # Whether or not this out functions is a "structured kernel". Structured
  488. # kernels are defined a little differently from normal kernels; in
  489. # particular, their shape checking logic is defined separately from
  490. # the kernel. Only out functions can be structured; other functions
  491. # delegate to the out function using the structured_delegate keyword.
  492. # Every structured kernel must have at least an out and a functional
  493. # variant.
  494. structured: bool
  495. # Whether or not this non-out function is a structured kernel, defined
  496. # in terms of the out kernel referenced by the string here.
  497. structured_delegate: OperatorName | None
  498. # Only valid for structured kernels. Specifies alternative of what
  499. # to inherit from when defining the meta class for the structured
  500. # operator. This will usually be TensorIteratorBase. This also
  501. # changes the semantics of set_output to call the parent class.
  502. structured_inherits: str | None
  503. # Structured kernels can declare elements as "precomputed". These elements
  504. # are returned by the meta function in one struct and passed to the impl
  505. # function in lieu of certain kernel arguments that these precomputed
  506. # elements supersede. Information about the names and types of these
  507. # precomputed elements and how they correspond to kernel arguments is stored
  508. # in this member, if applicable.
  509. precomputed: Precompute | None
  510. # Argument names whose default should be excluded from the C++ interface.
  511. # Intended for resolving overload ambiguities between signatures.
  512. cpp_no_default_args: set[str]
  513. # Note [Abstract ATen methods]
  514. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  515. # An abstract ATen method is one whose dispatch differs between
  516. # types. These are implemented in derived types (with a
  517. # standard (throwing) definition in Type). A concrete ATen
  518. # method is one which has the same dispatch for all types;
  519. # we just implement it in the base Type. This is exposed
  520. # in Declarations.yaml via a field named 'abstract'.
  521. is_abstract: bool
  522. # Whether or not the NativeFunction contains a backend-agnostic kernel
  523. has_composite_implicit_autograd_kernel: bool
  524. has_composite_implicit_autograd_nested_tensor_kernel: bool
  525. has_composite_explicit_autograd_kernel: bool
  526. has_composite_explicit_autograd_non_functional_kernel: bool
  527. # Tags are used to describe semantic information about (groups of) operators,
  528. # That aren't easily inferable directly from the operator's schema.
  529. tags: set[str]
  530. # NB: The benefit of defining a dataclass is that we automatically get
  531. # a constructor defined for all the fields we specify. No need
  532. # to explicitly write it out.
  533. # We parse both the NativeFunction + backend-specific information about it, which it stored in a corresponding BackendIndex.
  534. @staticmethod
  535. def from_yaml(
  536. ei: dict[str, object],
  537. loc: Location,
  538. valid_tags: set[str],
  539. ignore_keys: set[DispatchKey] | None = None,
  540. ) -> tuple[NativeFunction, dict[DispatchKey, dict[OperatorName, BackendMetadata]]]:
  541. """
  542. Parse a NativeFunction from a dictionary as directly parsed
  543. from native_functions.yaml
  544. """
  545. e = ei.copy()
  546. funcs = e.pop("func")
  547. assert isinstance(funcs, str), f"not a str: {funcs}"
  548. # only support one level of namespace. E.g., aten::add
  549. namespace_helper = NamespaceHelper.from_namespaced_entity(
  550. namespaced_entity=funcs, max_level=1
  551. )
  552. namespace = namespace_helper.get_cpp_namespace(default="aten")
  553. func = FunctionSchema.parse(namespace_helper.entity_name)
  554. cpp_no_default_args_list = e.pop("cpp_no_default_args", [])
  555. assert isinstance(cpp_no_default_args_list, list)
  556. cpp_no_default_args = set(cpp_no_default_args_list)
  557. use_const_ref_for_mutable_tensors = e.pop(
  558. "use_const_ref_for_mutable_tensors", False
  559. )
  560. assert isinstance(use_const_ref_for_mutable_tensors, bool)
  561. if use_const_ref_for_mutable_tensors:
  562. assert not func.arguments.out, (
  563. "see https://github.com/pytorch/pytorch/issues/145522"
  564. )
  565. variants_s = e.pop("variants", "function")
  566. assert isinstance(variants_s, str)
  567. variants: set[Variant] = set()
  568. for v in variants_s.split(", "):
  569. if v == "function":
  570. variants.add(Variant.function)
  571. elif v == "method":
  572. variants.add(Variant.method)
  573. else:
  574. raise AssertionError(f"illegal variant {v}")
  575. manual_kernel_registration = e.pop("manual_kernel_registration", False)
  576. assert isinstance(manual_kernel_registration, bool), (
  577. f"not a bool: {manual_kernel_registration}"
  578. )
  579. manual_cpp_binding = e.pop("manual_cpp_binding", False)
  580. assert isinstance(manual_cpp_binding, bool), f"not a bool: {manual_cpp_binding}"
  581. device_guard = e.pop("device_guard", True)
  582. assert isinstance(device_guard, bool), f"not a bool: {device_guard}"
  583. device_check_s = e.pop("device_check", None)
  584. assert device_check_s is None or isinstance(device_check_s, str), (
  585. f"not a str: {device_check_s}"
  586. )
  587. assert (
  588. device_check_s is None or device_check_s in DeviceCheckType.__members__
  589. ), f"illegal device_check: {device_check_s}"
  590. device_check: DeviceCheckType
  591. if device_check_s is None:
  592. device_check = DeviceCheckType.ExactSame
  593. else:
  594. device_check = DeviceCheckType[device_check_s]
  595. structured = e.pop("structured", False)
  596. assert isinstance(structured, bool), f"not a bool: {structured}"
  597. structured_delegate_s = e.pop("structured_delegate", None)
  598. assert structured_delegate_s is None or isinstance(
  599. structured_delegate_s, str
  600. ), f"not a str: {structured_delegate_s}"
  601. assert structured_delegate_s is None or "::" not in structured_delegate_s, (
  602. "namespace is not supported in structured delegate,"
  603. " using the same namespace as the native function"
  604. )
  605. structured_delegate: OperatorName | None = None
  606. if structured_delegate_s is not None:
  607. structured_delegate = OperatorName.parse(structured_delegate_s)
  608. structured_inherits = e.pop("structured_inherits", None)
  609. assert structured_inherits is None or isinstance(structured_inherits, str), (
  610. f"not a str: {structured_inherits}"
  611. )
  612. assert structured_inherits is None or "::" not in structured_inherits, (
  613. "namespace is not supported in structured inherits,"
  614. " using the same namespace as the native function"
  615. )
  616. python_module = e.pop("python_module", None)
  617. assert python_module is None or isinstance(python_module, str), (
  618. f"not a str: {python_module}"
  619. )
  620. assert python_module is None or Variant.method not in variants, (
  621. "functions in modules cannot be methods"
  622. )
  623. category_override = e.pop("category_override", None)
  624. assert category_override is None or isinstance(category_override, str), (
  625. f"not a str: {category_override}"
  626. )
  627. precomputed_dict = e.pop("precomputed", None)
  628. assert precomputed_dict is None or structured is True
  629. precomputed = Precompute.parse(precomputed_dict) if precomputed_dict else None
  630. tags_inp = e.pop("tags", [])
  631. if isinstance(tags_inp, str):
  632. tags_inp = [tags_inp]
  633. assert isinstance(tags_inp, list)
  634. # All aten ops generated by torchgen receive the pt2_compliant tag.
  635. if namespace == "aten" and "pt2_compliant_tag" in valid_tags:
  636. tags_inp.append("pt2_compliant_tag")
  637. tags: set[str] = set()
  638. for t in tags_inp:
  639. assert len(valid_tags) > 0
  640. # TODO: verify that the tag is valid and has an entry in tags.yaml
  641. if t in valid_tags:
  642. tags.add(t)
  643. else:
  644. raise AssertionError(f"illegal tag {t}")
  645. from torchgen.api import cpp
  646. raw_dispatch = e.pop("dispatch", None)
  647. assert raw_dispatch is None or isinstance(raw_dispatch, dict), e
  648. dispatch: dict[DispatchKey, BackendMetadata] = {}
  649. num_dispatch_keys: int = 0
  650. if raw_dispatch is not None:
  651. assert not manual_kernel_registration, (
  652. "cannot specify both manual_kernel_registration and dispatch; with "
  653. "manual registration, dispatch has no effect!"
  654. )
  655. redundant_composite_implicit_autograd = False
  656. for ks, v in raw_dispatch.items():
  657. if ks == "__line__":
  658. continue # not worth tracking line numbers for dispatch entries
  659. assert isinstance(ks, str), (
  660. f"illegal dispatch key '{ks}' in {raw_dispatch}"
  661. )
  662. assert isinstance(v, str), (
  663. f"illegal dispatch value '{v}' in {raw_dispatch}"
  664. )
  665. for k in ks.split(","):
  666. dispatch_key = DispatchKey.parse(k.strip())
  667. num_dispatch_keys += 1
  668. if ignore_keys and dispatch_key in ignore_keys:
  669. continue
  670. assert dispatch_key in dispatch_keys, (
  671. f"Dispatch key {dispatch_key} of kernel {v} "
  672. "is not a supported dispatch key."
  673. )
  674. # We only allow at most 3 levels of namespace for kernels.
  675. # We will append "native" to a custom kernel namespace.
  676. namespace_helper = NamespaceHelper.from_namespaced_entity(
  677. v, max_level=3
  678. )
  679. kernel_namespace = namespace_helper.get_cpp_namespace(default="at")
  680. # Why is 'structured' included? External backends (e.g.
  681. # XLA) opt into which ops are structured independently
  682. # of which in-tree ops are structured
  683. dispatch[dispatch_key] = BackendMetadata(
  684. kernel=namespace_helper.entity_name,
  685. structured=structured
  686. and is_structured_dispatch_key(dispatch_key),
  687. cpp_namespace=(kernel_namespace + "::native"),
  688. )
  689. if (
  690. dispatch_key is DispatchKey.CompositeImplicitAutograd
  691. and v == cpp.name(func)
  692. ):
  693. redundant_composite_implicit_autograd = True
  694. # We count the number of dispatch keys which have not been ignored to prevent a dispatch table
  695. # in which all backend keys are ignored but necessarily kept, remaining compositeimplicit,
  696. # from being treated as redundant.
  697. assert not (
  698. num_dispatch_keys == 1 and redundant_composite_implicit_autograd
  699. ), (
  700. "unnecessary dispatch table for this function; just delete the dispatch "
  701. "key entirely"
  702. )
  703. # if a function is a structured delegate, deleting the dispatch
  704. # table is NOT semantics preserving
  705. assert (
  706. structured_delegate
  707. or dispatch.keys() != {DispatchKey.CompositeImplicitAutograd}
  708. or dispatch[DispatchKey.CompositeImplicitAutograd].supports_symint()
  709. or num_dispatch_keys != 1
  710. ), (
  711. f"unexpected name for singleton CompositeImplicitAutograd dispatch entry: expected {cpp.name(func)} "
  712. f"but got {dispatch[DispatchKey.CompositeImplicitAutograd]}. Rename your implementation to the expected "
  713. "name, then delete the dispatch table"
  714. )
  715. elif not structured and structured_delegate is None:
  716. name = str(func.name.name)
  717. assert not (
  718. name.startswith("new_")
  719. or name.endswith("_like")
  720. # TODO: maybe it's better to test the return
  721. or (
  722. func.arguments.tensor_options
  723. and not func.arguments.has_tensor_arg()
  724. )
  725. ), (
  726. f"expected {name} to have a CompositeExplicitAutograd "
  727. "dispatch entry, but there was no dispatch table. Factory functions "
  728. "should not have implicit dispatch as they should not be decomposed "
  729. "for __torch_dispatch__"
  730. )
  731. dispatch[DispatchKey.CompositeImplicitAutograd] = BackendMetadata(
  732. cpp.name(func), structured=False, cpp_namespace=DEFAULT_KERNEL_NAMESPACE
  733. )
  734. composites_in_dispatch = [
  735. d
  736. for d in dispatch
  737. if d == DispatchKey.CompositeExplicitAutograd
  738. or d == DispatchKey.CompositeExplicitAutogradNonFunctional
  739. or d == DispatchKey.CompositeImplicitAutograd
  740. or d == DispatchKey.CompositeImplicitAutogradNestedTensor
  741. ]
  742. assert len(composites_in_dispatch) <= 1 or (
  743. len(composites_in_dispatch) == 2
  744. and (
  745. DispatchKey.CompositeExplicitAutogradNonFunctional
  746. not in composites_in_dispatch
  747. )
  748. and (
  749. DispatchKey.CompositeImplicitAutogradNestedTensor
  750. in composites_in_dispatch
  751. )
  752. ), (
  753. "cannot specify more than one of CompositeExplicitAutograd, CompositeExplicitAutogradNonFunctional, "
  754. "or CompositeImplicitAutograd on a single kernel; each "
  755. "strictly subsumes the other. If you wanted to provide an explicit autograd "
  756. "implementation, specify CompositeExplicitAutograd; otherwise specify CompositeImplicitAutograd only"
  757. )
  758. autogen_str = e.pop("autogen", "")
  759. assert isinstance(autogen_str, str)
  760. autogen = (
  761. []
  762. if autogen_str == ""
  763. else [OperatorName.parse(x) for x in autogen_str.split(", ")]
  764. )
  765. raw_ufunc_inner_loop = e.pop("ufunc_inner_loop", {})
  766. ufunc_inner_loop = {}
  767. if isinstance(raw_ufunc_inner_loop, str):
  768. ufunc_inner_loop[UfuncKey.Generic] = UfuncInnerLoop.parse(
  769. raw_ufunc_inner_loop, UfuncKey.Generic
  770. )
  771. elif isinstance(raw_ufunc_inner_loop, dict):
  772. for k, vo in raw_ufunc_inner_loop.items():
  773. if k == "__line__":
  774. continue
  775. assert isinstance(k, str), f"ufunc_inner_loop key is not a str: {k}"
  776. assert isinstance(vo, str), f"ufunc_inner_loop value is not a str: {v}"
  777. ufunc_key = UfuncKey.parse(k)
  778. ufunc_inner_loop[ufunc_key] = UfuncInnerLoop.parse(vo, ufunc_key)
  779. else:
  780. raise AssertionError(
  781. f"ufunc_inner_loop not str or dict: {raw_ufunc_inner_loop}"
  782. )
  783. # Program the BackendIndex for the implicit dispatch entry from ufunc
  784. if ufunc_inner_loop:
  785. assert structured, "ufunc must be structured"
  786. # Delay import ufunc here to avoid circular import issue
  787. # See: https://github.com/pytorch/pytorch/issues/81294
  788. import torchgen.api.ufunc as ufunc
  789. for dispatch_key in UFUNC_DISPATCH_KEYS:
  790. assert dispatch_key not in dispatch, (
  791. f"ufunc should not have explicit dispatch entry for {dispatch_key}"
  792. )
  793. dispatch[dispatch_key] = BackendMetadata(
  794. kernel=ufunc.schema_kernel_name(func, dispatch_key),
  795. structured=True,
  796. cpp_namespace=DEFAULT_KERNEL_NAMESPACE,
  797. )
  798. if structured_delegate:
  799. # Structured functions MUST have a dispatch table
  800. is_abstract = True
  801. else:
  802. is_abstract = (
  803. dispatch.keys() != {DispatchKey.CompositeImplicitAutograd}
  804. and dispatch.keys()
  805. != {DispatchKey.CompositeImplicitAutogradNestedTensor}
  806. and dispatch.keys()
  807. != {
  808. DispatchKey.CompositeImplicitAutograd,
  809. DispatchKey.CompositeImplicitAutogradNestedTensor,
  810. }
  811. )
  812. has_composite_implicit_autograd_kernel = (
  813. DispatchKey.CompositeImplicitAutograd in dispatch
  814. )
  815. has_composite_implicit_autograd_nested_tensor_kernel = (
  816. DispatchKey.CompositeImplicitAutogradNestedTensor in dispatch
  817. )
  818. has_composite_explicit_autograd_kernel = (
  819. DispatchKey.CompositeExplicitAutograd in dispatch
  820. )
  821. has_composite_explicit_autograd_non_functional_kernel = (
  822. DispatchKey.CompositeExplicitAutogradNonFunctional in dispatch
  823. )
  824. # We aren't going to store dispatch metadata inline in NativeFunctions;
  825. # instead it is separately indexed by backend (so other backends can
  826. # add more dispatch entries after the fact). Reindex the individual
  827. # metadata by OperatorName!
  828. backend_metadata = {k: {func.name: v} for k, v in dispatch.items()}
  829. # don't care if it exists or not; make it easier to use this function
  830. # with other yaml parsers that aren't setting __line__ in the dict
  831. e.pop("__line__", None)
  832. assert not e, f"leftover entries: {e}"
  833. # Asserts that we can't do in post_init, because they rely on backend-specific info
  834. if structured_delegate is not None:
  835. for key in STRUCTURED_DISPATCH_KEYS:
  836. assert key not in dispatch, (
  837. f"if structured_delegate, then must not have {key} in dispatch dictionary "
  838. "(it is delegated!)"
  839. )
  840. return (
  841. NativeFunction(
  842. func=func,
  843. use_const_ref_for_mutable_tensors=use_const_ref_for_mutable_tensors,
  844. variants=variants,
  845. structured=structured,
  846. structured_delegate=structured_delegate,
  847. structured_inherits=structured_inherits,
  848. precomputed=precomputed,
  849. autogen=autogen,
  850. ufunc_inner_loop=ufunc_inner_loop,
  851. manual_kernel_registration=manual_kernel_registration,
  852. manual_cpp_binding=manual_cpp_binding,
  853. python_module=python_module,
  854. category_override=category_override,
  855. device_guard=device_guard,
  856. device_check=device_check,
  857. loc=loc,
  858. cpp_no_default_args=cpp_no_default_args,
  859. is_abstract=is_abstract,
  860. has_composite_implicit_autograd_kernel=has_composite_implicit_autograd_kernel,
  861. has_composite_implicit_autograd_nested_tensor_kernel=has_composite_implicit_autograd_nested_tensor_kernel,
  862. has_composite_explicit_autograd_kernel=has_composite_explicit_autograd_kernel,
  863. has_composite_explicit_autograd_non_functional_kernel=has_composite_explicit_autograd_non_functional_kernel,
  864. tags=tags,
  865. namespace=namespace,
  866. ),
  867. backend_metadata,
  868. )
  869. def validate_unstructured(self) -> None:
  870. # TODO: probably better to accumulate these errors and report them all
  871. # at once
  872. assert not self.structured, (
  873. "This function is structured, but there was "
  874. "no valid functional variant of it."
  875. )
  876. assert self.structured_delegate, (
  877. "This function delegates to another structured out function, "
  878. "but no valid function was found (the delegate may not exist, or it has the wrong type)"
  879. )
  880. # __post_init__ functions in dataclasses can be used to do extra
  881. # validation after construction.
  882. #
  883. # Notice that we don't do any type validation here. In fact, we
  884. # rely exclusively on mypy to check if you've done types correctly!
  885. # Validation is for nontrivial invariants that cannot be (conveniently)
  886. # encoded in the type system.
  887. def __post_init__(self) -> None:
  888. if self.func.arguments.out:
  889. assert self.variants == {Variant.function}, (
  890. "Native functions with out arguments MUST "
  891. "be declared with only function variant; e.g., variants: function; "
  892. "otherwise you will tickle a Python argument binding bug "
  893. "(which usually manifests itself as the result variable being undefined.)"
  894. )
  895. if self.structured:
  896. assert self.func.kind() == SchemaKind.out, (
  897. "Put structured field on the out= "
  898. "variant of a function; did you mean structured_delegate?"
  899. )
  900. assert self.device_guard, (
  901. "device_guard: False is not respected by structured kernels"
  902. )
  903. if self.structured_delegate:
  904. assert self.func.kind() != SchemaKind.out, (
  905. "structured_delegate field not allowed "
  906. "on out= functions; did you mean structured?"
  907. )
  908. assert self.device_guard, (
  909. "device_guard: False is not respected by structured kernels"
  910. )
  911. # Technically, with the asserts above, this assert is impossible to
  912. # happen
  913. assert not (self.structured and self.structured_delegate), (
  914. "Cannot have both structured and structured_delegate on function"
  915. )
  916. defaulted_arguments = {
  917. a.name for a in self.func.schema_order_arguments() if a.default is not None
  918. }
  919. invalid_args = set.difference(self.cpp_no_default_args, defaulted_arguments)
  920. assert len(invalid_args) == 0, f"Invalid cpp_no_default_args: {invalid_args}"
  921. if self.structured_inherits is not None:
  922. assert self.structured, (
  923. "structured_inherits must also imply structured: True"
  924. )
  925. if str(self.func.name).startswith("_foreach"):
  926. assert self.device_check == DeviceCheckType.NoCheck, (
  927. "foreach kernels fall back to slow path when tensor are on different devices, "
  928. "device_check not allowed to be enabled"
  929. )
  930. # NB: if your function accidentally has rand/dropout/... in its name
  931. # but is not actually random, feel free to amend this to special case
  932. if (
  933. "rand" in str(self.func.name)
  934. or (
  935. (
  936. "dropout" in str(self.func.name)
  937. or any(
  938. "dropout" in arg.name for arg in self.func.arguments.flat_all
  939. )
  940. )
  941. # Backwards of dropout is typically deterministic
  942. and "backward" not in str(self.func.name)
  943. and str(self.func.name.name) not in ["_cudnn_init_dropout_state"]
  944. )
  945. or self.func.arguments.has_generator_arg()
  946. ):
  947. assert "nondeterministic_seeded" in self.tags, str(self.func.name)
  948. @property
  949. def has_composite_kernel(self) -> bool:
  950. return (
  951. self.has_composite_implicit_autograd_kernel
  952. or self.has_composite_explicit_autograd_kernel
  953. or self.has_composite_explicit_autograd_non_functional_kernel
  954. ) or (
  955. self.has_composite_implicit_autograd_kernel
  956. and self.has_composite_implicit_autograd_nested_tensor_kernel
  957. )
  958. @property
  959. def is_view_op(self) -> bool:
  960. rets = self.func.returns
  961. is_non_mutating_view = len(rets) > 0 and any(
  962. r.annotation is not None and not r.annotation.is_write for r in rets
  963. )
  964. # See Note [resize_ in Functionalization] for more dtails
  965. is_inplace_view = (
  966. "inplace_view" in self.tags
  967. and str(self.func.name) != "resize_"
  968. and str(self.func.name) != "resize_as_"
  969. )
  970. is_wildcard_view = any(
  971. inp.annotation is not None and "*" in inp.annotation.alias_set_after
  972. for inp in self.func.schema_order_arguments()
  973. )
  974. return is_non_mutating_view or is_inplace_view or is_wildcard_view
  975. @property
  976. def view_schema_kind(self) -> ViewSchemaKind:
  977. if self.is_view_op and self.func.name.name.inplace:
  978. assert "inplace_view" in self.tags
  979. return ViewSchemaKind.aliasing_inplace
  980. if self.is_view_op:
  981. return ViewSchemaKind.aliasing
  982. else:
  983. return ViewSchemaKind.non_aliasing
  984. @property
  985. def root_name(self) -> str:
  986. return self.func.name.name.base
  987. @property
  988. def part_of_structured_group(self) -> bool:
  989. return self.structured or self.structured_delegate is not None
  990. class SchemaKind(Enum):
  991. functional = auto()
  992. inplace = auto()
  993. out = auto()
  994. mutable = auto()
  995. scratch = auto()
  996. # A structured kernel is guaranteed to have a functional and out variant, and
  997. # optionally an inplace variant.
  998. #
  999. # NB: we create NativeFunctionsGroup *even if* the function is not
  1000. # actually annotated structured. Test the structured boolean to see if it
  1001. # actually is structured or not.
  1002. @dataclass(frozen=True)
  1003. class NativeFunctionsGroup:
  1004. functional: NativeFunction
  1005. inplace: NativeFunction | None
  1006. mutable: NativeFunction | None
  1007. out: NativeFunction
  1008. @property
  1009. def structured(self) -> bool:
  1010. # Whether or not the operator has a meta() function. This information is backend-agnostic.
  1011. return self.out.structured
  1012. def __post_init__(self) -> None:
  1013. test_sig: FunctionSchema = self.functional.func.signature()
  1014. for f in self.functions():
  1015. if test_sig != f.func.signature():
  1016. raise AssertionError(
  1017. "NativeFunctionsGroup constructed from two NativeFunctions "
  1018. f"that don't have matching signatures: {test_sig} != {f.func.signature()}"
  1019. )
  1020. if self.structured != f.part_of_structured_group:
  1021. raise AssertionError(
  1022. "NativeFunctionsGroup constructed from structured and unstructured "
  1023. f"functions: {self.out.func.name} and {f.func.name}"
  1024. )
  1025. assert self.functional.func.kind() == SchemaKind.functional
  1026. assert self.out.func.kind() == SchemaKind.out
  1027. assert self.functional.namespace == self.out.namespace
  1028. if self.inplace is not None:
  1029. assert self.inplace.func.kind() == SchemaKind.inplace
  1030. assert self.inplace.namespace == self.functional.namespace
  1031. if self.mutable is not None:
  1032. assert self.mutable.func.kind() == SchemaKind.mutable
  1033. assert self.mutable.namespace == self.functional.namespace
  1034. # See Note [Overload Ambiguity With Functional Variants]
  1035. assert self.functional.func.name.name.functional_overload
  1036. if self.structured:
  1037. # For now, structured composite kernels are not supported (need some
  1038. # design work to figure out how to make the composite case work)
  1039. assert (
  1040. not self.out.has_composite_implicit_autograd_kernel
  1041. and not self.out.has_composite_implicit_autograd_nested_tensor_kernel
  1042. )
  1043. assert self.functional.structured_delegate == self.out.func.name, (
  1044. f"{self.functional.func.name} delegates to {self.functional.structured_delegate} "
  1045. f"but its actual delegate is {self.out.func.name}"
  1046. )
  1047. if self.inplace is not None:
  1048. assert self.inplace.structured_delegate == self.out.func.name
  1049. generated_fns = sorted(
  1050. [str(f.func.name) for f in self.functions() if "generated" in f.tags]
  1051. )
  1052. generated_fns_str = ", ".join(str(x) for x in generated_fns)
  1053. expected_generated_fns: set[str] = set()
  1054. for f in self.functions():
  1055. expected_generated_fns.update(str(op) for op in f.autogen)
  1056. expected_generated_fns_str = ", ".join(
  1057. str(x) for x in sorted(expected_generated_fns)
  1058. )
  1059. if len(expected_generated_fns) == 0 and len(generated_fns) > 0:
  1060. raise RuntimeError(
  1061. f"The codegen expects to be able to generate '{generated_fns_str}'."
  1062. " In order to generate them however, we expect them to be called out explicitly in the yaml."
  1063. f" Please add an 'autogen: {generated_fns_str}' line to the entry for {str(f.func.name)}"
  1064. )
  1065. if expected_generated_fns_str != generated_fns_str:
  1066. raise RuntimeError(
  1067. f"The codegen expects to be able to generate '{generated_fns_str}'."
  1068. f" To do so, it expects a line: 'autogen: {generated_fns_str}'."
  1069. f" Instead, it found 'autogen: {expected_generated_fns_str}'"
  1070. )
  1071. def signature(self) -> FunctionSchema:
  1072. return self.out.func.signature()
  1073. def functions(self) -> Iterator[NativeFunction]:
  1074. yield self.functional
  1075. yield self.out
  1076. if self.inplace is not None:
  1077. yield self.inplace
  1078. if self.mutable is not None:
  1079. yield self.mutable
  1080. @property
  1081. def root_name(self) -> str:
  1082. return self.functional.root_name
  1083. @staticmethod
  1084. def from_dict(d: dict[SchemaKind, NativeFunction]) -> NativeFunctionsGroup | None:
  1085. assert d
  1086. if len(d) == 1:
  1087. return None
  1088. d = dict(d) # non-destructive updates please
  1089. functional = d.pop(SchemaKind.functional, None)
  1090. inplace = d.pop(SchemaKind.inplace, None)
  1091. mutable = d.pop(SchemaKind.mutable, None)
  1092. out = d.pop(SchemaKind.out, None)
  1093. assert not d
  1094. assert functional is not None
  1095. # There are a few operators which only have functional/inplace variants;
  1096. # these don't count as structured for our purposes here
  1097. if out is None:
  1098. return None
  1099. # assuming all variants have the same namespace
  1100. return NativeFunctionsGroup(
  1101. functional=functional,
  1102. inplace=inplace,
  1103. mutable=mutable,
  1104. out=out,
  1105. )
  1106. @dataclass(frozen=True)
  1107. class BackendMetadata:
  1108. # The name of the backend kernel, for a given operator
  1109. # for in-tree backends. These names come directly from the 'dispatch" field
  1110. # in native_functions.yaml. The dispatch entry is optional; in that
  1111. # case, that is equivalent to having written:
  1112. #
  1113. # dispatch:
  1114. # CompositeImplicitAutograd: $operator_name
  1115. kernel: str
  1116. # Whether or not the operator has a structured kernel implemented, for this particular backend.
  1117. # For in-tree backends, they all have the same value for structured- this is listed
  1118. # in native_functions.yaml.
  1119. # However, external backends like XLA can indendently toggle which ops are structured.
  1120. structured: bool
  1121. # The namespace for kernels, default value: DEFAULT_KERNEL_NAMESPACE
  1122. cpp_namespace: str
  1123. def supports_symint(self) -> bool:
  1124. return "_symint" in self.kernel
  1125. @dataclass(frozen=True)
  1126. class UfuncInnerLoop:
  1127. name: str
  1128. supported_dtypes: OrderedSet[ScalarType]
  1129. # key is stored here because it affects the semantics of name,
  1130. # so its helpful to have them together for further processing
  1131. ufunc_key: UfuncKey
  1132. @staticmethod
  1133. def parse(value: str, ufunc_key: UfuncKey) -> UfuncInnerLoop:
  1134. name, supported_dtypes_str = value.split(" ", 1)
  1135. assert supported_dtypes_str[0] == "("
  1136. assert supported_dtypes_str[-1] == ")"
  1137. supported_dtypes: OrderedSet[ScalarType] = OrderedSet()
  1138. for k in supported_dtypes_str[1:-1].split(", "):
  1139. supported_dtypes |= ScalarType.parse_set(k)
  1140. return UfuncInnerLoop(
  1141. name=name, supported_dtypes=supported_dtypes, ufunc_key=ufunc_key
  1142. )
  1143. # BackendIndex represents a backend.
  1144. # The BackendIndex encodes per-operator information that is potentially different
  1145. # for each backend. The most obvious example is the name of the kernel
  1146. # (the 'dispatch' entry in native_functions.yaml).
  1147. # However, there can be other examples of different backends having different information.
  1148. # External backends can choose to opt their kernels to be structured independently from in-tree backends,
  1149. # which means that this information isn't inherently tied to a NativeFunction- it's different per backend.
  1150. @dataclass(frozen=True)
  1151. class BackendIndex:
  1152. dispatch_key: DispatchKey
  1153. # Mainly important for structured kernels, this determines which variant in the operator group is used to implement the others.
  1154. # All in-tree ops use out kernels, while XLA uses functional kernels.
  1155. use_out_as_primary: bool
  1156. # Whether the backend requires a device guard, and device checks.
  1157. # For in-tree backends, this is currently just CUDA/HIP
  1158. # For out-of-tree backends, this is currently just Intel XPU
  1159. device_guard: bool
  1160. # Whether the backend is in-tree (CPU/CUDA) or out-of-tree (XLA)
  1161. external: bool
  1162. # Other backend-specific information that is on a per-operator basis
  1163. index: dict[OperatorName, BackendMetadata]
  1164. @staticmethod
  1165. def grow_index(
  1166. parent_index: dict[DispatchKey, dict[OperatorName, BackendMetadata]],
  1167. child_index: dict[DispatchKey, dict[OperatorName, BackendMetadata]],
  1168. ) -> None:
  1169. for k, v in child_index.items():
  1170. for op_name, metadata in v.items():
  1171. assert op_name not in parent_index[k], (
  1172. f"duplicate operator {op_name} for dispatch key {k}"
  1173. )
  1174. parent_index[k][op_name] = metadata
  1175. def primary(self, g: NativeFunctionsGroup) -> NativeFunction:
  1176. if self.use_out_as_primary:
  1177. return g.out
  1178. else:
  1179. return g.functional
  1180. def has_kernel(self, g: NativeFunction | NativeFunctionsGroup) -> bool:
  1181. m = self.get_kernel(g)
  1182. return m is not None
  1183. def get_kernel(
  1184. self, g: NativeFunction | NativeFunctionsGroup
  1185. ) -> BackendMetadata | None:
  1186. if isinstance(g, NativeFunction):
  1187. f = g
  1188. elif isinstance(g, NativeFunctionsGroup):
  1189. f = self.primary(g)
  1190. else:
  1191. assert_never(g)
  1192. if f.func.name not in self.index:
  1193. return None
  1194. return self.index[f.func.name]
  1195. def native_function_class_name(self) -> str | None:
  1196. if self.external:
  1197. return f"{str(self.dispatch_key)}NativeFunctions"
  1198. else:
  1199. # TODO: This discrepancy isn't required; we could also generated
  1200. # a class for in-tree kernels. It'll just require carefully
  1201. # updating every kernel definition + callsite of every in-tree aten kernel.
  1202. return None
  1203. # The function schema is undoubtedly the most important data structure
  1204. # in all of the codegen, as it defines the type signature for operators,
  1205. # and most of the code generation we do is type directed (e.g., look at
  1206. # the types, decide what to do. Think about how we code generate
  1207. # C++ function stubs!)
  1208. #
  1209. # We will also see in this class the general structure for how we model
  1210. # data in this code generation. A few notable properties to point out
  1211. # ahead of time:
  1212. #
  1213. # - These dataclasses are a *lossless* representation of the strings
  1214. # they are parsed from. In fact, we assert that given the
  1215. # information stored in the dataclass, we can exactly reconstruct
  1216. # the string we parsed from (and assert this inside the parse
  1217. # definition). There are a few reasons for this:
  1218. #
  1219. # - If you find that it is difficult to reconstruct the string
  1220. # given a dataclass, that is a clue that you are data
  1221. # representation is wrong.
  1222. #
  1223. # - It helps ensure that all relevant information is present
  1224. # in the dataclass, so that downstream users aren't tempted
  1225. # to reparse the original string to get some information
  1226. # that was omitted.
  1227. #
  1228. # - It forces you to represent the data in-memory in the same way
  1229. # it is recorded textually, which makes the dataclasses easier
  1230. # to understand for someone who is familiar with the
  1231. # textual format. (As a tradeoff, it means you have to model
  1232. # the syntax, even when it is inconvenient. But maybe that means
  1233. # the syntax is bad!) If you don't understand the internal
  1234. # representation, go look at the printing code to see how
  1235. # it maps onto the surface syntax!
  1236. #
  1237. # - It makes it easy to test the parsing code, as parsing code
  1238. # that is inconsistent with the string code will fail early
  1239. # and loudly. (As a tradeoff, it makes the parsing code a bit
  1240. # brittle (in particular, with trivial whitespace changes you
  1241. # are likely to trigger an assert error).
  1242. #
  1243. # In general, try to make the __str__ code as simple as possible
  1244. # (even at the cost of more complex parsing logic.) Additionally,
  1245. # try to minimize redundancy in data representation. (Precomputed
  1246. # fields are OK though: they are defined as a simple function on
  1247. # the canonical representation in question.)
  1248. #
  1249. # - These dataclasses are all frozen; once constructed their
  1250. # values never change. This makes it easy to tell where any
  1251. # given data came from: just look to the constructor. As a
  1252. # tradeoff, you can't easily "decorate" a schema with extra
  1253. # information from a post-facto analysis. We impose this
  1254. # restriction to make these structures more understandable.
  1255. #
  1256. @dataclass(frozen=True)
  1257. class FunctionSchema:
  1258. # The name of the operator this function schema describes.
  1259. name: OperatorName
  1260. arguments: Arguments
  1261. # TODO: Need to handle collisions with argument names at some point
  1262. returns: tuple[Return, ...]
  1263. @property
  1264. def is_mutable(self) -> bool:
  1265. def is_write(arg: Argument) -> bool:
  1266. if arg.annotation is None:
  1267. return False
  1268. return arg.annotation.is_write
  1269. # Corresponds to torch._C._FunctionSchema.is_mutable
  1270. # See aten/src/ATen/core/function_schema.h (keep these in sync)
  1271. return any(is_write(a) for a in self.arguments.flat_all)
  1272. def schema_order_arguments(self) -> Iterator[Argument]:
  1273. return itertools.chain(
  1274. self.arguments.flat_positional,
  1275. self.arguments.flat_kwarg_only,
  1276. self.arguments.out,
  1277. )
  1278. decl_re = re.compile(r"(?P<name>[^\(]+)\((?P<args>.*)\) -> (?P<returns>.*)")
  1279. @staticmethod
  1280. def parse(func: str) -> FunctionSchema:
  1281. # We should probably get a proper parser here
  1282. decls = FunctionSchema.decl_re.findall(func)
  1283. assert len(decls) == 1, f"Invalid function schema: {func}"
  1284. ops, args, return_decl = decls[0]
  1285. name = OperatorName.parse(ops)
  1286. arguments = Arguments.parse(args)
  1287. returns = parse_returns(return_decl)
  1288. r = FunctionSchema(name=name, arguments=arguments, returns=returns)
  1289. assert str(r) == func, f"{str(r)} != {func}"
  1290. return r
  1291. def returns_are_aliased(self) -> bool:
  1292. # We assert earlier that schemas can't have a mix of aliased and non-aliased returns
  1293. return any(
  1294. r
  1295. for r in self.returns
  1296. if r.annotation is not None and r.annotation.is_write
  1297. )
  1298. def __post_init__(self) -> None:
  1299. for arg, ret in zip(self.arguments.out, self.returns):
  1300. assert arg.annotation == ret.annotation, (
  1301. "Out arguments must have matching return Tensor; furthermore, "
  1302. "the ith-argument needs to correspond to the ith return"
  1303. )
  1304. # We also enforce that if you have any mutable, positional args, then they are not returned.
  1305. # This makes it easier to group these functions properly with their functional/out= counterparts.
  1306. for a in self.arguments.post_self_positional_mutable:
  1307. assert not any(a.annotation == r.annotation for r in self.returns), (
  1308. f"If you have a schema with mutable positional args, we expect them to not be returned. schema: {str(self)}"
  1309. )
  1310. # Invariant: we expect out arguments to appear as keyword arguments in the schema.
  1311. # This means that all mutable returns should be aliased to a keyword argument
  1312. # (except for "self", which we explicitly don't treat as an out argument because of its use in methods)
  1313. # See Note [is_out_fn]
  1314. out_and_self = list(self.arguments.out) + [
  1315. arg for arg in self.arguments.flat_positional if arg.name == "self"
  1316. ]
  1317. mutable_returns = [
  1318. ret
  1319. for ret in self.returns
  1320. if ret.annotation is not None and ret.annotation.is_write
  1321. ]
  1322. immutable_returns = [
  1323. ret
  1324. for ret in self.returns
  1325. if ret.annotation is None or not ret.annotation.is_write
  1326. ]
  1327. # Some assertions: We don't want any functions with a return type of "-> (Tensor(a!), Tensor)",
  1328. # because:
  1329. # (1) It's more annoying to handle properly
  1330. # (2) It's unnecessary - you can't method-chain on the first (mutated) output because it's part of a tuple.
  1331. # Instead, we expect the (a!) argument to not be returned.
  1332. assert len(mutable_returns) == 0 or len(immutable_returns) == 0, (
  1333. f"NativeFunctions must have either only mutable returns, or only immutable returns. Found: {str(self)}"
  1334. )
  1335. for ret in mutable_returns:
  1336. assert any(ret.annotation == arg.annotation for arg in out_and_self), (
  1337. 'All mutable returns must be aliased either to a keyword argument, or to "self". '
  1338. "Did you forget to mark an out argument as keyword-only?"
  1339. )
  1340. if self.arguments.out:
  1341. # out= ops that return their mutable inputs are only really useful for method chaining.
  1342. # And method chaining is only really useful if the thing you're returning is a plain Tensor.
  1343. # So ideally, we'd enforce that out= ops with a single plain mutable tensor should return the tensor,
  1344. # and all other types of out= op schemas should return void.
  1345. # There are a bunch of existing out= ops that return tuples of tensors though, so we're stuck with allowing that.
  1346. if any(a.type != BaseType(BaseTy.Tensor) for a in self.arguments.out):
  1347. assert len(self.returns) == 0, (
  1348. "out= ops that accept tensor lists as out arguments "
  1349. )
  1350. "are expected to have no return type (since you can't do method chaining on them)"
  1351. else:
  1352. # mutable keyword arguments whose name has _scratch_ prefix are
  1353. # scratch tensors for memory planning and should not be returned
  1354. assert len(
  1355. [
  1356. arg
  1357. for arg in self.arguments.out
  1358. if not arg.name.startswith("_scratch_")
  1359. ]
  1360. ) == len(self.returns), (
  1361. "Must return as many arguments as there are out arguments, or no return at all"
  1362. )
  1363. if self.name.name.inplace:
  1364. self_a = self.arguments.self_arg
  1365. assert (
  1366. self_a
  1367. and self_a.argument.annotation
  1368. and self_a.argument.annotation.is_write
  1369. )
  1370. if self_a.argument.type == BaseType(BaseTy.Tensor):
  1371. # All inplace ops with an ordinary `Tensor self` argument should return self,
  1372. # to allow for method chaining.
  1373. assert (
  1374. len(self.returns) == 1
  1375. and self.returns[0].annotation == self_a.argument.annotation
  1376. )
  1377. else:
  1378. # You can't method chain on non-tensor self arguments though (like a list[Tensor])
  1379. # so in all other cases we expect the return type to be none.
  1380. assert len(self.returns) == 0
  1381. if self.arguments.tensor_options is not None:
  1382. assert self.kind() == SchemaKind.functional, (
  1383. "Found an operator that is not functional or out variant, but has tensor options arguments."
  1384. "This is not allowed- tensor options arguments are only allowed for factory functions."
  1385. f"schema: {str(self)}"
  1386. )
  1387. if self.is_functional_fn():
  1388. assert self.kind() == SchemaKind.functional, (
  1389. "Found an operator that is not functional, but its overload contains the string 'functional'."
  1390. "This is a special keyword in the codegen, please use a different overload name."
  1391. f"schema: {str(self)}"
  1392. )
  1393. def is_functional_fn(self) -> bool:
  1394. return "functional" in self.name.overload_name
  1395. def is_out_fn(self) -> bool:
  1396. # Note [is_out_fn]
  1397. #
  1398. # out functions are the variants which take an explicit out= argument
  1399. # to populate into. We need to know if a schema corresponds to an
  1400. # out function for several reasons:
  1401. #
  1402. # - They codegen differently in C++ API
  1403. # - codegen to at::add_out rather than at::add
  1404. # - out argument is moved to front of C++ argument list
  1405. #
  1406. # out functions are DEFINED to be any function with a keyword-only
  1407. # argument that is mutable. In principle, this could lead to a
  1408. # false positive if you define a function that mutates a
  1409. # kwarg only argument, but this isn't the "true" output of this
  1410. # function. A more robust definition that would work in this
  1411. # case would also look at:
  1412. #
  1413. # - The output types. Out functions take in the arguments
  1414. # they mutate and then return them again; this is sort
  1415. # of "definitionally" what makes something an out function.
  1416. # Historically, we DO check this for consistency.
  1417. # - Correspondence with pure variant. An out function
  1418. # should have a signature equivalent to its pure variant,
  1419. # but just with extra kwargs for the output elements. This
  1420. # is difficult to actually check for and historically
  1421. # we only do this check in tools/
  1422. return bool(self.arguments.out)
  1423. def kind(self) -> SchemaKind:
  1424. """
  1425. What kind of schema is this? A functional schema is one
  1426. that returns a newly allocated output; an inplace schema
  1427. modifies the self argument inplace; an out schema writes
  1428. the result into an explicitly provided out argument.
  1429. """
  1430. is_out = bool(self.arguments.out)
  1431. is_scratch = bool(
  1432. [arg for arg in self.arguments.out if arg.name.startswith("_scratch_")]
  1433. )
  1434. is_inplace = self.name.name.inplace
  1435. is_mutable = any(
  1436. a.annotation is not None and a.annotation.is_write
  1437. for a in self.arguments.post_self_positional
  1438. )
  1439. assert not (is_out and is_inplace)
  1440. # out= and inplace schemas can also have post_self_positional mutable args,
  1441. # but we give precedence to out= and inplace when deciding the schema kind.
  1442. # Tradeoff: we probably don't want to have to teach codegen that looks at inplace ops
  1443. # to also worry about mutable post_self_positional arguments,
  1444. # but it seems like a much bigger lift to classify them has having a new schema kind.
  1445. # The number of ops that fit in this strange category is small enough that
  1446. # we can probably manually write code for them instead of forcing the codegen to handle them.
  1447. if is_inplace:
  1448. return SchemaKind.inplace
  1449. elif is_scratch:
  1450. assert is_out, (
  1451. "invariant: all scratch operators are expected to be out= operators too"
  1452. )
  1453. return SchemaKind.scratch
  1454. elif is_out:
  1455. assert not is_scratch, (
  1456. "We should not categorize a scratch op as an out variant. Check if the order of if statements are expected!"
  1457. ) # noqa: B950
  1458. return SchemaKind.out
  1459. elif is_mutable:
  1460. return SchemaKind.mutable
  1461. else:
  1462. return SchemaKind.functional
  1463. # For every return:
  1464. # - If the return aliases an input, we return the input name
  1465. # - Otherwise, we return None.
  1466. # If return names were enforced to be consistent with aliasing information, then we wouldn't need this.
  1467. def aliased_return_names(self) -> list[str | None]:
  1468. outs: list[str | None] = []
  1469. for r in self.returns:
  1470. aliased_args = [
  1471. a
  1472. for a in self.arguments.flat_all
  1473. if a.annotation is not None and a.annotation == r.annotation
  1474. ]
  1475. if len(aliased_args) == 0:
  1476. outs.append(None)
  1477. elif len(aliased_args) == 1:
  1478. outs.append(aliased_args[0].name)
  1479. else:
  1480. aliased_names = ", ".join(a.name for a in aliased_args)
  1481. raise AssertionError(
  1482. f"Found a return ({r.name})that aliases multiple inputs ({aliased_names})"
  1483. )
  1484. return outs
  1485. def signature(
  1486. self,
  1487. *,
  1488. strip_default: bool = False,
  1489. strip_view_copy_name: bool = False,
  1490. keep_return_names: bool = False,
  1491. ) -> FunctionSchema:
  1492. """
  1493. Certain schemas are 'related', in that they are simply
  1494. inplace/out/functional versions of the same function. This method
  1495. factors these schemas into the "core" functional signature which
  1496. is equal across all versions.
  1497. Here is what normalization happens to the schema to convert
  1498. it to a signature:
  1499. - The overload name is stripped (name is retained, since
  1500. it expresses semantic content about what the function does)
  1501. - Inplace is set False
  1502. - Out arguments are stripped
  1503. - Mutable post_self_positional args are converted to returns
  1504. - Mutability annotations are stripped (this is sound
  1505. because you cannot overload on mutability annotation)
  1506. - Return names are stripped since they are not overloadable and
  1507. some variants have return names but some not
  1508. - TensorOptions are dropped
  1509. because out= variants of factory functions don't include them
  1510. (and we want to be able to pair up factory functions with their out variants)
  1511. Finally, we want to be able to pair up related "view" and their
  1512. corresponding "view_copy" operators. We do this by optionally
  1513. stripping the trailing "_copy" from the base name.
  1514. Example of a mutable op before and after:
  1515. f.func (Mutable operator):
  1516. _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask) # noqa: B950
  1517. f.func (Corresponding functional operator):
  1518. _fused_moving_avg_obs_fq_helper.functional(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor running_min, Tensor running_max, Tensor scale, Tensor zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask, Tensor running_min_out, Tensor running_max_out, Tensor scale_out, Tensor zero_point_out) # noqa: B950
  1519. f.func.signature() output:
  1520. _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor running_min, Tensor running_max, Tensor scale, Tensor zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor) # noqa: B950
  1521. """
  1522. def strip_ret_annotation(r: Return) -> Return:
  1523. return Return(
  1524. name=r.name if keep_return_names else None,
  1525. type=r.type,
  1526. annotation=None,
  1527. )
  1528. base_name = self.name.name.base
  1529. if strip_view_copy_name:
  1530. if base_name.endswith("_copy"):
  1531. base_name = base_name.replace("_copy", "")
  1532. elif base_name.endswith("_scatter"):
  1533. base_name = base_name.replace("scatter", "inverse")
  1534. # find mutable inputs that are not originally returned, and convert them to returns
  1535. returns_from_mutable_inputs = tuple(
  1536. # When we're grouping functions we strip the return names,
  1537. # but when we're generating the actual functional variants then we follow
  1538. # a convention for what to name the returns
  1539. Return(
  1540. name=f"{a.name}_out" if keep_return_names else None,
  1541. type=a.type,
  1542. annotation=None,
  1543. )
  1544. for a in itertools.chain(
  1545. # Order is important here (otherwise e.g. inplace with mutable args
  1546. # and out= with mutable args won't have the same signature)
  1547. (
  1548. [self.arguments.self_arg.argument]
  1549. if self.arguments.self_arg is not None
  1550. else []
  1551. ),
  1552. self.arguments.out,
  1553. self.arguments.post_self_positional,
  1554. )
  1555. if a.annotation is not None
  1556. and a.annotation.is_write
  1557. and not any(a.annotation == r.annotation for r in self.returns)
  1558. )
  1559. original_returns = tuple(map(strip_ret_annotation, self.returns))
  1560. # Ordering is important here. We expect the "mutable input" returns to come last.
  1561. returns = original_returns + returns_from_mutable_inputs
  1562. args_sig = self.arguments.signature(strip_default=strip_default)
  1563. # See Note [bernoulli.p schema]
  1564. if str(self.name) == "bernoulli.p":
  1565. args_sig = Arguments.parse(str(args_sig).replace("float p", "float p=0.5"))
  1566. return FunctionSchema(
  1567. name=OperatorName(
  1568. name=BaseOperatorName(
  1569. base=base_name,
  1570. inplace=False,
  1571. dunder_method=self.name.name.dunder_method,
  1572. ),
  1573. overload_name="", # stripped
  1574. ),
  1575. arguments=args_sig,
  1576. returns=returns,
  1577. )
  1578. def view_signature(self) -> FunctionSchema:
  1579. return self.signature(strip_view_copy_name=True)
  1580. def with_name(self, name: OperatorName) -> FunctionSchema:
  1581. return FunctionSchema(
  1582. name=name,
  1583. arguments=self.arguments,
  1584. returns=self.returns,
  1585. )
  1586. @property
  1587. def modifies_arguments(self) -> bool:
  1588. return self.kind() in [SchemaKind.inplace, SchemaKind.out, SchemaKind.mutable]
  1589. def has_symint(self) -> bool:
  1590. return self.arguments.has_symint_arg()
  1591. def __str__(self) -> str:
  1592. all_arguments_str = str(self.arguments)
  1593. if len(self.returns) == 1:
  1594. returns = str(self.returns[0]) # omit parentheses
  1595. else:
  1596. returns = "(" + ", ".join(map(str, self.returns)) + ")"
  1597. return f"{self.name}({all_arguments_str}) -> {returns}"
  1598. # Here is the rest of the data model, described more briefly.
  1599. # Simplified version for what actually shows up in built-ins.
  1600. # Look at alias_info.h for expanded syntax. If you need the structure,
  1601. # you also need to make this structure recursive so it can be lined
  1602. # up with the type components too. For primitives this isn't really
  1603. # necessary
  1604. @dataclass(frozen=True)
  1605. class Annotation:
  1606. # Typically only has one element. Not actually a set so
  1607. # we can conveniently assume it is canonically ordered
  1608. alias_set: tuple[str, ...]
  1609. is_write: bool
  1610. alias_set_after: tuple[str, ...]
  1611. @staticmethod
  1612. def parse(ann: str) -> Annotation:
  1613. # TODO: implement a proper parser if this gets more ugly
  1614. # Regex Explanation:
  1615. # Example: "a! -> a|b"
  1616. # Group #1: alias before optional '|', required. Matches the first
  1617. # character 'a' in the example
  1618. # Group #2: optional alias set after optional '|', matches empty string
  1619. # in the example
  1620. # Group #3: optional "is write" flag, matches '!' in the example.
  1621. # Group #4: optional section containing arrow, matches " -> a|b" in the
  1622. # example.
  1623. # Group #5: optional alias after set, supports wildcard, matches "a|b"
  1624. # in the example.
  1625. # Group #6: optional sub-section of alias after set, matches "|b" in the
  1626. # example.
  1627. m = re.match(r"^([a-z])(\|[a-z])*(!?)( -> (\*|[a-z](\|[a-z])*))?$", ann)
  1628. assert m is not None, f"unrecognized alias annotation {ann}"
  1629. before_alias = m.group(1) + (m.group(2) if m.group(2) else "")
  1630. alias_set = tuple(before_alias.split("|"))
  1631. is_write = m.group(3) == "!"
  1632. assert not (is_write and len(alias_set) > 1), (
  1633. f"alias set larger than 1 is not mutable, got {ann} instead."
  1634. )
  1635. after_set = tuple(m.group(5).split("|")) if m.group(5) else ()
  1636. assert not (len(before_alias) > 1 and len(after_set) > 1), (
  1637. f"before alias set and after alias set cannot be larger than 1 at the same time, got {ann} instead."
  1638. )
  1639. r = Annotation(
  1640. alias_set=alias_set, is_write=is_write, alias_set_after=after_set
  1641. )
  1642. assert str(r) == ann, f"{r} != {ann}"
  1643. return r
  1644. def __str__(self) -> str:
  1645. alias_set = "|".join(self.alias_set)
  1646. if self.is_write:
  1647. alias_set = f"{alias_set}!"
  1648. alias_set_after = "|".join(self.alias_set_after)
  1649. if alias_set_after:
  1650. alias_set = f"{alias_set} -> {alias_set_after}"
  1651. return alias_set
  1652. # The base class for the type system. This is also loosely modeled
  1653. # off of jit_type.h, but we've simplified the hierarchy to focus
  1654. # in on the aspects of the type system that matter for code generation
  1655. # (for example, there's no SingleElementType subclass anymore).
  1656. # You never actually construct a Type; usually it's going to be one
  1657. # of the subclasses. If Python had ADTs this would be one!
  1658. @dataclass(frozen=True)
  1659. class Type:
  1660. @staticmethod
  1661. def parse(t: str) -> Type:
  1662. r = Type._parse(t)
  1663. assert str(r) == t, f"{r} != {t}"
  1664. return r
  1665. @staticmethod
  1666. def _parse(t: str) -> Type:
  1667. m = re.match(r"^(.+)\?$", t)
  1668. if m is not None:
  1669. return OptionalType(Type.parse(m.group(1)))
  1670. m = re.match(r"^(.+)\[([0-9]+)?\]$", t)
  1671. if m is not None:
  1672. size = int(m.group(2)) if m.group(2) is not None else None
  1673. return ListType(elem=Type.parse(m.group(1)), size=size)
  1674. # '__torch__.torch.classes.' is the prefix for custom class
  1675. m = re.match(r"^__torch__\.torch\.classes\.([a-zA-Z0-9_.]+)$", t)
  1676. if m is not None:
  1677. return CustomClassType(m.group(1))
  1678. try:
  1679. return BaseType(BaseTy[t])
  1680. except KeyError as e:
  1681. raise RuntimeError(f"unrecognized type {t}") from e
  1682. def __str__(self) -> str:
  1683. raise NotImplementedError
  1684. # WARNING: These concepts are not very well-defined. For example,
  1685. # is "int?" nullable? How about "int?[]". They are defined
  1686. # so we can conveniently generate legacy Declarations.yaml but
  1687. # really we should probably just remove these at some point
  1688. def is_base_ty_like(self, base_ty: BaseTy) -> bool:
  1689. raise NotImplementedError
  1690. def is_tensor_like(self) -> bool:
  1691. return self.is_base_ty_like(BaseTy.Tensor)
  1692. def is_generator_like(self) -> bool:
  1693. return self.is_base_ty_like(BaseTy.Generator)
  1694. def is_symint_like(self) -> bool:
  1695. return self.is_base_ty_like(BaseTy.SymInt)
  1696. def is_nullable(self) -> bool:
  1697. raise NotImplementedError
  1698. def is_list_like(self) -> ListType | None:
  1699. raise NotImplementedError
  1700. # Base types are simple, atomic types with no further structure
  1701. class BaseTy(Enum):
  1702. Generator = auto()
  1703. ScalarType = auto()
  1704. Tensor = auto()
  1705. int = auto()
  1706. Dimname = auto()
  1707. DimVector = auto()
  1708. float = auto()
  1709. str = auto()
  1710. bool = auto()
  1711. Layout = auto()
  1712. Device = auto()
  1713. DeviceIndex = auto()
  1714. Scalar = auto()
  1715. MemoryFormat = auto()
  1716. QScheme = auto()
  1717. Storage = auto()
  1718. Stream = auto()
  1719. SymInt = auto()
  1720. SymBool = auto()
  1721. GraphModule = auto()
  1722. @dataclass(frozen=True)
  1723. class BaseType(Type):
  1724. name: BaseTy
  1725. def __str__(self) -> str:
  1726. return f"{self.name.name}"
  1727. def is_base_ty_like(self, base_ty: BaseTy) -> bool:
  1728. return self.name == base_ty
  1729. def is_nullable(self) -> bool:
  1730. return False
  1731. def is_list_like(self) -> ListType | None:
  1732. return None
  1733. def is_symint_like(self) -> bool:
  1734. return self.name == BaseTy.SymInt
  1735. # Optional types may be specified, or may also be validly given None
  1736. @dataclass(frozen=True)
  1737. class OptionalType(Type):
  1738. elem: Type
  1739. def __str__(self) -> str:
  1740. return f"{self.elem}?"
  1741. def is_base_ty_like(self, base_ty: BaseTy) -> bool:
  1742. return self.elem.is_base_ty_like(base_ty)
  1743. def is_symint_like(self) -> bool:
  1744. return self.elem.is_symint_like()
  1745. def is_nullable(self) -> bool:
  1746. return True
  1747. def is_list_like(self) -> ListType | None:
  1748. return self.elem.is_list_like()
  1749. # A type representing a PyTorch custom class
  1750. @dataclass(frozen=True)
  1751. class CustomClassType(Type):
  1752. class_name: str
  1753. def __str__(self) -> str:
  1754. """
  1755. Return the class name will prefix __torch__.torch.classes
  1756. """
  1757. return f"__torch__.torch.classes.{self.class_name}"
  1758. def is_base_ty_like(self, base_ty: BaseTy) -> bool:
  1759. return False
  1760. def is_symint_like(self) -> bool:
  1761. return False
  1762. def is_nullable(self) -> bool:
  1763. """
  1764. Assume a custom class is not nullable.
  1765. """
  1766. return False
  1767. def is_list_like(self) -> ListType | None:
  1768. return None
  1769. # List types specify that we may have multiples of an element. We
  1770. # also support explicit sizes on list types, but these have
  1771. # some nontrivial semantics! (However, for C++ API purposes, explicit
  1772. # sizes are mostly erased from the type system.)
  1773. #
  1774. # DANGER WILL ROBINSON: C++ elaboration depends on elem type; e.g.,
  1775. # int[] elaborates differently than bool[3]!
  1776. @dataclass(frozen=True)
  1777. class ListType(Type):
  1778. elem: Type
  1779. size: int | None
  1780. def __str__(self) -> str:
  1781. size = f"{self.size}" if self.size else ""
  1782. return f"{self.elem}[{size}]"
  1783. def is_base_ty_like(self, base_ty: BaseTy) -> bool:
  1784. return self.elem.is_base_ty_like(base_ty)
  1785. def is_symint_like(self) -> bool:
  1786. return self.elem.is_symint_like()
  1787. def is_nullable(self) -> bool:
  1788. return self.elem.is_nullable()
  1789. def is_list_like(self) -> ListType | None:
  1790. return self
  1791. @dataclass(frozen=True)
  1792. class Argument:
  1793. # NB: I didn't put kwarg_only as a boolean field here, unlike
  1794. # c10::Argument, so that printing works correctly
  1795. name: str
  1796. type: Type
  1797. default: str | None
  1798. # The semantics of the annotation field are a little strange.
  1799. #
  1800. # Alias annotations parametrize Tensors (since Tensors are the only things
  1801. # that can alias.) This motivates why I write Tensor(a!)? (and not, for
  1802. # example, Tensor?(a!)), because the (a!) describes aliasing on the tensor,
  1803. # which may be optional (i.e., the alias annotation should bind first to
  1804. # Tensor, before the optional postfix annotation).
  1805. #
  1806. # However, despite being a property of Tensor, we (and c10::Argument)
  1807. # store the annotation at the top level of the Argument, rather than
  1808. # inside the embedded Tensor type. In the C++ version of this
  1809. # class, we then go through great lengths to mimic the type
  1810. # structure in the annotation structure so we can correlate
  1811. # annotations with types.
  1812. #
  1813. # Now, it turns out, in all applications in code generation, the
  1814. # structure of annotated types is very simple. So we just hard
  1815. # code it here. But if we ever do get anything more complex, this
  1816. # model will have to change!
  1817. annotation: Annotation | None
  1818. @property
  1819. def alias_info(self) -> Annotation | None:
  1820. return self.annotation
  1821. @staticmethod
  1822. def parse(arg: str) -> Argument:
  1823. name: str
  1824. default: str | None
  1825. assert " " in arg, f"illegal argument '{arg}'"
  1826. if "=" in arg:
  1827. assert arg.count("=") == 1, f"illegal argument with default value: '{arg}'"
  1828. type_and_annot_and_name, default = arg.split("=")
  1829. type_and_annot, name = type_and_annot_and_name.rsplit(" ", 1)
  1830. name_and_default = f"{name}={default}"
  1831. else:
  1832. type_and_annot, name_and_default = arg.rsplit(" ", 1)
  1833. name = name_and_default
  1834. default = None
  1835. # TODO: deduplicate annotation matching with Return
  1836. match = re.match(r"Tensor\((.+)\)(.*)", type_and_annot)
  1837. annotation: Annotation | None
  1838. if match:
  1839. # If you update this, make sure the __str__ still works too
  1840. assert match.group(2) in [
  1841. "",
  1842. "?",
  1843. "[]",
  1844. ], "unrecognized alias analysis form with Tensor"
  1845. type_s = "Tensor" + match.group(2)
  1846. annotation = Annotation.parse(match.group(1))
  1847. else:
  1848. type_s = type_and_annot
  1849. annotation = None
  1850. type = Type.parse(type_s)
  1851. r = Argument(
  1852. name=name,
  1853. type=type,
  1854. default=default,
  1855. annotation=annotation,
  1856. )
  1857. assert str(r) == arg, f"{str(r)} != {arg}"
  1858. return r
  1859. @property
  1860. def is_write(self) -> bool:
  1861. return self.annotation is not None and self.annotation.is_write
  1862. def __str__(self) -> str:
  1863. type = f"{self.type}"
  1864. if self.annotation:
  1865. assert type in ["Tensor", "Tensor?", "Tensor[]"]
  1866. type = type.replace("Tensor", f"Tensor({self.annotation})")
  1867. if self.name is None:
  1868. return type
  1869. else:
  1870. mb_default = ""
  1871. if self.default:
  1872. mb_default = f"={self.default}"
  1873. return f"{type} {self.name}{mb_default}"
  1874. @dataclass(frozen=True)
  1875. class Return:
  1876. name: str | None
  1877. type: Type
  1878. annotation: Annotation | None
  1879. @property
  1880. def alias_info(self) -> Annotation | None:
  1881. return self.annotation
  1882. @staticmethod
  1883. def parse(arg: str) -> Return:
  1884. name: str | None
  1885. if " " in arg:
  1886. type_and_annot, name = arg.rsplit(" ", 1)
  1887. else:
  1888. type_and_annot = arg
  1889. name = None
  1890. match = re.match(r"Tensor\((.+)\)(.*)", type_and_annot)
  1891. annotation: Annotation | None
  1892. if match:
  1893. # If you update this, make sure the __str__ still works too
  1894. assert match.group(2) in [
  1895. "",
  1896. "?",
  1897. "[]",
  1898. ], "unrecognized alias analysis form with Tensor"
  1899. type_s = "Tensor" + match.group(2)
  1900. annotation = Annotation.parse(match.group(1))
  1901. else:
  1902. type_s = type_and_annot
  1903. annotation = None
  1904. type = Type.parse(type_s)
  1905. r = Return(
  1906. name=name,
  1907. type=type,
  1908. annotation=annotation,
  1909. )
  1910. assert str(r) == arg, f"{str(r)} != {arg}"
  1911. return r
  1912. @property
  1913. def is_write(self) -> bool:
  1914. return self.annotation is not None and self.annotation.is_write
  1915. def __str__(self) -> str:
  1916. type = f"{self.type}"
  1917. if self.annotation:
  1918. assert type in ["Tensor", "Tensor?", "Tensor[]"]
  1919. type = type.replace("Tensor", f"Tensor({self.annotation})")
  1920. if self.name is None:
  1921. return type
  1922. else:
  1923. return f"{type} {self.name}"
  1924. # Represents the self argument for functions that may be methods
  1925. @dataclass(frozen=True)
  1926. class SelfArgument:
  1927. argument: Argument
  1928. # Bundle of arguments that represent a TensorOptions. This is mostly
  1929. # relevant for the public C++ API but we bake it into the core data
  1930. # model because other APIs often have to interact with it
  1931. @dataclass(frozen=True)
  1932. class TensorOptionsArguments:
  1933. dtype: Argument
  1934. layout: Argument
  1935. device: Argument
  1936. pin_memory: Argument
  1937. def all(self) -> Sequence[Argument]:
  1938. return [self.dtype, self.layout, self.device, self.pin_memory]
  1939. @dataclass(frozen=True)
  1940. class Arguments:
  1941. # pre_self_positional is usually empty, but is notably non-empty
  1942. # for where.self, where the condition argument comes before the
  1943. # self argument
  1944. pre_self_positional: tuple[Argument, ...]
  1945. self_arg: SelfArgument | None
  1946. post_self_positional: tuple[Argument, ...]
  1947. pre_tensor_options_kwarg_only: tuple[Argument, ...]
  1948. tensor_options: TensorOptionsArguments | None
  1949. # post_tensor_options is typically memory format, which should be
  1950. # part of tensor options but isn't right now, and is usually
  1951. # placed after the tensor options arguments
  1952. post_tensor_options_kwarg_only: tuple[Argument, ...]
  1953. # Unlike in the previous codegen, we have factored out 'out' arguments
  1954. # in the canonical representation, removing them from kwarg
  1955. # arguments. This choice is justified by numerous downstream
  1956. # transformations which treat out arguments specially; additionally,
  1957. # you can see that canonicity is not violated!
  1958. out: tuple[Argument, ...] # these are also kwarg-only
  1959. @property
  1960. def flat_non_out(self) -> Sequence[Argument]:
  1961. ret: list[Argument] = []
  1962. ret.extend(self.flat_positional)
  1963. ret.extend(self.flat_kwarg_only)
  1964. return ret
  1965. @property
  1966. def flat_positional(self) -> Sequence[Argument]:
  1967. ret: list[Argument] = []
  1968. ret.extend(self.pre_self_positional)
  1969. if self.self_arg is not None:
  1970. ret.append(self.self_arg.argument)
  1971. ret.extend(self.post_self_positional)
  1972. return ret
  1973. @property
  1974. def post_self_positional_mutable(self) -> Sequence[Argument]:
  1975. return [a for a in self.post_self_positional if a.is_write]
  1976. # NB: doesn't contain out arguments
  1977. @property
  1978. def flat_kwarg_only(self) -> Sequence[Argument]:
  1979. ret: list[Argument] = []
  1980. ret.extend(self.pre_tensor_options_kwarg_only)
  1981. if self.tensor_options is not None:
  1982. ret.extend(self.tensor_options.all())
  1983. ret.extend(self.post_tensor_options_kwarg_only)
  1984. return ret
  1985. @property
  1986. def flat_all(self) -> Sequence[Argument]:
  1987. ret: list[Argument] = []
  1988. ret.extend(self.flat_positional)
  1989. ret.extend(self.flat_kwarg_only)
  1990. ret.extend(self.out)
  1991. return ret
  1992. @property
  1993. def non_out(
  1994. self,
  1995. ) -> Sequence[Argument | SelfArgument | TensorOptionsArguments]:
  1996. ret: list[Argument | SelfArgument | TensorOptionsArguments] = []
  1997. ret.extend(self.positional)
  1998. ret.extend(self.kwarg_only)
  1999. return ret
  2000. @property
  2001. def positional(self) -> Sequence[Argument | SelfArgument]:
  2002. ret: list[Argument | SelfArgument] = []
  2003. ret.extend(self.pre_self_positional)
  2004. if self.self_arg is not None:
  2005. ret.append(self.self_arg)
  2006. ret.extend(self.post_self_positional)
  2007. return ret
  2008. @property
  2009. def kwarg_only(self) -> Sequence[Argument | TensorOptionsArguments]:
  2010. ret: list[Argument | TensorOptionsArguments] = []
  2011. ret.extend(self.pre_tensor_options_kwarg_only)
  2012. if self.tensor_options is not None:
  2013. ret.append(self.tensor_options)
  2014. ret.extend(self.post_tensor_options_kwarg_only)
  2015. return ret
  2016. @property
  2017. def all(self) -> Sequence[Argument | SelfArgument | TensorOptionsArguments]:
  2018. ret: list[Argument | SelfArgument | TensorOptionsArguments] = []
  2019. ret.extend(self.positional)
  2020. ret.extend(self.kwarg_only)
  2021. ret.extend(self.out)
  2022. return ret
  2023. def mutable_arg_names(self) -> list[str]:
  2024. return [
  2025. a.name
  2026. for a in self.flat_all
  2027. if a.annotation is not None and a.annotation.is_write
  2028. ]
  2029. def has_tensor_arg(self) -> bool:
  2030. return any(a.type.is_tensor_like() for a in self.flat_non_out)
  2031. def has_symint_arg(self) -> bool:
  2032. return any(a.type.is_symint_like() for a in self.flat_non_out)
  2033. def has_generator_arg(self) -> bool:
  2034. return any(a.type.is_generator_like() for a in self.flat_non_out)
  2035. def signature(self, *, strip_default: bool = False) -> Arguments:
  2036. # dataclasses.replace could be used here, but it is less
  2037. # type safe so for now I've opted to type everything out
  2038. def strip_arg_annotation(a: Argument) -> Argument:
  2039. return Argument(
  2040. name=a.name,
  2041. type=a.type,
  2042. default=a.default if not strip_default else None,
  2043. annotation=None,
  2044. )
  2045. return Arguments(
  2046. pre_self_positional=tuple(
  2047. map(strip_arg_annotation, self.pre_self_positional)
  2048. ),
  2049. self_arg=(
  2050. SelfArgument(strip_arg_annotation(self.self_arg.argument))
  2051. if self.self_arg is not None
  2052. else None
  2053. ),
  2054. post_self_positional=tuple(
  2055. map(strip_arg_annotation, self.post_self_positional)
  2056. ),
  2057. # Since TensorOptions are dropped, the post_tensor_options_kwargs are
  2058. # converted to pre_tensor_options_kwargs
  2059. pre_tensor_options_kwarg_only=tuple(
  2060. map(strip_arg_annotation, self.pre_tensor_options_kwarg_only)
  2061. )
  2062. + tuple(map(strip_arg_annotation, self.post_tensor_options_kwarg_only)),
  2063. # TensorOptions are dropped in signature,
  2064. # so we can pair factory functions with their out= variants.
  2065. tensor_options=None,
  2066. post_tensor_options_kwarg_only=(),
  2067. # out arguments are dropped in signature
  2068. out=(),
  2069. )
  2070. def remove_self_annotation(self) -> Arguments:
  2071. assert self.self_arg is not None
  2072. return dataclasses.replace(
  2073. self,
  2074. self_arg=SelfArgument(
  2075. dataclasses.replace(self.self_arg.argument, annotation=None)
  2076. ),
  2077. )
  2078. def with_out_args(self, outs: list[Argument]) -> Arguments:
  2079. assert len(self.out) == 0
  2080. return dataclasses.replace(
  2081. self,
  2082. out=tuple(outs),
  2083. )
  2084. @staticmethod
  2085. def _preparse(args: str) -> tuple[list[Argument], list[Argument], list[Argument]]:
  2086. positional: list[Argument] = []
  2087. kwarg_only: list[Argument] = []
  2088. out: list[Argument] = []
  2089. arguments_acc = positional
  2090. # TODO: Use a real parser here; this will get bamboozled
  2091. # by signatures that contain things like std::array<bool, 2> (note the space)
  2092. for arg in args.split(", "):
  2093. if not arg:
  2094. continue
  2095. if arg == "*":
  2096. assert arguments_acc is positional, (
  2097. "invalid syntax: kwarg-only specifier * can only occur once"
  2098. )
  2099. arguments_acc = kwarg_only
  2100. continue
  2101. parg = Argument.parse(arg)
  2102. # Currently, we rely directly on the invariant that there are NO
  2103. # kwarg-only mutating arguments. If you want to relax this,
  2104. # we will need a more semantic way of matching that takes
  2105. # into account return arguments. In that case, you will have
  2106. # to manage out computation a level up, in FunctionSchema. See Note
  2107. # [is_out_fn]
  2108. if parg.annotation is not None and parg.annotation.is_write:
  2109. if arguments_acc is positional:
  2110. pass # do nothing
  2111. elif arguments_acc is kwarg_only:
  2112. arguments_acc = out
  2113. else:
  2114. assert arguments_acc is not out
  2115. arguments_acc.append(parg)
  2116. return positional, kwarg_only, out
  2117. @staticmethod
  2118. def parse(args: str) -> Arguments:
  2119. """
  2120. Input: 'int x, int y, int z'
  2121. """
  2122. # We do this in two phases. First we parse into three
  2123. # main categories: positional, kwarg_only, out.
  2124. # Then, we reparse positional and kwarg_only to separate
  2125. # out the self argument and tensor options arguments.
  2126. positional, kwarg_only, out = Arguments._preparse(args)
  2127. # Split self argument
  2128. self_ix = None
  2129. for i, a in enumerate(positional):
  2130. if a.name == "self":
  2131. self_ix = i
  2132. break
  2133. pre_self_positional: list[Argument]
  2134. self_arg: SelfArgument | None
  2135. post_self_positional: list[Argument]
  2136. if self_ix is not None:
  2137. pre_self_positional = positional[:self_ix]
  2138. self_arg = SelfArgument(positional[self_ix])
  2139. post_self_positional = positional[self_ix + 1 :]
  2140. else:
  2141. pre_self_positional = []
  2142. self_arg = None
  2143. post_self_positional = positional
  2144. # Group tensor options arguments
  2145. pre_tensor_options_kwarg_only: list[Argument] = []
  2146. tensor_options: TensorOptionsArguments | None = None
  2147. post_tensor_options_kwarg_only: list[Argument] = []
  2148. kwarg_only_acc = pre_tensor_options_kwarg_only
  2149. def pred(name: str, ty: Type) -> Callable[[Argument], bool]:
  2150. return lambda a: a.name == name and a.type in [ty, OptionalType(ty)]
  2151. predicates = [ # order matters
  2152. pred("dtype", Type.parse("ScalarType")),
  2153. pred("layout", Type.parse("Layout")),
  2154. pred("device", Type.parse("Device")),
  2155. pred("pin_memory", Type.parse("bool")),
  2156. ]
  2157. i = 0
  2158. while i < len(kwarg_only):
  2159. # If there is enough space...
  2160. if i <= len(kwarg_only) - len(predicates):
  2161. # And the next len(predicates) arguments look like TensorOptions arguments
  2162. if all(
  2163. p(a)
  2164. for p, a in zip(predicates, kwarg_only[i : i + len(predicates)])
  2165. ):
  2166. assert kwarg_only_acc is pre_tensor_options_kwarg_only
  2167. # Group them together as one argument
  2168. tensor_options = TensorOptionsArguments(
  2169. dtype=kwarg_only[i],
  2170. layout=kwarg_only[i + 1],
  2171. device=kwarg_only[i + 2],
  2172. pin_memory=kwarg_only[i + 3],
  2173. )
  2174. i += len(predicates)
  2175. kwarg_only_acc = post_tensor_options_kwarg_only
  2176. continue
  2177. kwarg_only_acc.append(kwarg_only[i])
  2178. i += 1
  2179. return Arguments(
  2180. pre_self_positional=tuple(pre_self_positional),
  2181. self_arg=self_arg,
  2182. post_self_positional=tuple(post_self_positional),
  2183. pre_tensor_options_kwarg_only=tuple(pre_tensor_options_kwarg_only),
  2184. tensor_options=tensor_options,
  2185. post_tensor_options_kwarg_only=tuple(post_tensor_options_kwarg_only),
  2186. out=tuple(out),
  2187. )
  2188. def __str__(self) -> str:
  2189. all_arguments: list[str] = []
  2190. all_arguments.extend(map(str, self.flat_positional))
  2191. if self.flat_kwarg_only or self.out:
  2192. all_arguments.append("*")
  2193. all_arguments.extend(map(str, self.flat_kwarg_only))
  2194. all_arguments.extend(map(str, self.out))
  2195. return ", ".join(all_arguments)
  2196. def __post_init__(self) -> None:
  2197. # TODO: These invariants are weirdly asymmetric?
  2198. # TODO: Fancier types?
  2199. if self.self_arg is None:
  2200. assert not self.pre_self_positional
  2201. if self.tensor_options is None:
  2202. assert not self.post_tensor_options_kwarg_only
  2203. # We don't allow any of the following to have argument annotations,
  2204. # to keep things simple.
  2205. mutable_pre_self_positionals = [
  2206. a
  2207. for a in self.pre_self_positional
  2208. if a.annotation is not None and a.annotation.is_write
  2209. ]
  2210. assert len(mutable_pre_self_positionals) == 0, (
  2211. "mutable pre_self_positional arguments are not currently supported in the schema"
  2212. )
  2213. # Names that validly are __iXXX__ indicating inplace operations.
  2214. # Taken from https://www.python.org/dev/peps/pep-0203/#new-methods
  2215. # NB: PyTorch hasn't actually implemented all of these
  2216. AUGMENTED_ASSIGNMENT_NAMES = [
  2217. "add",
  2218. "sub",
  2219. "mul",
  2220. "div",
  2221. "mod",
  2222. "pow",
  2223. "lshift",
  2224. "rshift",
  2225. "and",
  2226. "xor",
  2227. "or",
  2228. ]
  2229. # A BaseOperatorName is what we think of the operator name, without
  2230. # the overload name. Unusually, we don't represent this as just a
  2231. # string; instead, we directly represent a few important semantic
  2232. # bits of information we derive from the string: namely whether
  2233. # or not it's inplace (add_) and whether or not it's a double-underscore
  2234. # method (__add__)
  2235. @dataclass(frozen=True)
  2236. class BaseOperatorName:
  2237. base: str
  2238. inplace: bool
  2239. dunder_method: bool
  2240. # Note [Overload Ambiguity With Functional Variants]
  2241. # A handful of operators have both a "mutable" and a "functional" variant.
  2242. # (native_batch_norm is a good example, although this isn't the case today).
  2243. # For those operators, the mutable and functional variant take in the same set of
  2244. # arguments, but have different alias annotations.
  2245. # this makes it ambiguous when you try to resolve an OverloadPacket into an overload,
  2246. # given a set of input arguments.
  2247. #
  2248. # So instead of making the "functional" variant in this case a real overload, e.g:
  2249. # native_batch_norm (mutable variant)
  2250. # native_batch_norm.functional (functional variant)
  2251. # we make it a new base operator,
  2252. # native_batch_norm_functional (functional variant)
  2253. #
  2254. # In an ideal world, we would probably invert this so the operators were:
  2255. # native_batch_norm.mutable (mutable variant)
  2256. # native_batch_norm (functional variant)
  2257. #
  2258. # Doing that is BC-breaking though, so we're stuck with the above modeling.
  2259. functional_overload: bool = False
  2260. # NB: We don't officially support namespace in FunctionSchema, we treat this prefix
  2261. # as part of the base operator name, for __str__() to consume.
  2262. # The canonical input (from the rest of the infra) will not contain namespace, but
  2263. # we have a usecase in ExecuTorch where we want to support BaseOperatorName with namespace.
  2264. namespace: str | None = None
  2265. @staticmethod
  2266. def parse(op: str) -> BaseOperatorName:
  2267. assert op != ""
  2268. assert not op.endswith("_out"), (
  2269. "_out suffix is reserved and not permitted for operator names; "
  2270. "did you mean to specify an out overload name instead?"
  2271. )
  2272. # Extract namespace out. Base operator name may or may not contain namespace.
  2273. # E.g., aten::__lshift__ is a valid base operator name, __lshift__ is also valid.
  2274. # We want to split the namespace out from the base operator name.
  2275. match = re.match(r"^(?:(.*)::)?(.*)$", op)
  2276. namespace = match.group(1) if match else ""
  2277. op_without_ns = match.group(2) if match else op
  2278. m = re.match(r"^__([^_]+)__$", op_without_ns)
  2279. if m is not None:
  2280. dunder_method = True
  2281. base = m.group(1)
  2282. if any(base == f"i{n}" for n in AUGMENTED_ASSIGNMENT_NAMES):
  2283. inplace = True
  2284. base = base[1:]
  2285. else:
  2286. inplace = False
  2287. # temporary, this is not intrinsically true but
  2288. # has been historically true for dunder methods
  2289. # we support (but, if we ever got, say, __int__, this would
  2290. # be wrong!)
  2291. assert base[0] != "i"
  2292. else:
  2293. dunder_method = False
  2294. base = op_without_ns
  2295. if base[-1] == "_":
  2296. inplace = True
  2297. base = base[:-1]
  2298. else:
  2299. inplace = False
  2300. # See Note [Overload Ambiguity With Functional Variants]
  2301. functional_suffix = "_functional"
  2302. if base.endswith(functional_suffix):
  2303. functional_overload = True
  2304. base = base[: -len(functional_suffix)]
  2305. # This seems complicated and unnecessary, so banning dunder methods
  2306. # for now on ops that have a functional + mutable variant (like native_batch_norm).
  2307. assert not dunder_method and not inplace
  2308. else:
  2309. functional_overload = False
  2310. r = BaseOperatorName(
  2311. base=base,
  2312. inplace=inplace,
  2313. dunder_method=dunder_method,
  2314. functional_overload=functional_overload,
  2315. namespace=namespace,
  2316. )
  2317. assert str(r) == op, f"{str(r)} != {op}"
  2318. return r
  2319. def __str__(self) -> str:
  2320. namespace_prefix = f"{self.namespace}::" if self.namespace else ""
  2321. if self.dunder_method:
  2322. i = "i" if self.inplace else ""
  2323. return f"{namespace_prefix}__{i}{self.base}__"
  2324. else:
  2325. i = (
  2326. "_"
  2327. if self.inplace
  2328. else "_functional"
  2329. if self.functional_overload
  2330. else ""
  2331. )
  2332. return f"{namespace_prefix}{self.base}{i}"
  2333. # Operator name is the base operator name along with the (typically not
  2334. # user visible) overload string.
  2335. @dataclass(frozen=True)
  2336. class OperatorName:
  2337. name: BaseOperatorName
  2338. overload_name: str
  2339. @staticmethod
  2340. def parse(op_name: str) -> OperatorName:
  2341. if "." in op_name:
  2342. name, overload_name = op_name.split(".", 1)
  2343. else:
  2344. name = op_name
  2345. overload_name = ""
  2346. r = OperatorName(name=BaseOperatorName.parse(name), overload_name=overload_name)
  2347. assert str(r) == op_name, f"{str(r)} != {op_name}"
  2348. return r
  2349. def __str__(self) -> str:
  2350. if self.overload_name:
  2351. return f"{self.name}.{self.overload_name}"
  2352. else:
  2353. return f"{self.name}"
  2354. # NB: This must be synchronized with the naming scheme in
  2355. # aten/src/ATen/templates/Operators.h
  2356. # Given a function schema "aten::op.overload(...)",
  2357. # If there is no overload name, this returns f"{op}"
  2358. # If there is an overload name, this returns f"{op}_{overload}"
  2359. def unambiguous_name(self) -> str:
  2360. if self.overload_name:
  2361. return f"{self.name}_{self.overload_name}"
  2362. else:
  2363. return f"{self.name}"
  2364. def remove_inplace(self) -> OperatorName:
  2365. return OperatorName(
  2366. name=BaseOperatorName(
  2367. base=self.name.base,
  2368. inplace=False,
  2369. dunder_method=self.name.dunder_method,
  2370. ),
  2371. overload_name=self.overload_name,
  2372. )
  2373. def with_overload(self, overload: str) -> OperatorName:
  2374. return OperatorName(
  2375. name=BaseOperatorName(
  2376. base=self.name.base,
  2377. inplace=False,
  2378. dunder_method=self.name.dunder_method,
  2379. ),
  2380. overload_name=overload,
  2381. )
  2382. def gets_generated_out_inplace_wrapper(
  2383. f: NativeFunction, g: NativeFunctionsGroup, b: BackendIndex
  2384. ) -> bool:
  2385. return (
  2386. f.func.kind() is not SchemaKind.functional
  2387. and not b.has_kernel(f)
  2388. and b.has_kernel(g.functional)
  2389. )
  2390. # NativeFunction objects that are views (f.is_view_op returns True)
  2391. # are added into a `NativeFunctionsViewGroup`, which we can use to
  2392. # easily access the generated (optional) view_copy NativeFunction.
  2393. # It's convenient to group them together, so we pair them up in NativeFunctionsViewGroup.
  2394. # See Note [Codegen'd {view}_copy Operators]
  2395. #
  2396. # One property of this representation is that in order for a view-like op to be part of
  2397. # a NativeFunctionsViewGroup, the "aliasing" version of that view op must exist.
  2398. # There's one case where that doesn't happen: we have a non-aliasing `narrow_copy.out` op,
  2399. # but don't have corresponding aliasing `narrow.out` op.
  2400. # This means that `narrow_copy.out` won't appear as a NativeFunctionsViewGroup.
  2401. @dataclass(frozen=True)
  2402. class NativeFunctionsViewGroup:
  2403. view: NativeFunction
  2404. # Note: the {view}_copy operator is optional because we currently don't generate copy variants
  2405. # for all view ops. Notably, we don't generate them for CompositeImplicitAutograd views
  2406. # (we already get them "for free" through decomposition)
  2407. view_copy: NativeFunction | None
  2408. # view_inplace ops are also optional, but every view_inplace op should have out-of-place variant.
  2409. view_inplace: NativeFunction | None
  2410. def __post_init__(self) -> None:
  2411. assert self.view.is_view_op
  2412. if self.view_copy is None:
  2413. assert not gets_generated_view_copy(self.view), (
  2414. f"{str(self.view.func.name)} appears to be a new operator that aliases its inputs."
  2415. " The codegen expects you to add a corresponding operator to native_functions.yaml:"
  2416. f" {get_view_copy_name(self.view)!s}."
  2417. " See Note [view_copy NativeFunctions] for details."
  2418. )
  2419. else:
  2420. assert self.view_copy.func.name.name.base.endswith(("_copy", "_scatter"))
  2421. assert self.view.func.signature() == self.view_copy.func.signature(
  2422. strip_view_copy_name=True,
  2423. )
  2424. assert "view_copy" in self.view_copy.tags, (
  2425. f"{str(self.view_copy.func.name), str(self.view.tags)} appears to be a view_copy operator. The codegen expects"
  2426. " view_copy operators to be annotated with the 'view_copy' tag in native_functions.yaml."
  2427. " See Note [view_copy NativeFunction] for details."
  2428. )
  2429. if self.view_inplace is not None:
  2430. assert self.view.func.signature() == self.view_inplace.func.signature()
  2431. if self.view.has_composite_implicit_autograd_kernel:
  2432. if self.view_inplace is not None:
  2433. assert self.view_inplace.has_composite_implicit_autograd_kernel, (
  2434. f"{str(self.view.func.name)} and {str(self.view_inplace.func.name)} must either"
  2435. " both have CompositeImplicitAutograd kernels, or both not have composite kernels."
  2436. )
  2437. if self.view.has_composite_implicit_autograd_nested_tensor_kernel:
  2438. if self.view_inplace is not None:
  2439. assert self.view_inplace.has_composite_implicit_autograd_nested_tensor_kernel, (
  2440. f"{str(self.view.func.name)} and {str(self.view_inplace.func.name)} must either"
  2441. " both have CompositeImplicitAutogradNestedTensor kernels, or both not have composite kernels."
  2442. )
  2443. def functions(self, *, include_copy: bool = True) -> Iterator[NativeFunction]:
  2444. yield self.view
  2445. if self.view_inplace is not None:
  2446. yield self.view_inplace
  2447. if self.view_copy is not None and include_copy:
  2448. yield self.view_copy
  2449. @property
  2450. def root_name(self) -> str:
  2451. return self.view.root_name
  2452. @property
  2453. def composite(self) -> bool:
  2454. # We currently assert that the "group" is consistent.
  2455. # If the view op is composite, then its view_inplace op is too.
  2456. return self.view.has_composite_implicit_autograd_kernel
  2457. def gets_generated_view_copy(f: NativeFunction) -> bool:
  2458. # Only aliasing (view) operators get a copy variant.
  2459. if not f.is_view_op:
  2460. return False
  2461. # We don't need to bother generating copy variants for CompositeImplicitAutograd ops,
  2462. # because we can let them decompose into base view ops.
  2463. if f.has_composite_implicit_autograd_kernel:
  2464. return False
  2465. # We also don't need to generate copy variants for inplace views.
  2466. if "inplace_view" in f.tags:
  2467. return False
  2468. # Assume ops ending in _inverse have manually-defined copy variants
  2469. # (e.g. slice_inverse() has the copy variant slice_scatter()).
  2470. # We -could- probably generate these as well, but the codegen will be
  2471. # slightly different, and hand-writing these few kernels keeps codegen
  2472. # complexity lower.
  2473. if f.func.name.name.base.endswith("_inverse"):
  2474. return False
  2475. return True
  2476. # Given a NativeFunction that corresponds to a view op,
  2477. # returns the OperatorName of the corresponding "copy" variant of the op.
  2478. def get_view_copy_name(f: NativeFunction) -> OperatorName:
  2479. # Right now, when asking for a view op's corresponding "view_copy" name
  2480. # we assert for sanity that the op is allowed to have a generated view_copy variant.
  2481. # (We can do this because "gets_generated_view_copy()" tell us which ops get a generated view_copy op).
  2482. # However, narrow_copy() already exists as an op directly in native_functions.yaml.
  2483. # I'm hardcoding narrow_copy here for now to maintain the assert,
  2484. # But we could also just get rid of the assert.
  2485. list_of_ops_with_explicit_view_copy_operators = ["narrow"]
  2486. if str(f.func.name) not in list_of_ops_with_explicit_view_copy_operators:
  2487. assert gets_generated_view_copy(f)
  2488. base_name = f"{f.func.name.name.base}_copy"
  2489. view_copy_name = OperatorName(
  2490. name=BaseOperatorName(
  2491. base=base_name, inplace=False, dunder_method=f.func.name.name.dunder_method
  2492. ),
  2493. overload_name=f.func.name.overload_name,
  2494. )
  2495. return view_copy_name
  2496. # Helper functions for parsing argument lists (both inputs and returns)
  2497. def parse_returns(return_decl: str) -> tuple[Return, ...]:
  2498. """
  2499. Input: '()'
  2500. Output: []
  2501. """
  2502. if return_decl == "()":
  2503. return ()
  2504. if return_decl[0] == "(" and return_decl[-1] == ")":
  2505. return_decl = return_decl[1:-1]
  2506. return tuple(Return.parse(arg) for arg in return_decl.split(", "))
  2507. # A Precompute instance consists of a map from kernel argument name
  2508. # to the list of Argument instances that should replace that
  2509. # kernel argument in the impl function.
  2510. @dataclass(frozen=True)
  2511. class Precompute:
  2512. # A map from kernel argument name -> a list of precomputed
  2513. # elements that replaces/supersedes it.
  2514. replace: dict[str, list[Argument]]
  2515. # List of precomputed args added without replacement
  2516. add: list[Argument]
  2517. @staticmethod
  2518. def parse(src: object) -> Precompute:
  2519. assert isinstance(src, list)
  2520. # src is a list of strings of the format:
  2521. # {kernel param name} -> {replacement decl}[, {replacement decl}, ...]
  2522. # [{add decl}[, {add decl}, ...]]
  2523. # The last line is optional and contains the precomputed parameters that are
  2524. # added without replacement.
  2525. # The other lines are parsed to get the names of which precomputed elements
  2526. # should replace which kernel arguments.
  2527. add_args = []
  2528. if " -> " not in src[-1]:
  2529. add_list = src[-1].split(",")
  2530. add_args = [Argument.parse(name.strip()) for name in add_list]
  2531. src = src[:-1]
  2532. replace = {}
  2533. for raw_replace_item in src:
  2534. assert isinstance(raw_replace_item, str)
  2535. assert " -> " in raw_replace_item, (
  2536. "precomputed parameters without replacement"
  2537. " are allowed only in the last line"
  2538. )
  2539. arg, with_list_raw = raw_replace_item.split(" -> ")
  2540. assert " " not in arg, (
  2541. f"illegal kernel param name '{arg}' in precomputed parameters'"
  2542. )
  2543. with_list = with_list_raw.split(",")
  2544. with_list_args = [Argument.parse(name.strip()) for name in with_list]
  2545. replace[arg] = with_list_args
  2546. r = Precompute(replace=replace, add=add_args)
  2547. assert r.to_list() == src, "r.to_list() != src"
  2548. return r
  2549. def __post_init__(self) -> None:
  2550. # the template parameters are upper so if these are the
  2551. # same then it is ambiguous
  2552. for a in self.add:
  2553. assert a.name.upper() != a.name
  2554. for args in self.replace.values():
  2555. for a in args:
  2556. assert a.name.upper() != a.name
  2557. def to_list(self) -> list[str]:
  2558. replace_list = []
  2559. for kernel_param, replacement_params in self.replace.items():
  2560. replacements = ", ".join(str(param) for param in replacement_params)
  2561. replace_list.append(f"{kernel_param} -> {replacements}")
  2562. return replace_list