model.py 121 KB

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