model.py 92 KB

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