model.py 107 KB

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