model.py 112 KB

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