gen.py 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032
  1. from __future__ import annotations
  2. import argparse
  3. import functools
  4. import json
  5. import keyword
  6. import os
  7. from collections import defaultdict, namedtuple, OrderedDict
  8. from dataclasses import dataclass, field
  9. from pathlib import Path
  10. from typing import Any, Literal, TYPE_CHECKING, TypeVar
  11. from typing_extensions import assert_never
  12. import yaml
  13. import torchgen.api.dispatcher as dispatcher
  14. import torchgen.api.meta as meta
  15. import torchgen.api.native as native
  16. import torchgen.api.structured as structured
  17. import torchgen.dest as dest
  18. from torchgen.api import cpp
  19. from torchgen.api.translate import translate
  20. from torchgen.api.types import (
  21. Binding,
  22. CppSignature,
  23. CppSignatureGroup,
  24. DispatcherSignature,
  25. NamedCType,
  26. NativeSignature,
  27. SpecialArgName,
  28. )
  29. from torchgen.context import (
  30. method_with_native_function,
  31. native_function_manager,
  32. with_native_function,
  33. with_native_function_and_indices,
  34. )
  35. from torchgen.gen_aoti_c_shim import (
  36. gen_aoti_c_shim_files,
  37. gen_static_dispatch_backend_call_signature,
  38. )
  39. from torchgen.gen_functionalization_type import (
  40. gen_functionalization_definition,
  41. gen_functionalization_registration,
  42. gen_functionalization_view_inverse_declaration,
  43. gen_functionalization_view_meta_classes_decl,
  44. gen_functionalization_view_meta_classes_impl,
  45. GenCompositeViewCopyKernel,
  46. )
  47. from torchgen.gen_vmap_plumbing import gen_all_vmap_plumbing
  48. from torchgen.model import (
  49. Argument,
  50. BackendIndex,
  51. BackendMetadata,
  52. BaseOperatorName,
  53. DEFAULT_KERNEL_NAMESPACE,
  54. dispatch_device_map,
  55. DispatchKey,
  56. FRAGMENT_NAMESPACES,
  57. FunctionSchema,
  58. is_cuda_dispatch_key,
  59. is_generic_dispatch_key,
  60. is_ufunc_dispatch_key,
  61. is_xpu_dispatch_key,
  62. Location,
  63. NativeFunction,
  64. NativeFunctionsGroup,
  65. NativeFunctionsViewGroup,
  66. OperatorName,
  67. OptionalType,
  68. SchemaKind,
  69. SelfArgument,
  70. STRUCTURED_DISPATCH_KEYS,
  71. TensorOptionsArguments,
  72. Type,
  73. Variant,
  74. ViewSchemaKind,
  75. )
  76. from torchgen.native_function_generation import (
  77. add_generated_native_functions,
  78. gen_composite_functional_kernel,
  79. gen_composite_out_kernel,
  80. pre_group_native_functions,
  81. )
  82. from torchgen.selective_build.selector import SelectiveBuilder
  83. from torchgen.utils import (
  84. concatMap,
  85. context,
  86. FileManager,
  87. make_file_manager,
  88. mapMaybe,
  89. NamespaceHelper,
  90. Target,
  91. )
  92. from torchgen.yaml_utils import YamlDumper, YamlLoader
  93. if TYPE_CHECKING:
  94. from collections.abc import Callable, Sequence
  95. T = TypeVar("T")
  96. # Welcome to the ATen code generator v2! The ATen code generator is
  97. # responsible for parsing native_functions.yaml and then generating
  98. # various generated files (e.g., TypeDefault.cpp) based on the operators
  99. # defined in this file. This means that the code generator knows how to
  100. # parse function schema, and then translate this into various C++ types
  101. # and boilerplate code.
  102. #
  103. # Some things to know about this file when you modify it:
  104. #
  105. # - This file has STRICT mypy typechecking. Typecheck it with
  106. # `mypy --config mypy-strict.ini` in the root source directory
  107. #
  108. # - Most of the heavy lifting lives in external modules:
  109. # - 'model' has the data model for native_functions.yaml. The classes
  110. # in those file represent what you see when you look at
  111. # a native_functions.yaml
  112. # - 'api' has conversions for how to translate JIT schema into
  113. # the various C++ APIs that the codegen interacts with. There
  114. # are in fact THREE different C++ APIs: the public C++ API,
  115. # the dispatcher API, and the legacy dispatcher API. See each
  116. # of these respective files for more information
  117. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
  118. #
  119. # HELPER FUNCTIONS
  120. #
  121. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
  122. # A custom loader for YAML to let us also keep track of line numbers
  123. # of each entry in the YAML file
  124. class LineLoader(YamlLoader):
  125. def construct_mapping(self, node, deep=False): # type: ignore[no-untyped-def]
  126. mapping = super().construct_mapping(node, deep=deep) # type: ignore[no-untyped-call]
  127. # Add 1 so line numbering starts at 1
  128. mapping["__line__"] = node.start_mark.line + 1
  129. return mapping
  130. # Parse native_functions.yaml into a sequence of NativeFunctions and Backend Indices.
  131. ParsedYaml = namedtuple("ParsedYaml", ["native_functions", "backend_indices"])
  132. _GLOBAL_PARSE_NATIVE_YAML_CACHE: dict[str, ParsedYaml] = {}
  133. _GLOBAL_PARSE_TAGS_YAML_CACHE: dict[str, set[str]] = {}
  134. def file_manager_from_dispatch_key(
  135. dispatch_key: DispatchKey,
  136. device_fms: dict[str, FileManager],
  137. default_fm: FileManager,
  138. ) -> FileManager:
  139. fm = device_fms.get(
  140. next(
  141. (
  142. device
  143. for check, device in dispatch_device_map.items()
  144. if check(dispatch_key)
  145. ),
  146. "",
  147. ),
  148. default_fm,
  149. )
  150. return fm
  151. def parse_native_yaml_struct(
  152. es: object,
  153. valid_tags: set[str],
  154. ignore_keys: set[DispatchKey] | None = None,
  155. path: str = "<stdin>",
  156. skip_native_fns_gen: bool = False,
  157. ) -> ParsedYaml:
  158. assert isinstance(es, list)
  159. rs: list[NativeFunction] = []
  160. bs: dict[DispatchKey, dict[OperatorName, BackendMetadata]] = defaultdict(dict)
  161. for e in es:
  162. assert isinstance(e, dict), f"expected to be dict: {e}"
  163. assert isinstance(e.get("__line__"), int), e
  164. loc = Location(path, e["__line__"])
  165. funcs = e.get("func")
  166. assert funcs is not None, f"missed 'func' in {e}"
  167. with context(lambda: f"in {loc}:\n {funcs}"):
  168. func, m = NativeFunction.from_yaml(e, loc, valid_tags, ignore_keys)
  169. rs.append(func)
  170. BackendIndex.grow_index(bs, m)
  171. error_check_native_functions(rs)
  172. # Default dict is to prevent the codegen from barfing when we have a dispatch key that has no kernels yet.
  173. indices: dict[DispatchKey, BackendIndex] = defaultdict(
  174. lambda: BackendIndex(
  175. dispatch_key=DispatchKey.Undefined,
  176. use_out_as_primary=True,
  177. external=False,
  178. device_guard=False,
  179. # I'm actually not sure about this; undefined could be hit on
  180. # empty TensorList, hypothetically that could have sizes in it
  181. index={},
  182. )
  183. )
  184. if not skip_native_fns_gen:
  185. add_generated_native_functions(rs, bs)
  186. for k, v in bs.items():
  187. # All structured in-tree operators are implemented in terms of their out operator.
  188. indices[k] = BackendIndex(
  189. dispatch_key=k,
  190. use_out_as_primary=True,
  191. external=False,
  192. # Only cuda-like devices in tree require device guards
  193. device_guard=is_cuda_dispatch_key(k) or is_xpu_dispatch_key(k),
  194. index=v,
  195. )
  196. return ParsedYaml(rs, indices)
  197. def parse_tags_yaml_struct(es: object, path: str = "<stdin>") -> set[str]:
  198. assert isinstance(es, list)
  199. rs: set[str] = set()
  200. for e in es:
  201. assert isinstance(e.get("__line__"), int), e
  202. loc = Location(path, e["__line__"])
  203. tags = e.get("tag")
  204. with context(lambda: f"in {loc}:\n {tags}"):
  205. e_i = e.copy()
  206. name = e_i.pop("tag")
  207. desc = e_i.pop("desc", "")
  208. # ensure that each tag has a non-empty description
  209. assert desc != ""
  210. rs.add(name)
  211. return rs
  212. @functools.cache
  213. def parse_tags_yaml(path: str) -> set[str]:
  214. global _GLOBAL_PARSE_TAGS_YAML_CACHE
  215. if path not in _GLOBAL_PARSE_TAGS_YAML_CACHE:
  216. with open(path) as f:
  217. es = yaml.load(f, Loader=LineLoader)
  218. _GLOBAL_PARSE_TAGS_YAML_CACHE[path] = parse_tags_yaml_struct(es, path=path)
  219. return _GLOBAL_PARSE_TAGS_YAML_CACHE[path]
  220. def parse_native_yaml(
  221. path: str,
  222. tags_yaml_path: str,
  223. ignore_keys: set[DispatchKey] | None = None,
  224. *,
  225. skip_native_fns_gen: bool = False,
  226. loaded_yaml: object | None = None,
  227. ) -> ParsedYaml:
  228. global _GLOBAL_PARSE_NATIVE_YAML_CACHE
  229. if path not in _GLOBAL_PARSE_NATIVE_YAML_CACHE:
  230. valid_tags = parse_tags_yaml(tags_yaml_path)
  231. # if a loaded yaml is provided, use that instead of reading from path
  232. if loaded_yaml is None:
  233. with open(path) as f:
  234. es = yaml.load(f, Loader=LineLoader)
  235. else:
  236. es = loaded_yaml
  237. _GLOBAL_PARSE_NATIVE_YAML_CACHE[path] = parse_native_yaml_struct(
  238. es,
  239. valid_tags,
  240. ignore_keys,
  241. path=path,
  242. skip_native_fns_gen=skip_native_fns_gen,
  243. )
  244. return _GLOBAL_PARSE_NATIVE_YAML_CACHE[path]
  245. # Some assertions are already performed during parsing, but those are only within a single NativeFunction.
  246. # Assertions here are meant to be performed across NativeFunctions.
  247. def error_check_native_functions(funcs: Sequence[NativeFunction]) -> None:
  248. func_map: dict[OperatorName, NativeFunction] = {}
  249. base_func_map: dict[BaseOperatorName, list[NativeFunction]] = defaultdict(list)
  250. for f in funcs:
  251. func_map[f.func.name] = f
  252. base_func_map[f.func.name.name].append(f)
  253. for f in funcs:
  254. if f.structured_delegate is not None:
  255. delegate_func = func_map.get(f.structured_delegate)
  256. assert delegate_func is not None, (
  257. f"{f.func.name} is marked as a structured_delegate pointing to "
  258. f"{f.structured_delegate}, but {f.structured_delegate} is missing."
  259. )
  260. assert delegate_func.structured, (
  261. f"{f.func.name} is marked as a structured_delegate pointing to "
  262. f"{f.structured_delegate}, but {f.structured_delegate} is not marked as structured. "
  263. f"Consider adding 'structured=True' to the delegated operator"
  264. )
  265. # Check for reserved Python keywords
  266. PYTHON_RESERVED_KEYWORDS = set(keyword.kwlist)
  267. # List of pre-existing operators that are known to have reserved keywords
  268. # Exclusion list is used to suppress the assertion for these operators
  269. EXCLUSION_LIST = {
  270. ("_has_compatible_shallow_copy_type", "from"),
  271. ("random_.from", "from"),
  272. ("uniform_", "from"),
  273. }
  274. for arg in f.func.arguments.flat_all:
  275. if arg.name in PYTHON_RESERVED_KEYWORDS:
  276. if (str(f.func.name), arg.name) not in EXCLUSION_LIST:
  277. raise AssertionError(
  278. f"Argument name '{arg.name}' in function '{f.func.name}' is a reserved Python keyword."
  279. )
  280. # See Note [resize_ in Functionalization]
  281. # resize_() is technically an inplace view op (and therefore needs the tag),
  282. # but it would be overkill to add a true "view" variant of resize.
  283. # Instead, resize_() gets special treatment in functionalization,
  284. # and we have a resize() op that is non-aliasing + functional.
  285. if (
  286. "inplace_view" in f.tags
  287. and str(f.func.name) != "resize_"
  288. and str(f.func.name) != "resize_as_"
  289. and str(f.func.name.name) != "set_"
  290. ):
  291. base_name = f.func.name.name
  292. assert base_name.inplace, (
  293. f"{f.func.name} is marked with tag: inplace_view, but it doesn't follow the naming "
  294. "convention for inplace ops - the codegen expects the base name to have a trailing underscore. "
  295. )
  296. out_of_place_base_name = BaseOperatorName(
  297. base_name.base, False, base_name.dunder_method
  298. )
  299. assert len(base_func_map[out_of_place_base_name]) > 0, (
  300. f"{f.func.name} is marked with tag: inplace_view. The codegen expects there to be a corresponding "
  301. f"out-of-place view op with the name '{base_name}' and matching schema, but it didn't find one. "
  302. )
  303. def cpp_string(s: str) -> str:
  304. """Convert a python string into a c++ string literal"""
  305. s = s.replace("\\", "\\\\")
  306. s = s.replace('"', '\\"')
  307. s = s.replace("\a", "\\a")
  308. s = s.replace("\b", "\\b")
  309. s = s.replace("\f", "\\f")
  310. s = s.replace("\n", "\\n")
  311. s = s.replace("\v", "\\v")
  312. s = s.replace("\t", "\\t")
  313. return f'"{s}"'
  314. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
  315. #
  316. # C++ CODE GENERATION
  317. #
  318. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
  319. # Most functions in this section are curried: they consist of a function
  320. # that takes some parameters (e.g., what is to be generated) which itself
  321. # returns a function that actually maps NativeFunction to the code
  322. # to be generated. This pattern makes it convenient to use map, concatMap
  323. # and similar functional combinators.
  324. def static_dispatch_keys(backends: list[BackendIndex]) -> list[DispatchKey]:
  325. if len(backends) == 0:
  326. return []
  327. else:
  328. return [backend.dispatch_key for backend in backends] + [
  329. DispatchKey.CompositeImplicitAutograd,
  330. DispatchKey.CompositeImplicitAutogradNestedTensor,
  331. DispatchKey.CompositeExplicitAutograd,
  332. DispatchKey.CompositeExplicitAutogradNonFunctional,
  333. ]
  334. def get_static_dispatch_backend(
  335. f: NativeFunction, backend_index: BackendIndex
  336. ) -> DispatchKey | None:
  337. if f.structured_delegate is not None or backend_index.has_kernel(f):
  338. # TODO: for ops with structured_delegate it should check the dispatch table of
  339. # the out variant instead. For now, these structured ops all have CPU/CUDA kernels
  340. # so we always dispatch to the `backend`, but this could be wrong when we
  341. # migrate math/default_backend ops to use structured delegate.
  342. return backend_index.dispatch_key
  343. elif f.has_composite_explicit_autograd_kernel:
  344. return DispatchKey.CompositeExplicitAutograd
  345. elif f.has_composite_explicit_autograd_non_functional_kernel:
  346. return DispatchKey.CompositeExplicitAutogradNonFunctional
  347. elif f.has_composite_implicit_autograd_kernel:
  348. return DispatchKey.CompositeImplicitAutograd
  349. elif f.has_composite_implicit_autograd_nested_tensor_kernel:
  350. return DispatchKey.CompositeImplicitAutogradNestedTensor
  351. return None
  352. def static_dispatch_ops_header(
  353. f: NativeFunction, backend_index: list[BackendIndex]
  354. ) -> str | None:
  355. if backend_index is None or f.manual_kernel_registration:
  356. return None
  357. output = []
  358. for index in backend_index:
  359. dispatch_key = get_static_dispatch_backend(f, index)
  360. if dispatch_key is not None:
  361. output.append(
  362. f"#include <ATen/ops/{f.root_name}_{dispatch_key.lower()}_dispatch.h>"
  363. )
  364. return "\n".join(output)
  365. def static_dispatch_extra_headers(backends: list[BackendIndex]) -> list[str]:
  366. return [
  367. f"#include <ATen/{dispatch_key}Functions.h>"
  368. for dispatch_key in static_dispatch_keys(backends)
  369. ]
  370. # Translates arguments of `sig` to CppSignature bindings.
  371. # Note that we have a special case for `memory_format` argument and this case is not covered by
  372. # tools.codegen.api.translate() yet as its application is limited to static dispatch.
  373. def translate_args(
  374. sig: CppSignature | DispatcherSignature,
  375. cpp_sig: CppSignature,
  376. ) -> str:
  377. # Adds SpecialArgName.possibly_redundant_memory_format NamedCType for memory_format bindings
  378. def add_spl_memory_format_binding(input_bindings: list[Binding]) -> list[Binding]:
  379. output_bindings: list[Binding] = []
  380. for binding in input_bindings:
  381. if binding.name == "memory_format":
  382. spl_mem_format_binding = Binding(
  383. nctype=NamedCType(
  384. SpecialArgName.possibly_redundant_memory_format,
  385. binding.nctype.type,
  386. ),
  387. name=binding.name,
  388. default=binding.default,
  389. argument=binding.argument,
  390. )
  391. output_bindings.append(spl_mem_format_binding)
  392. else:
  393. output_bindings.append(binding)
  394. return output_bindings
  395. src_bindings = list(sig.arguments())
  396. goal_bindings = list(cpp_sig.arguments())
  397. # When last argument of CPP signature has SpecialArgName.possibly_redundant_memory_format NCType,
  398. # get memory_format bindings of dispatcher signature to have the same NCType as well
  399. for arg in goal_bindings:
  400. if arg.nctype.name == SpecialArgName.possibly_redundant_memory_format:
  401. src_bindings = add_spl_memory_format_binding(src_bindings)
  402. break
  403. exprs = translate(src_bindings, goal_bindings)
  404. return ", ".join(a.expr for a in exprs)
  405. def generate_static_dispatch_backend_call(
  406. sig: CppSignature | DispatcherSignature,
  407. f: NativeFunction,
  408. backend_index: BackendIndex,
  409. ) -> str:
  410. cpp_sig = gen_static_dispatch_backend_call_signature(sig, f)
  411. name = cpp_sig.name()
  412. exprs = translate_args(sig, cpp_sig)
  413. backend_metadata = backend_index.get_kernel(f)
  414. kernel_ns = (
  415. backend_metadata.cpp_namespace
  416. if backend_metadata and backend_metadata.cpp_namespace
  417. else DEFAULT_KERNEL_NAMESPACE
  418. )
  419. ns = kernel_ns.replace("::native", "")
  420. return f"return {ns}::{backend_index.dispatch_key.lower()}::{name}({exprs});"
  421. def generate_static_dispatch_fallback_call(
  422. sig: CppSignature | DispatcherSignature,
  423. f: NativeFunction,
  424. backend_indices: list[BackendIndex],
  425. ) -> str:
  426. cpp_sigs = CppSignatureGroup.from_native_function(
  427. f, method=False, fallback_binding=False
  428. )
  429. if sig.symint and f.func.has_symint():
  430. cpp_sig = cpp_sigs.symint_signature
  431. else:
  432. cpp_sig = cpp_sigs.signature
  433. assert cpp_sig is not None
  434. name = cpp_sig.name()
  435. exprs = translate_args(sig, cpp_sig)
  436. ns = DEFAULT_KERNEL_NAMESPACE.replace("::native", "")
  437. if f.has_composite_explicit_autograd_kernel:
  438. return f"return {ns}::{DispatchKey.CompositeExplicitAutograd.lower()}::{name}({exprs});"
  439. elif f.has_composite_explicit_autograd_non_functional_kernel:
  440. return f"return {ns}::{DispatchKey.CompositeExplicitAutogradNonFunctional.lower()}::{name}({exprs});"
  441. elif f.has_composite_implicit_autograd_kernel:
  442. return f"return {ns}::{DispatchKey.CompositeImplicitAutograd.lower()}::{name}({exprs});"
  443. elif f.has_composite_implicit_autograd_nested_tensor_kernel:
  444. return f"return {ns}::{DispatchKey.CompositeImplicitAutogradNestedTensor.lower()}::{name}({exprs});"
  445. else:
  446. return f"""TORCH_CHECK(false, "Static dispatch does not support {name} for\
  447. {", ".join([str(index.dispatch_key) for index in backend_indices])} ");"""
  448. def static_dispatch(
  449. sig: CppSignature | DispatcherSignature,
  450. f: NativeFunction,
  451. backend_indices: list[BackendIndex],
  452. ) -> str:
  453. """
  454. For a given `NativeFunction`, find out the corresponding backend and dispatch to it. If more than one
  455. backends exist, fallback to static dispatch by determining dispatch key from inputs.
  456. Arguments:
  457. sig: A CppSignature or DispatcherSignature for this native function we want to use.
  458. f: NativeFunction to generate static dispatch.
  459. backend_indices: All available backends.
  460. Return:
  461. C++ code to call backend-specific functions, e.g., "return at::cpu::add(self, other, scale);"
  462. """
  463. if len(backend_indices) == 0 or f.manual_kernel_registration:
  464. return ""
  465. keys = [
  466. b
  467. for b in backend_indices
  468. if b.has_kernel(f)
  469. or (
  470. f.structured_delegate is not None
  471. and b.dispatch_key in STRUCTURED_DISPATCH_KEYS
  472. )
  473. ]
  474. if len(keys) == 1:
  475. return generate_static_dispatch_backend_call(sig, f, keys[0])
  476. elif len(keys) == 0:
  477. return generate_static_dispatch_fallback_call(sig, f, backend_indices)
  478. native_tensor_args = [
  479. a.name
  480. for a in sig.arguments()
  481. if isinstance(a.argument, SelfArgument)
  482. or isinstance(a.argument, Argument)
  483. and a.argument.type.is_tensor_like()
  484. ]
  485. tensor_args = ", ".join(native_tensor_args)
  486. tensor_opts = f.func.arguments.tensor_options
  487. stmts = []
  488. subexprs: list[str] = []
  489. if tensor_opts is not None:
  490. subexprs.append(
  491. "DispatchKeySet(c10::computeDispatchKey(dtype, layout, device))"
  492. )
  493. if tensor_args != "":
  494. subexprs.append(f"c10::detail::multi_dispatch_key_set({tensor_args})")
  495. stmts.append(f"""DispatchKeySet _dk_set = {" | ".join(subexprs)};""")
  496. stmts.append("DispatchKey _dk = c10::highestPriorityBackendTypeId(_dk_set);")
  497. dispatch_code = []
  498. for index in keys:
  499. dispatch_code.append(f"""case DispatchKey::{index.dispatch_key}:""")
  500. dispatch_code.append(
  501. f"""\t{generate_static_dispatch_backend_call(sig, f, index)};"""
  502. )
  503. fallback = generate_static_dispatch_fallback_call(sig, f, backend_indices)
  504. connector = "\n\t\t"
  505. return f"""
  506. {connector.join(stmts)}
  507. switch (_dk) {{
  508. {connector.join(dispatch_code)}
  509. default:
  510. {fallback}
  511. }}
  512. """
  513. # Generates RegisterSchema.cpp. Depending on the selector, either
  514. # all schemas are registered, or only some are (in the case of
  515. # selective build)
  516. @dataclass(frozen=True)
  517. class RegisterSchema:
  518. selector: SelectiveBuilder
  519. known_tags: dict[str, int] = field(default_factory=dict)
  520. @method_with_native_function
  521. def __call__(self, f: NativeFunction) -> str | None:
  522. if not self.selector.is_native_function_selected(f):
  523. return None
  524. tags = "{" + ", ".join(f"at::Tag::{tag}" for tag in sorted(f.tags)) + "}"
  525. if tags == "{}":
  526. return f"m.def({cpp_string(str(f.func))}, {{}});\n"
  527. maybe_tags = ""
  528. if tags not in self.known_tags:
  529. idx = len(self.known_tags)
  530. self.known_tags[tags] = idx
  531. maybe_tags = f"const std::vector<at::Tag> tags_{idx} = {tags};\n"
  532. return f"{maybe_tags}m.def({cpp_string(str(f.func))}, tags_{self.known_tags[tags]});\n"
  533. # Generates Operators.h and Operators.cpp.
  534. # These provide macros that, given an operator and overload name, allow users
  535. # to access an "un-overloaded" function version of the operator. This
  536. # is useful for extension writers who want to (1) want to decltype the operator
  537. # and (2) don't want to worry about method-only operators.
  538. @dataclass(frozen=True)
  539. class ComputeOperators:
  540. target: Literal[Target.DECLARATION, Target.DEFINITION]
  541. static_dispatch_backend_indices: list[BackendIndex]
  542. @method_with_native_function
  543. def __call__(self, f: NativeFunction) -> str:
  544. sig = DispatcherSignature.from_schema(f.func)
  545. name = f.func.name.unambiguous_name()
  546. if self.target is Target.DECLARATION:
  547. # Note [The ATen Operators API]
  548. # The ATen Operators API lives in the at::_ops namespace, and contains compile-time
  549. # metadata about each operator + entry points into the Dispatcher.
  550. # The C++ function, method, and redispatch API's are all implemented as wrappers
  551. # into various bits of the structs defined here.
  552. #
  553. # Important characteristics about the Operators API:
  554. # (1) It follows the Dispatcher API.
  555. # This is kind of necessary to avoid overhead.
  556. # For example: if it followed the C++ API, then all of the faithful C++ factory functions
  557. # would need to wrap their arguments into TensorOptions only to unwrap them again.
  558. # (2) Overload names are disambiguated.
  559. # This is helpful for pytorch extenders who would like to decltype() an aten operator,
  560. # that has overloads, e.g. decltype(at::_ops::mul_Tensor::call)
  561. # (3) No argument defaulting is allowed.
  562. # This is more of an implementation detail to avoid #include cycles,
  563. # since TensorBody.h (which defines the Tensor class) needs to include this file.
  564. # (4) manual_cpp_bindings and faithful names are not included in the API.
  565. # This applies to stuff like __dispatch__is_complex(), and add_outf().
  566. # These aren't "real aten ops", they're just additional functions provided by the C++ API.
  567. # They're implemented as wrappers in Functions.h that call into the actual operators
  568. # defined here, i.e. at::_ops::is_complex::call() and at::_ops::add_out::call().
  569. # This means that ATEN_OP(is_complex) will not fastpath, and will go through the dispatcher.
  570. return f"""
  571. struct TORCH_API {name} {{
  572. using schema = {sig.type()};
  573. using ptr_schema = schema*;
  574. // See Note [static constexpr char* members for windows NVCC]
  575. static constexpr const char* name = "aten::{f.func.name.name}";
  576. static constexpr const char* overload_name = "{f.func.name.overload_name}";
  577. static constexpr const char* schema_str = {cpp_string(str(f.func))};
  578. static {sig.defn(name="call", is_redispatching_fn=False)};
  579. static {sig.defn(name="redispatch", is_redispatching_fn=True)};
  580. }};"""
  581. elif self.target is Target.DEFINITION:
  582. defns = f"""
  583. // aten::{f.func}
  584. static C10_NOINLINE c10::TypedOperatorHandle<{name}::schema> create_{name}_typed_handle() {{
  585. return c10::Dispatcher::singleton()
  586. .findSchemaOrThrow({name}::name, {name}::overload_name)
  587. .typed<{name}::schema>();
  588. }}
  589. """
  590. for is_redispatching_fn in [False, True]:
  591. if is_redispatching_fn:
  592. dispatcher_exprs_str = ", ".join(
  593. ["dispatchKeySet"] + [a.name for a in sig.arguments()]
  594. )
  595. method_base = "redispatch"
  596. else:
  597. dispatcher_exprs_str = ", ".join([a.name for a in sig.arguments()])
  598. method_base = "call"
  599. dispatcher_call = method_base
  600. method_name = f"{name}::{method_base}"
  601. fn_body = f"""
  602. static auto op = create_{name}_typed_handle();
  603. return op.{dispatcher_call}({dispatcher_exprs_str});"""
  604. if (
  605. not is_redispatching_fn
  606. and len(self.static_dispatch_backend_indices) > 0
  607. ):
  608. # call() should go through static dispatch
  609. fn_body = static_dispatch(
  610. sig, f, backend_indices=self.static_dispatch_backend_indices
  611. )
  612. defns += f"""
  613. // aten::{f.func}
  614. {sig.defn(name=method_name, is_redispatching_fn=is_redispatching_fn)} {{
  615. {fn_body}
  616. }}
  617. """
  618. return defns
  619. else:
  620. assert_never(self.target)
  621. # Generates Functions.h, which provides the functional public C++ API,
  622. # and the scaffolding to call into the dispatcher from these functions.
  623. @dataclass(frozen=True)
  624. class ComputeFunction:
  625. @method_with_native_function
  626. def __call__(self, f: NativeFunction) -> str | None:
  627. sig_group = CppSignatureGroup.from_native_function(
  628. f, method=False, fallback_binding=f.manual_cpp_binding
  629. )
  630. has_symint = f.func.has_symint()
  631. result = ""
  632. for sig in sig_group.signatures():
  633. # See Note [The ATen Operators API]
  634. target_sig = DispatcherSignature.from_schema(f.func)
  635. exprs = translate(sig.arguments(), target_sig.arguments())
  636. exprs_str = ", ".join([e.expr for e in exprs])
  637. if sig.symint:
  638. intlike_t = "c10::SymInt"
  639. else:
  640. intlike_t = "int64_t"
  641. if Variant.function in f.variants:
  642. result += f"""
  643. // aten::{f.func}
  644. inline {sig.decl()} {{
  645. return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str});
  646. }}"""
  647. # The template function can be used from template situations
  648. # where you want to switch between the symint or not version
  649. # depending on a template argument
  650. #
  651. # NB: we ALWAYS generate this even for methods. But we put it in
  652. # this header so it can take advantage of per-op headers
  653. if has_symint:
  654. result += f"""
  655. namespace symint {{
  656. template <typename T, typename = std::enable_if_t<std::is_same_v<T, {intlike_t}>>>
  657. {sig.decl(suppress_symint_suffix=True)} {{
  658. return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str});
  659. }}
  660. }}
  661. """
  662. return result
  663. # Generates TensorBody.h. This file provides the object-oriented (method-based)
  664. # public C++ API, and the scaffolding to call into the dispatcher from these functions.
  665. @dataclass(frozen=True)
  666. class ComputeTensorMethod:
  667. target: Literal[Target.DECLARATION, Target.DEFINITION]
  668. static_dispatch_backend_indices: list[BackendIndex]
  669. @method_with_native_function
  670. def __call__(self, f: NativeFunction) -> str | None:
  671. if Variant.method not in f.variants:
  672. return None
  673. assert not f.func.is_out_fn()
  674. assert f.func.arguments.self_arg is not None
  675. sig_group = CppSignatureGroup.from_native_function(
  676. f, method=True, fallback_binding=f.manual_cpp_binding
  677. )
  678. if self.target is Target.DECLARATION:
  679. result = ""
  680. for sig in sig_group.signatures():
  681. result += f"{sig.decl()} const;\n"
  682. return result
  683. if self.target is not Target.DEFINITION:
  684. assert_never(self.target)
  685. result = ""
  686. for sig in sig_group.signatures():
  687. target_sig = DispatcherSignature.from_schema(f.func)
  688. exprs = translate(sig.arguments(), target_sig.arguments(), method=True)
  689. exprs_str = ", ".join([e.expr for e in exprs])
  690. result += f"""
  691. // aten::{f.func}
  692. inline {sig.defn(prefix="Tensor::")} const {{
  693. return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str});
  694. }}
  695. """
  696. return result
  697. # Generates RedispatchFunctions.h.
  698. # This is similar to the C++ API defined in Functions.h, but provides access
  699. # to the dispatcher's redispatch API.
  700. @dataclass(frozen=True)
  701. class ComputeRedispatchFunction:
  702. @method_with_native_function
  703. def __call__(self, f: NativeFunction) -> str | None:
  704. # We unconditionally generate function variants of the redispatch API.
  705. # This is mainly because we can namespace functions separately, but not methods,
  706. sig_group = CppSignatureGroup.from_native_function(
  707. f, method=False, fallback_binding=f.manual_cpp_binding
  708. )
  709. result = ""
  710. for sig in sig_group.signatures():
  711. target_sig = DispatcherSignature.from_schema(f.func)
  712. exprs = translate(sig.arguments(), target_sig.arguments())
  713. exprs_str = ", ".join(["dispatchKeySet"] + [a.expr for a in exprs])
  714. result += f"""
  715. // aten::{f.func}
  716. inline {sig.decl(is_redispatching_fn=True)} {{
  717. return at::_ops::{f.func.name.unambiguous_name()}::redispatch({exprs_str});
  718. }}
  719. """
  720. return result
  721. # Generates ATenOpList.cpp, a runtime accessible list of all aten
  722. # operators.
  723. # TODO: This was historically used to help some JIT interop code
  724. # figure out whether or not to treat aten namespace'd operators
  725. # one way or another, we should reevaluate if this is actually needed.
  726. @with_native_function
  727. def compute_aten_op(f: NativeFunction) -> str:
  728. return f'{{"aten::{f.func.name.name}", "{f.func.name.overload_name}"}},'
  729. # Generates MetaFunctions.h
  730. def compute_meta_function_declaration(g: NativeFunctionsGroup) -> str | None:
  731. if not g.structured:
  732. return None
  733. with native_function_manager(g.out):
  734. name = meta.name(g)
  735. args = structured.meta_arguments(g)
  736. args_str = ", ".join(a.decl() for a in args)
  737. parent_class = g.out.structured_inherits
  738. if parent_class is None:
  739. parent_class = "at::impl::MetaBase"
  740. meta_return = "void"
  741. precomputed = g.out.precomputed if g.structured else None
  742. if precomputed:
  743. # Generate the template declaration with one bool parameter for each
  744. # precomputed element. Each parameter is true if the corresponding (in
  745. # terms of position) precomputed element has been set.
  746. precomputed_values = [*precomputed.replace.values(), precomputed.add]
  747. precomputed_elements = [
  748. elem for replace_list in precomputed_values for elem in replace_list
  749. ]
  750. precomputed_template_parameters = [
  751. elem.name.upper() for elem in precomputed_elements
  752. ]
  753. precomputed_template_params_str = ", ".join(
  754. f"bool {param} = false" for param in precomputed_template_parameters
  755. )
  756. precompute_template_decl = f"template <{precomputed_template_params_str}>"
  757. # Generate a string containing declarations of all precomputed elements.
  758. precomputed_elements_with_cpp_types = [
  759. structured.argument_type(elem, binds=elem.name)
  760. for elem in precomputed_elements
  761. ]
  762. precomputed_elements_decl = ";\n".join(
  763. f"{elem.cpp_type(strip_ref=True)} {elem.name}"
  764. for elem in precomputed_elements_with_cpp_types
  765. )
  766. # Generate "setter" methods for each precomputed element. Each method will return
  767. # a new instance of precompute_out with the template parameter that corresponds to
  768. # the member set by the method to true (to indicate that it has been set).
  769. setter_methods = []
  770. for i, elem in enumerate(precomputed_elements):
  771. # Generate the signature. The return type will be the same
  772. # as the type of `this` but with the template parameter
  773. # corresponding to the element set by this method set to true.
  774. # The assert generated below will ensure that this template
  775. # parameter is false on the type of `this`.
  776. return_ty_templates = ", ".join(
  777. precomputed_template_parameters[:i]
  778. + ["true"]
  779. + precomputed_template_parameters[i + 1 :]
  780. )
  781. return_ty = f"precompute_out<{return_ty_templates}>"
  782. elem_cpp_ty = precomputed_elements_with_cpp_types[i].cpp_type(
  783. strip_ref=True
  784. )
  785. signature = f"{return_ty} set_{elem.name}({elem_cpp_ty} value)"
  786. # Generate an assert which checks that the
  787. # template parameter corresponding to the precomputed
  788. # element that is set by this method is false on the
  789. # class corresponding to the object that `this` points to.
  790. # This ensures that each element can be set only once.
  791. assert_msg = f'"{elem.name} already set"'
  792. assert_stmt = f"static_assert({precomputed_template_parameters[i]} == false, {assert_msg});"
  793. # Generate the new object construction block. All state
  794. # except the element that this method sets is copied from the
  795. # object that `this` points to. The value for the element that
  796. # the method sets is taken from a method parameter.
  797. construction_stmts = []
  798. construction_stmts.append(f"{return_ty} ret;")
  799. for j, elem in enumerate(precomputed_elements):
  800. if i == j:
  801. construction_stmts.append(f"ret.{elem.name} = value;")
  802. else:
  803. construction_stmts.append(
  804. f"ret.{elem.name} = this->{elem.name};"
  805. )
  806. construction_stmts.append("return ret;")
  807. construction_block = "\n".join(construction_stmts)
  808. setter_methods.append(
  809. f"""
  810. {signature} {{
  811. {assert_stmt}
  812. {construction_block}
  813. }}
  814. """
  815. )
  816. setter_methods_decl = "\n".join(setter_methods)
  817. # Meta should return an instance of the struct containing the precomputed elements.
  818. meta_return_template_params = ", ".join(
  819. ["true"] * len(precomputed_template_parameters)
  820. )
  821. # This typedef (actually a using statement) is needed so that TORCH_META_FUNC can reuse the return
  822. # type (which has a variable number of template parameters).
  823. meta_return_typedef = f"using meta_return_ty = precompute_out <{meta_return_template_params}>;"
  824. meta_return = "meta_return_ty"
  825. precomputed_decl = f"""
  826. {precompute_template_decl}
  827. struct TORCH_API precompute_out {{
  828. {setter_methods_decl}
  829. {precomputed_elements_decl};
  830. }};"""
  831. else:
  832. meta_return_typedef = ""
  833. precomputed_decl = ""
  834. return f"""\
  835. struct TORCH_API structured_{name} : public {parent_class} {{
  836. {precomputed_decl}
  837. {meta_return_typedef}
  838. {meta_return} meta({args_str});
  839. }};
  840. """
  841. def needs_backend_select(f: NativeFunction, selector: SelectiveBuilder) -> bool:
  842. name = str(f.func.name.name)
  843. if name.endswith("_like") or name.startswith("new_"):
  844. return False
  845. if f.func.arguments.tensor_options is None:
  846. return False
  847. return selector.is_native_function_selected(f)
  848. # Generates RegisterBackendSelect.cpp, a series of kernels which provide
  849. # specialized computation of dispatch key for operator signatures which cannot
  850. # be easily done automatically using templating.
  851. @dataclass(frozen=True)
  852. class ComputeBackendSelect:
  853. target: Literal[Target.DEFINITION, Target.REGISTRATION]
  854. # Selector object to determine which operators to generate
  855. # registration code for.
  856. selector: SelectiveBuilder
  857. @method_with_native_function
  858. def __call__(self, f: NativeFunction) -> str | None:
  859. if not needs_backend_select(f, self.selector):
  860. return None
  861. name = native.name(f.func)
  862. # BackendSelect can go to Meta, so it must preserve symints
  863. native_sig = NativeSignature(f.func, symint=True)
  864. native_tensor_args = [
  865. a
  866. for a in native_sig.arguments()
  867. if isinstance(a.argument, Argument) and a.argument.type.is_tensor_like()
  868. ]
  869. dispatcher_sig = DispatcherSignature.from_schema(f.func)
  870. sig: NativeSignature | DispatcherSignature
  871. sig = dispatcher_sig
  872. dispatcher_exprs = dispatcher_sig.exprs()
  873. dispatch_key = "c10::computeDispatchKey(dtype, layout, device)"
  874. if self.target is Target.DEFINITION:
  875. # I don't think there's actually a good reason to generate
  876. # these two cases differently
  877. # The first case could probably be improved though- it calls computeDispatchKeySet(),
  878. # which looks at TLS dispatch keys- there should not be any by the time we reach backend select.
  879. if native_tensor_args:
  880. assert f.func.arguments.has_tensor_arg()
  881. tensor_args = ", ".join(a.name for a in native_tensor_args)
  882. compute_dk = f"""\
  883. DispatchKeySet _dk_set = c10::DispatchKeySet({dispatch_key}) | c10::detail::multi_dispatch_key_set({tensor_args});
  884. DispatchKeySet _dk_mask = c10::DispatchKeySet(DispatchKeySet::FULL_AFTER, DispatchKey::BackendSelect);
  885. DispatchKeySet _dk = c10::impl::computeDispatchKeySet(_dk_set, _dk_mask);"""
  886. else:
  887. assert not f.func.arguments.has_tensor_arg()
  888. compute_dk = (
  889. f"DispatchKeySet _dk = c10::DispatchKeySet({dispatch_key});"
  890. )
  891. return f"""\
  892. // aten::{f.func}
  893. C10_ALWAYS_INLINE
  894. {sig.defn(name)} {{
  895. {compute_dk}
  896. return at::_ops::{f.func.name.unambiguous_name()}::redispatch(
  897. _dk, {", ".join(a.expr for a in dispatcher_exprs)});
  898. }}
  899. """
  900. elif self.target is Target.REGISTRATION:
  901. return f"""m.impl("aten::{f.func.name}", TORCH_FN({name}));"""
  902. else:
  903. assert_never(self.target)
  904. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
  905. #
  906. # YAML CODE GENERATION
  907. #
  908. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
  909. def format_yaml(data: object) -> str:
  910. # Ignore alias in Dumper
  911. YamlDumper.ignore_aliases = lambda self, data: True # type: ignore[assignment]
  912. # Support serializing OrderedDict
  913. def dict_representer(dumper: Any, data: Any) -> Any:
  914. return dumper.represent_dict(data.items())
  915. YamlDumper.add_representer(OrderedDict, dict_representer) # type: ignore[no-untyped-call]
  916. # Some yaml parsers (e.g. Haskell's) don't understand line breaks.
  917. # width=1e9 turns off optional line breaks and improves
  918. # the portability of the outputted yaml.
  919. return yaml.dump(data, default_flow_style=False, Dumper=YamlDumper, width=1e9) # type: ignore[no-any-return, call-overload]
  920. # For some reason, some defaults we write to YAML are written as native
  921. # YAML objects, rather than doing them uniformly as strings. This
  922. # function detects those cases and converts them into native Python
  923. # objects.
  924. def pythonify_default(s: str) -> object:
  925. if s == "true":
  926. return True
  927. elif s == "false":
  928. return False
  929. try:
  930. return int(s)
  931. except ValueError:
  932. try:
  933. return float(s)
  934. except ValueError:
  935. return s
  936. # What is a dynamic type? Over time, the semantic meaning of
  937. # dynamic type has degraded to meaninglessness (in the old days,
  938. # it captured dtype-ness of types, but that has gone away with
  939. # the removal of TH). These days, it's mostly the same thing as
  940. # the C++ API argument type, except that Tensor and Tensor?
  941. # arguments simply present as Tensor.
  942. #
  943. # TODO: Get rid of dynamic_type, after getting tools/autograd
  944. # to use the new codegen framework
  945. def dynamic_type(t: Type) -> str:
  946. if isinstance(t, OptionalType):
  947. return dynamic_type(t.elem)
  948. # Note we don't use t.is_tensor_like() here because it would
  949. # also include Tensor[]
  950. if str(t) == "Tensor":
  951. return "at::Tensor"
  952. # This is a legacy concept, so never report SymInt
  953. return cpp.argumenttype_type(
  954. t, mutable=False, binds="__placeholder__", symint=False
  955. ).cpp_type()
  956. def compute_method_of_yaml(variants: set[Variant]) -> list[str]:
  957. # This is written out explicitly to ensure that Tensor and
  958. # namespace are put into the list in the right order
  959. method_of = ["Type"]
  960. if Variant.method in variants:
  961. method_of.append("Tensor")
  962. if Variant.function in variants:
  963. method_of.append("namespace")
  964. return method_of
  965. def compute_returns_yaml(
  966. f: NativeFunction,
  967. ) -> tuple[list[dict[str, str]], dict[str, str]]:
  968. # Note [name and field_name]
  969. # ~~~~~~~~~~~~~~~~~~~~~~~~~~
  970. # To understand name_to_field_name, we must first talk about this
  971. # schema:
  972. #
  973. # lstsq.X(Tensor self, Tensor A, *, Tensor(a!) X, Tensor(b!) qr) -> (Tensor(a!) solution, Tensor(b!) QR)
  974. #
  975. # There is something very odd about this schema: it is an out
  976. # variant of the function (that is to say, it will convert into
  977. # at::lstsq_out() in the C++ API), but the names of the output
  978. # return arguments don't match the keyword argument names of
  979. # the inputs. It TURNS OUT that in this situation, the historical
  980. # Declarations.yaml we want to output is this (abbreviated to
  981. # only show relevant fields):
  982. #
  983. # arguments:
  984. # ...
  985. # - field_name: solution
  986. # name: X
  987. # - field_name: QR
  988. # name: qr
  989. # ...
  990. #
  991. # returns:
  992. # - field_name: solution
  993. # name: X
  994. # - field_name: QR
  995. # name: qr
  996. #
  997. # The name of the return fields is stored in 'field_name', and the
  998. # name of the arguments is stored in 'name'. So when we process
  999. # arguments, we need a way to get at the corresponding return. At
  1000. # the moment, this is most conveniently done by constructing a
  1001. # mapping from name (the argument concept) to field_name (the
  1002. # return concept) while processing return arguments, since we don't
  1003. # directly maintain this correspondence in the modeling of function
  1004. # schema itself.
  1005. #
  1006. # See also https://github.com/pytorch/pytorch/issues/43114
  1007. name_to_field_name: dict[str, str] = {}
  1008. # Compute the returns field of the YAML entry
  1009. names = cpp.return_names(f)
  1010. returns = []
  1011. for i, (r, name) in enumerate(zip(f.func.returns, names)):
  1012. ret = {
  1013. "dynamic_type": dynamic_type(r.type),
  1014. "name": name,
  1015. # legacy, report ints
  1016. "type": cpp.return_type(r, symint=False).cpp_type(),
  1017. }
  1018. if r.name:
  1019. # See Note [name and field_name]
  1020. ret["field_name"] = r.name
  1021. if f.func.is_out_fn():
  1022. name_to_field_name[f.func.arguments.out[i].name] = r.name
  1023. returns.append(ret)
  1024. return returns, name_to_field_name
  1025. # arguments in yaml roughly corresponds to the public C++ API
  1026. def compute_cpp_argument_yaml(
  1027. cpp_a: Binding,
  1028. *,
  1029. schema_order: bool,
  1030. kwarg_only_set: set[str],
  1031. out_arg_set: set[str],
  1032. name_to_field_name: dict[str, str],
  1033. ) -> object:
  1034. if isinstance(cpp_a.argument, TensorOptionsArguments):
  1035. arg: dict[str, object] = {
  1036. "annotation": None,
  1037. "dynamic_type": "at::TensorOptions",
  1038. "is_nullable": False,
  1039. "name": cpp_a.name,
  1040. "type": cpp_a.type,
  1041. "kwarg_only": True,
  1042. }
  1043. if cpp_a.default is not None:
  1044. arg["default"] = cpp_a.default
  1045. return arg
  1046. elif isinstance(cpp_a.argument, SelfArgument):
  1047. raise AssertionError
  1048. elif isinstance(cpp_a.argument, Argument):
  1049. return compute_argument_yaml(
  1050. cpp_a.argument,
  1051. schema_order=schema_order,
  1052. kwarg_only_set=kwarg_only_set,
  1053. out_arg_set=out_arg_set,
  1054. name_to_field_name=name_to_field_name,
  1055. )
  1056. def compute_argument_yaml(
  1057. a: Argument,
  1058. *,
  1059. schema_order: bool,
  1060. kwarg_only_set: set[str],
  1061. out_arg_set: set[str],
  1062. name_to_field_name: dict[str, str],
  1063. ) -> object:
  1064. arg: dict[str, object] = {
  1065. "annotation": str(a.annotation) if a.annotation else None,
  1066. "dynamic_type": dynamic_type(a.type),
  1067. "is_nullable": a.type.is_nullable(),
  1068. "name": a.name,
  1069. # legacy, report ints
  1070. "type": cpp.argument_type(a, binds="__placeholder__", symint=False).cpp_type(),
  1071. }
  1072. if a.default is not None:
  1073. arg["default"] = pythonify_default(
  1074. cpp.default_expr(a.default, a.type, symint=False)
  1075. )
  1076. if a.name in kwarg_only_set:
  1077. arg["kwarg_only"] = True
  1078. if a.name in out_arg_set:
  1079. arg["output"] = True
  1080. arg["allocate"] = True
  1081. # See Note [name and field_name]
  1082. if a.name in name_to_field_name:
  1083. arg["field_name"] = name_to_field_name[a.name]
  1084. # Historically, booleans don't get their size recorded, because it
  1085. # is already built into the cpp type (e.g., std::array<bool, 4>)
  1086. l = a.type.is_list_like()
  1087. if l is not None and l.size is not None and str(l.elem) != "bool":
  1088. arg["size"] = l.size
  1089. return arg
  1090. @with_native_function
  1091. def compute_declaration_yaml(f: NativeFunction) -> object:
  1092. returns, name_to_field_name = compute_returns_yaml(f)
  1093. # These sets are used to conveniently test if an argument is a
  1094. # kwarg-only or out argument
  1095. kwarg_only_set = {a.name for a in f.func.arguments.flat_kwarg_only}
  1096. out_arg_set = {a.name for a in f.func.arguments.out}
  1097. sig_group = CppSignatureGroup.from_native_function(
  1098. f, method=False, fallback_binding=False
  1099. )
  1100. cpp_args = sig_group.signature.arguments()
  1101. arguments = [
  1102. compute_cpp_argument_yaml(
  1103. cpp_a,
  1104. schema_order=False,
  1105. kwarg_only_set=kwarg_only_set,
  1106. out_arg_set=out_arg_set,
  1107. name_to_field_name=name_to_field_name,
  1108. )
  1109. for cpp_a in cpp_args
  1110. ]
  1111. schema_order_jit_arguments = list(f.func.schema_order_arguments())
  1112. schema_order_arguments = [
  1113. compute_argument_yaml(
  1114. a,
  1115. schema_order=True,
  1116. kwarg_only_set=kwarg_only_set,
  1117. out_arg_set=out_arg_set,
  1118. name_to_field_name=name_to_field_name,
  1119. )
  1120. for a in schema_order_jit_arguments
  1121. ]
  1122. cpp_schema_order_types = [
  1123. # NB: method here doesn't matter
  1124. r.type
  1125. for a in schema_order_jit_arguments
  1126. for r in cpp.argument(
  1127. a,
  1128. method=False,
  1129. cpp_no_default_args=set(),
  1130. faithful=False,
  1131. symint=False,
  1132. has_tensor_options=False,
  1133. )
  1134. ]
  1135. # legacy, report ints
  1136. cpp_returns = cpp.returns_type(f.func.returns, symint=False).cpp_type()
  1137. schema_order_cpp_signature = f"{cpp_returns} ({', '.join(cpp_schema_order_types)})"
  1138. is_factory_method = (
  1139. any(isinstance(a.argument, TensorOptionsArguments) for a in cpp_args)
  1140. and Variant.method not in f.variants
  1141. )
  1142. return OrderedDict(
  1143. [
  1144. ("name", cpp.name(f.func)),
  1145. ("operator_name", str(f.func.name.name)),
  1146. ("overload_name", str(f.func.name.overload_name)),
  1147. ("manual_kernel_registration", f.manual_kernel_registration),
  1148. (
  1149. "category_override",
  1150. f.category_override if f.category_override is not None else "",
  1151. ),
  1152. ("schema_string", f"aten::{f.func}"),
  1153. ("arguments", arguments),
  1154. ("schema_order_cpp_signature", schema_order_cpp_signature),
  1155. ("schema_order_arguments", schema_order_arguments),
  1156. ("method_of", compute_method_of_yaml(f.variants)),
  1157. ("mode", "native"),
  1158. ("python_module", "" if f.python_module is None else f.python_module),
  1159. ("returns", returns),
  1160. ("inplace", f.func.name.name.inplace),
  1161. ("is_factory_method", is_factory_method),
  1162. ("abstract", f.is_abstract),
  1163. ("device_guard", f.device_guard),
  1164. ("with_gil", False),
  1165. ("deprecated", False),
  1166. ("has_math_kernel", f.has_composite_implicit_autograd_kernel),
  1167. ]
  1168. )
  1169. # See Note [Auto generated composite kernels]
  1170. def has_autogenerated_composite_kernel(f: NativeFunction) -> bool:
  1171. return (f.structured or f.structured_delegate is not None) and (
  1172. f.func.kind() == SchemaKind.functional or f.func.kind() == SchemaKind.inplace
  1173. )
  1174. @with_native_function_and_indices
  1175. def compute_registration_declarations(
  1176. f: NativeFunction, backend_indices: dict[DispatchKey, BackendIndex]
  1177. ) -> str:
  1178. name = dispatcher.name(f.func)
  1179. returns_type = dispatcher.returns_type(f.func.returns).cpp_type()
  1180. args = dispatcher.arguments(f.func)
  1181. args_str = ", ".join(a.no_default().decl() for a in args)
  1182. comment_data: dict[str, str] = {
  1183. "schema": f"aten::{f.func}",
  1184. # TODO: What exactly is the semantics of the 'dispatch' field?
  1185. "dispatch": str(
  1186. {k for k, v in backend_indices.items() if v.has_kernel(f)}
  1187. != {DispatchKey.CompositeImplicitAutograd}
  1188. and {k for k, v in backend_indices.items() if v.has_kernel(f)}
  1189. != {
  1190. DispatchKey.CompositeImplicitAutograd,
  1191. DispatchKey.CompositeImplicitAutogradNestedTensor,
  1192. }
  1193. ),
  1194. "default": str(f.has_composite_kernel or has_autogenerated_composite_kernel(f)),
  1195. }
  1196. return f"""{returns_type} {name}({args_str}); // {json.dumps(comment_data)}
  1197. """
  1198. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
  1199. #
  1200. # RUN IT ALL
  1201. #
  1202. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
  1203. def get_custom_build_selector(
  1204. provided_op_registration_allowlist: list[str] | None,
  1205. op_selection_yaml_path: str | None,
  1206. ) -> SelectiveBuilder:
  1207. assert not (
  1208. provided_op_registration_allowlist is not None
  1209. and op_selection_yaml_path is not None
  1210. ), (
  1211. "Both provided_op_registration_allowlist and "
  1212. + "op_selection_yaml_path can NOT be provided at the "
  1213. + "same time."
  1214. )
  1215. op_registration_allowlist: set[str] | None = None
  1216. if provided_op_registration_allowlist is not None:
  1217. op_registration_allowlist = set(provided_op_registration_allowlist)
  1218. if op_registration_allowlist is not None:
  1219. selector = SelectiveBuilder.from_legacy_op_registration_allow_list(
  1220. op_registration_allowlist,
  1221. True,
  1222. False,
  1223. )
  1224. elif op_selection_yaml_path is not None:
  1225. selector = SelectiveBuilder.from_yaml_path(op_selection_yaml_path)
  1226. else:
  1227. selector = SelectiveBuilder.get_nop_selector()
  1228. return selector
  1229. def get_grouped_by_view_native_functions(
  1230. native_functions: Sequence[NativeFunction],
  1231. ) -> Sequence[NativeFunction | NativeFunctionsViewGroup]:
  1232. def maybe_create_view_group(
  1233. d: dict[ViewSchemaKind | SchemaKind, NativeFunction],
  1234. ) -> list[NativeFunction | NativeFunctionsViewGroup]:
  1235. funcs: list[NativeFunction | NativeFunctionsViewGroup] = []
  1236. if ViewSchemaKind.aliasing in d:
  1237. view = d.pop(ViewSchemaKind.aliasing)
  1238. view_inplace = d.pop(ViewSchemaKind.aliasing_inplace, None)
  1239. view_copy = d.pop(SchemaKind.functional, None)
  1240. funcs.append(
  1241. NativeFunctionsViewGroup(
  1242. view=view,
  1243. view_copy=view_copy,
  1244. view_inplace=view_inplace,
  1245. )
  1246. )
  1247. # Take the remaining functions that weren't part of the view group
  1248. # and emit them separately
  1249. funcs.extend(d.values())
  1250. return funcs
  1251. grouped_by_views: dict[
  1252. FunctionSchema, dict[SchemaKind | ViewSchemaKind, NativeFunction]
  1253. ] = defaultdict(dict)
  1254. for f in native_functions:
  1255. schema = f.func.view_signature()
  1256. view_kind: ViewSchemaKind = f.view_schema_kind
  1257. # We need to group up ops relevant to the same "view", consisting of:
  1258. # view op (ViewSchemaKind.aliasing)
  1259. # view_inplace op (ViewSchemaKind.aliasing_inplace)
  1260. # view_copy op (SchemaKind.functional)
  1261. if view_kind == ViewSchemaKind.non_aliasing:
  1262. kind = f.func.kind()
  1263. assert kind not in grouped_by_views[schema]
  1264. grouped_by_views[schema][kind] = f
  1265. else:
  1266. assert view_kind not in grouped_by_views[schema], (
  1267. f"{view_kind} already in {grouped_by_views[schema].keys()}"
  1268. )
  1269. grouped_by_views[schema][view_kind] = f
  1270. return list(concatMap(maybe_create_view_group, grouped_by_views.values()))
  1271. def get_grouped_native_functions(
  1272. native_functions: Sequence[NativeFunction],
  1273. ) -> Sequence[NativeFunction | NativeFunctionsGroup]:
  1274. def flatten_pre_group(
  1275. d: dict[SchemaKind, NativeFunction],
  1276. ) -> Sequence[NativeFunction | NativeFunctionsGroup]:
  1277. r = NativeFunctionsGroup.from_dict(d)
  1278. if r is None:
  1279. # Invariant: any NativeFunctions that are code-generated
  1280. # should have been grouped into NativeFunctionsGroup objects
  1281. assert not any("generated" in f.tags for f in d.values())
  1282. return list(d.values())
  1283. else:
  1284. return [r]
  1285. # TODO: how come ValuesView isn't a Sequence lol
  1286. pre_grouped_native_functions = pre_group_native_functions(native_functions)
  1287. return list(
  1288. concatMap(flatten_pre_group, list(pre_grouped_native_functions.values()))
  1289. )
  1290. def get_ns_grouped_kernels(
  1291. *,
  1292. grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
  1293. backend_indices: dict[DispatchKey, BackendIndex],
  1294. native_function_decl_gen: Callable[
  1295. [NativeFunctionsGroup | NativeFunction, BackendIndex], list[str]
  1296. ] = dest.compute_native_function_declaration,
  1297. ) -> dict[str, list[str]]:
  1298. ns_grouped_kernels: dict[str, list[str]] = defaultdict(list)
  1299. for f in grouped_native_functions:
  1300. native_function_namespaces = set()
  1301. dispatch_keys = set()
  1302. for dispatch_key, backend_idx in backend_indices.items():
  1303. backend_metadata = backend_idx.get_kernel(f)
  1304. if backend_metadata:
  1305. namespace = backend_metadata.cpp_namespace
  1306. dispatch_keys.add(dispatch_key)
  1307. native_function_namespaces.add(namespace)
  1308. else:
  1309. namespace = DEFAULT_KERNEL_NAMESPACE
  1310. assert len(native_function_namespaces) <= 1, (
  1311. f"Codegen only supports one namespace per operator, got {native_function_namespaces} from {dispatch_keys}"
  1312. )
  1313. ns_grouped_kernels[namespace].extend(
  1314. native_function_decl_gen(f, backend_idx)
  1315. )
  1316. return ns_grouped_kernels
  1317. def get_native_function_declarations_from_ns_grouped_kernels(
  1318. *,
  1319. ns_grouped_kernels: dict[str, list[str]],
  1320. ) -> list[str]:
  1321. declarations: list[str] = []
  1322. newline = "\n"
  1323. for namespace, kernels in ns_grouped_kernels.items():
  1324. ns_helper = NamespaceHelper(
  1325. namespace_str=namespace,
  1326. entity_name="",
  1327. max_level=4,
  1328. )
  1329. # Convert to a set first to remove duplicate kernel names. Backends are
  1330. # allowed to repeat kernel names; only generate the declaration once!
  1331. ordered_kernels = list(OrderedDict.fromkeys(kernels))
  1332. declarations.extend(
  1333. f"""
  1334. {ns_helper.prologue}
  1335. {newline.join(ordered_kernels)}
  1336. {ns_helper.epilogue}
  1337. """.split(newline)
  1338. )
  1339. return declarations
  1340. # Return native function declarations grouped by their namespaces.
  1341. def get_native_function_declarations(
  1342. *,
  1343. grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
  1344. backend_indices: dict[DispatchKey, BackendIndex],
  1345. native_function_decl_gen: Callable[
  1346. [NativeFunctionsGroup | NativeFunction, BackendIndex], list[str]
  1347. ] = dest.compute_native_function_declaration,
  1348. ) -> list[str]:
  1349. """
  1350. Generate kernel declarations, in `NativeFunction(s).h`.
  1351. :param grouped_native_functions: a sequence of `NativeFunction` or `NativeFunctionGroup`.
  1352. :param backend_indices: kernel collections grouped by dispatch key.
  1353. :param native_function_decl_gen: callable to generate kernel declaration for each `NativeFunction`.
  1354. :return: a list of string, from the string with all declarations, grouped by namespaces, split by newline.
  1355. """
  1356. ns_grouped_kernels = get_ns_grouped_kernels(
  1357. grouped_native_functions=grouped_native_functions,
  1358. backend_indices=backend_indices,
  1359. native_function_decl_gen=native_function_decl_gen,
  1360. )
  1361. return get_native_function_declarations_from_ns_grouped_kernels(
  1362. ns_grouped_kernels=ns_grouped_kernels
  1363. )
  1364. def get_kernel_namespace(
  1365. *, f: NativeFunction | NativeFunctionsGroup, backend_idx: BackendIndex
  1366. ) -> str:
  1367. backend_metadata = backend_idx.get_kernel(f)
  1368. assert not backend_metadata or "::native" in backend_metadata.cpp_namespace, (
  1369. f"The kernel for function {f.func.name if isinstance(f, NativeFunction) else f.functional.func.name} "
  1370. f"with dispatch key {backend_idx.dispatch_key}"
  1371. f" has a namespace {backend_metadata.cpp_namespace} and it's not ending with '::native'."
  1372. )
  1373. return (
  1374. backend_metadata.cpp_namespace if backend_metadata else DEFAULT_KERNEL_NAMESPACE
  1375. )
  1376. # Return native function definitions grouped by dispatch key and custom namespace.
  1377. # Used in RegisterDispatchKey.cpp and etc.
  1378. def get_native_function_definitions(
  1379. *,
  1380. fm: FileManager,
  1381. grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
  1382. dispatch_key: DispatchKey,
  1383. backend_idx: BackendIndex,
  1384. selector: SelectiveBuilder,
  1385. rocm: bool,
  1386. symint: bool,
  1387. skip_dispatcher_op_registration: bool,
  1388. gen_dispatch_helpers: bool,
  1389. ) -> list[str]:
  1390. definitions: list[str] = []
  1391. ns_definitions: dict[str, list[str]] = defaultdict(list)
  1392. anonymous_definitions: dict[str, list[str]] = defaultdict(list)
  1393. registrations: dict[str, dict[str, list[str]]] = defaultdict(dict)
  1394. newline = "\n"
  1395. ns_gen = dest.RegisterDispatchKey(
  1396. backend_idx,
  1397. Target.NAMESPACED_DEFINITION,
  1398. selector,
  1399. rocm=rocm,
  1400. symint=symint,
  1401. class_method_name=None,
  1402. skip_dispatcher_op_registration=skip_dispatcher_op_registration,
  1403. )
  1404. anonymous_gen = dest.RegisterDispatchKey(
  1405. backend_idx,
  1406. Target.ANONYMOUS_DEFINITION,
  1407. selector,
  1408. rocm=rocm,
  1409. symint=symint,
  1410. class_method_name=None,
  1411. skip_dispatcher_op_registration=skip_dispatcher_op_registration,
  1412. )
  1413. reg_gen = dest.RegisterDispatchKey(
  1414. backend_idx,
  1415. Target.REGISTRATION,
  1416. selector,
  1417. rocm=rocm,
  1418. symint=symint,
  1419. class_method_name=None,
  1420. skip_dispatcher_op_registration=skip_dispatcher_op_registration,
  1421. )
  1422. for f in grouped_native_functions:
  1423. kernel_namespace = get_kernel_namespace(f=f, backend_idx=backend_idx).replace(
  1424. "::native", ""
  1425. )
  1426. ns_definitions[kernel_namespace].extend(
  1427. ns_gen(f),
  1428. )
  1429. anonymous_definitions[kernel_namespace].extend(
  1430. anonymous_gen(f),
  1431. )
  1432. namespace = (
  1433. f.namespace if isinstance(f, NativeFunction) else f.functional.namespace
  1434. )
  1435. if namespace not in registrations[kernel_namespace]:
  1436. registrations[kernel_namespace] = defaultdict(list)
  1437. registrations[kernel_namespace][namespace].extend(
  1438. reg_gen(f),
  1439. )
  1440. for kernel_namespace in ns_definitions:
  1441. if len(ns_definitions[kernel_namespace]) == 0:
  1442. continue
  1443. ns_helper = NamespaceHelper(namespace_str=kernel_namespace)
  1444. registration_body = ""
  1445. for namespace in registrations[kernel_namespace]:
  1446. if not registrations[kernel_namespace][namespace]:
  1447. continue
  1448. registration_body += f"""
  1449. TORCH_LIBRARY_IMPL({namespace}, {dispatch_key}, m) {{
  1450. {newline.join(registrations[kernel_namespace][namespace])}
  1451. }}"""
  1452. definitions.extend(
  1453. fm.substitute_with_template(
  1454. "RegisterDispatchDefinitions.ini",
  1455. lambda: {
  1456. "ns_prologue": ns_helper.prologue,
  1457. "ns_epilogue": ns_helper.epilogue,
  1458. "dispatch_anonymous_definitions": anonymous_definitions[
  1459. kernel_namespace
  1460. ],
  1461. "static_init_dispatch_registrations": ""
  1462. if skip_dispatcher_op_registration
  1463. else registration_body,
  1464. "deferred_dispatch_registrations": "",
  1465. "dispatch_namespace": dispatch_key.lower(),
  1466. "dispatch_namespaced_definitions": ns_definitions[kernel_namespace],
  1467. },
  1468. ).split(newline)
  1469. )
  1470. return definitions
  1471. # Return native function declarations grouped by dispatch key and custom namespace.
  1472. # Used in CPUFunctions_inl.h and etc.
  1473. def get_namespaced_declaration(
  1474. *,
  1475. grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
  1476. dispatch_key: DispatchKey,
  1477. backend_idx: BackendIndex,
  1478. selector: SelectiveBuilder,
  1479. rocm: bool,
  1480. symint: bool,
  1481. ) -> list[str]:
  1482. declarations: list[str] = []
  1483. ns_grouped_kernels: dict[str, list[str]] = defaultdict(list)
  1484. newline = "\n"
  1485. func = dest.RegisterDispatchKey(
  1486. backend_idx,
  1487. Target.NAMESPACED_DECLARATION,
  1488. selector,
  1489. rocm=rocm,
  1490. class_method_name=None,
  1491. skip_dispatcher_op_registration=False,
  1492. symint=symint,
  1493. )
  1494. for f in grouped_native_functions:
  1495. namespace = get_kernel_namespace(f=f, backend_idx=backend_idx).replace(
  1496. "native", dispatch_key.lower()
  1497. )
  1498. ns_grouped_kernels[namespace].extend(
  1499. func(f),
  1500. )
  1501. for namespace, kernels in ns_grouped_kernels.items():
  1502. if len(kernels) == 0:
  1503. continue
  1504. ns_helper = NamespaceHelper(
  1505. namespace_str=namespace, entity_name="", max_level=3
  1506. )
  1507. ordered_kernels = list(OrderedDict.fromkeys(kernels))
  1508. declarations.extend(
  1509. f"""
  1510. {ns_helper.prologue}
  1511. {newline.join(ordered_kernels)}
  1512. {ns_helper.epilogue}
  1513. """.split(newline)
  1514. )
  1515. return declarations
  1516. # Return native function schema registration code for aten and other namespaces.
  1517. def get_native_function_schema_registrations(
  1518. *,
  1519. native_functions: Sequence[NativeFunction],
  1520. schema_selector: SelectiveBuilder,
  1521. ) -> tuple[list[str], str]:
  1522. ns_native_functions: dict[str, list[NativeFunction]] = defaultdict(list)
  1523. for native_function in native_functions:
  1524. ns_native_functions[native_function.namespace].append(native_function)
  1525. schema_registrations = ""
  1526. aten_schema_registrations = []
  1527. custom_namespace = None
  1528. for namespace, funcs in ns_native_functions.items():
  1529. schema_registrations_body = list(
  1530. mapMaybe(RegisterSchema(schema_selector), funcs)
  1531. )
  1532. # NB: we have to separate aten namespace registration from other namespaces,
  1533. # because in the template we hardcoded an operator for ATen already.
  1534. if namespace == "aten":
  1535. aten_schema_registrations = schema_registrations_body
  1536. else:
  1537. custom_namespace = namespace
  1538. tab = "\t"
  1539. # if the namespace is predefined, we should use define a library fragment
  1540. # instead of a new library
  1541. torch_library_macro = (
  1542. "TORCH_LIBRARY_FRAGMENT"
  1543. if namespace in FRAGMENT_NAMESPACES
  1544. else "TORCH_LIBRARY"
  1545. )
  1546. schema_registrations += f"""
  1547. {torch_library_macro}({custom_namespace}, m) {{
  1548. {tab.join(schema_registrations_body)}
  1549. }};"""
  1550. return (aten_schema_registrations, schema_registrations)
  1551. def gen_aggregated_headers(
  1552. *,
  1553. native_functions: Sequence[NativeFunction],
  1554. grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
  1555. structured_native_functions: Sequence[NativeFunctionsGroup],
  1556. static_dispatch_idx: list[BackendIndex],
  1557. selector: SelectiveBuilder,
  1558. backend_indices: dict[DispatchKey, BackendIndex],
  1559. cpu_fm: FileManager,
  1560. device_fms: dict[str, FileManager],
  1561. functions_keys: set[DispatchKey],
  1562. dispatch_keys: Sequence[DispatchKey],
  1563. rocm: bool,
  1564. ) -> None:
  1565. # Buck doesn't support dynamic output files, so we aggregate all operator
  1566. # headers into a single file
  1567. cpu_fm.write(
  1568. "NativeMetaFunctions.h",
  1569. lambda: {
  1570. "NativeMetaFunctions_includes": [],
  1571. "NativeMetaFunctions_declarations": list(
  1572. mapMaybe(compute_meta_function_declaration, structured_native_functions)
  1573. ),
  1574. },
  1575. )
  1576. method_native_functions = [
  1577. fn for fn in native_functions if Variant.method in fn.variants
  1578. ]
  1579. non_method_native_functions = [
  1580. fn for fn in native_functions if fn not in method_native_functions
  1581. ]
  1582. cpu_fm.write(
  1583. "MethodOperators.h",
  1584. lambda: {
  1585. "MethodOperators_includes": [],
  1586. "MethodOperators_declarations": list(
  1587. mapMaybe(
  1588. ComputeOperators(
  1589. Target.DECLARATION,
  1590. static_dispatch_backend_indices=static_dispatch_idx,
  1591. ),
  1592. method_native_functions,
  1593. )
  1594. ),
  1595. },
  1596. )
  1597. cpu_fm.write(
  1598. "Operators.h",
  1599. lambda: {
  1600. "Operators_includes": ["#include <ATen/MethodOperators.h>"],
  1601. "Operators_declarations": list(
  1602. mapMaybe(
  1603. ComputeOperators(
  1604. Target.DECLARATION,
  1605. static_dispatch_backend_indices=static_dispatch_idx,
  1606. ),
  1607. non_method_native_functions,
  1608. )
  1609. ),
  1610. },
  1611. )
  1612. cpu_fm.write(
  1613. "Functions.h",
  1614. lambda: {
  1615. "static_dispatch_extra_headers": static_dispatch_extra_headers(
  1616. static_dispatch_idx
  1617. ),
  1618. "Functions_includes": ["#include <ATen/Operators.h>"],
  1619. "Functions_declarations": list(
  1620. mapMaybe(
  1621. ComputeFunction(),
  1622. native_functions,
  1623. )
  1624. ),
  1625. },
  1626. )
  1627. declarations = get_native_function_declarations(
  1628. grouped_native_functions=grouped_native_functions,
  1629. backend_indices=backend_indices,
  1630. )
  1631. cpu_fm.write(
  1632. "NativeFunctions.h",
  1633. lambda: {
  1634. "NativeFunctions_includes": ["#include <ATen/NativeMetaFunctions.h>"],
  1635. "NativeFunctions_declarations": declarations,
  1636. },
  1637. )
  1638. for dispatch_key in dispatch_keys:
  1639. fm = file_manager_from_dispatch_key(dispatch_key, device_fms, cpu_fm)
  1640. if dispatch_key in functions_keys:
  1641. inl_headers = f"#include <ATen/{dispatch_key}Functions_inl.h>"
  1642. fm.write_with_template(
  1643. f"{dispatch_key}Functions.h",
  1644. "DispatchKeyFunctions.h",
  1645. lambda: {
  1646. "dispatch_key": str(dispatch_key),
  1647. "inline_headers": inl_headers,
  1648. },
  1649. )
  1650. fm.write_with_template(
  1651. f"{dispatch_key}Functions_inl.h",
  1652. "DispatchKeyFunctions_inl.h",
  1653. lambda: {
  1654. "DispatchKeyFunctions_inl_includes": [],
  1655. "dispatch_namespace": dispatch_key.lower(),
  1656. "dispatch_namespaced_declarations": get_namespaced_declaration(
  1657. grouped_native_functions=grouped_native_functions,
  1658. dispatch_key=dispatch_key,
  1659. backend_idx=backend_indices[dispatch_key],
  1660. selector=selector,
  1661. rocm=rocm,
  1662. symint=True,
  1663. ),
  1664. },
  1665. )
  1666. del fm
  1667. def gen_per_operator_headers(
  1668. *,
  1669. native_functions: Sequence[NativeFunction],
  1670. grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
  1671. static_dispatch_idx: list[BackendIndex],
  1672. selector: SelectiveBuilder,
  1673. backend_indices: dict[DispatchKey, BackendIndex],
  1674. cpu_fm: FileManager,
  1675. device_fms: dict[str, FileManager],
  1676. ops_fm: FileManager,
  1677. functions_keys: set[DispatchKey],
  1678. dispatch_keys: Sequence[DispatchKey],
  1679. rocm: bool,
  1680. ) -> None:
  1681. # For CMake builds, split operator declarations into separate headers in
  1682. # the ATen/ops folder to split up header dependencies
  1683. functions_by_root_name: dict[str, list[NativeFunction]] = defaultdict(list)
  1684. for fn in native_functions:
  1685. functions_by_root_name[fn.root_name].append(fn)
  1686. grouped_functions_by_root_name: dict[
  1687. str, list[NativeFunction | NativeFunctionsGroup]
  1688. ] = defaultdict(list)
  1689. for group in grouped_native_functions:
  1690. name = group.root_name
  1691. grouped_functions_by_root_name[name].append(group)
  1692. for name, functions in functions_by_root_name.items():
  1693. ops_fm.write_with_template(
  1694. f"{name}_ops.h",
  1695. "Operator.h",
  1696. lambda: {
  1697. "declarations": list(
  1698. mapMaybe(
  1699. ComputeOperators(
  1700. Target.DECLARATION,
  1701. static_dispatch_backend_indices=static_dispatch_idx,
  1702. ),
  1703. functions,
  1704. )
  1705. ),
  1706. },
  1707. )
  1708. ops_fm.write_with_template(
  1709. f"{name}.h",
  1710. "Function.h",
  1711. lambda: {
  1712. "static_dispatch_ops_headers": list(
  1713. mapMaybe(
  1714. lambda fn: static_dispatch_ops_header(
  1715. fn, backend_index=static_dispatch_idx
  1716. ),
  1717. functions,
  1718. )
  1719. ),
  1720. "operator_includes": f"#include <ATen/ops/{name}_ops.h>",
  1721. "function_definitions": list(
  1722. mapMaybe(
  1723. ComputeFunction(),
  1724. functions,
  1725. )
  1726. ),
  1727. },
  1728. )
  1729. grouped_functions = grouped_functions_by_root_name.get(name, [])
  1730. structured_functions = [
  1731. fn
  1732. for fn in grouped_functions
  1733. if isinstance(fn, NativeFunctionsGroup) and fn.structured
  1734. ]
  1735. is_structured = len(structured_functions) > 0
  1736. if is_structured:
  1737. ops_fm.write_with_template(
  1738. f"{name}_meta.h",
  1739. "NativeMetaFunction.h",
  1740. lambda: {
  1741. "meta_function_declarations": list(
  1742. mapMaybe(
  1743. compute_meta_function_declaration, structured_functions
  1744. )
  1745. ),
  1746. },
  1747. )
  1748. declarations = get_native_function_declarations(
  1749. grouped_native_functions=grouped_functions,
  1750. backend_indices=backend_indices,
  1751. native_function_decl_gen=dest.compute_native_function_declaration,
  1752. )
  1753. ops_fm.write_with_template(
  1754. f"{name}_native.h",
  1755. "NativeFunction.h",
  1756. lambda: {
  1757. "extra_includes": (
  1758. f"#include <ATen/ops/{name}_meta.h>" if is_structured else []
  1759. ),
  1760. "native_function_declarations": declarations,
  1761. },
  1762. )
  1763. for category, suffix in [
  1764. ("Functions", ""),
  1765. ("Operators", "_ops"),
  1766. ("NativeMetaFunctions", "_meta"),
  1767. ("NativeFunctions", "_native"),
  1768. ]:
  1769. cpu_fm.write(
  1770. f"{category}.h",
  1771. lambda: {
  1772. f"{category}_includes": [
  1773. f"#include <ATen/ops/{name}{suffix}.h>"
  1774. for name in sorted(functions_by_root_name.keys())
  1775. ],
  1776. f"{category}_declarations": [],
  1777. },
  1778. )
  1779. for dispatch_key in dispatch_keys:
  1780. if dispatch_key not in functions_keys:
  1781. continue
  1782. dispatch_namespace = dispatch_key.lower()
  1783. dispatch_names = []
  1784. for name, functions in functions_by_root_name.items():
  1785. grouped_functions = grouped_functions_by_root_name.get(name, [])
  1786. declarations = list(
  1787. concatMap(
  1788. dest.RegisterDispatchKey(
  1789. backend_indices[dispatch_key],
  1790. Target.NAMESPACED_DECLARATION,
  1791. selector,
  1792. rocm=rocm,
  1793. symint=True,
  1794. class_method_name=None,
  1795. skip_dispatcher_op_registration=False,
  1796. ),
  1797. grouped_functions,
  1798. )
  1799. )
  1800. if len(declarations) == 0:
  1801. continue
  1802. dispatch_names.append(name)
  1803. ops_fm.write_with_template(
  1804. f"{name}_{dispatch_namespace}_dispatch.h",
  1805. "DispatchKeyFunction.h",
  1806. lambda: {
  1807. "dispatch_namespace": dispatch_namespace,
  1808. "dispatch_namespaced_declarations": declarations,
  1809. },
  1810. )
  1811. fm = file_manager_from_dispatch_key(dispatch_key, device_fms, cpu_fm)
  1812. inl_headers = f"#include <ATen/{dispatch_key}Functions_inl.h>"
  1813. fm.write_with_template(
  1814. f"{dispatch_key}Functions.h",
  1815. "DispatchKeyFunctions.h",
  1816. lambda: {
  1817. "dispatch_key": str(dispatch_key),
  1818. "inline_headers": inl_headers,
  1819. },
  1820. )
  1821. fm.write_with_template(
  1822. f"{dispatch_key}Functions_inl.h",
  1823. "DispatchKeyFunctions_inl.h",
  1824. lambda: {
  1825. "dispatch_namespace": dispatch_namespace,
  1826. "DispatchKeyFunctions_inl_includes": [
  1827. f"#include <ATen/ops/{name}_{dispatch_namespace}_dispatch.h>"
  1828. for name in sorted(dispatch_names)
  1829. ],
  1830. "dispatch_namespaced_declarations": [],
  1831. },
  1832. )
  1833. del fm
  1834. cpu_fm.write(
  1835. "MethodOperators.h",
  1836. lambda: {
  1837. "MethodOperators_includes": sorted(
  1838. f"#include <ATen/ops/{name}_ops.h>"
  1839. for name, functions in functions_by_root_name.items()
  1840. if any(Variant.method in fn.variants for fn in functions)
  1841. ),
  1842. "MethodOperators_declarations": [],
  1843. },
  1844. )
  1845. def gen_headers(
  1846. *,
  1847. native_functions: Sequence[NativeFunction],
  1848. valid_tags: set[str],
  1849. grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
  1850. structured_native_functions: Sequence[NativeFunctionsGroup],
  1851. static_dispatch_idx: list[BackendIndex],
  1852. selector: SelectiveBuilder,
  1853. backend_indices: dict[DispatchKey, BackendIndex],
  1854. core_fm: FileManager,
  1855. cpu_fm: FileManager,
  1856. device_fms: dict[str, FileManager],
  1857. ops_fm: FileManager,
  1858. dispatch_keys: Sequence[DispatchKey],
  1859. functions_keys: set[DispatchKey],
  1860. rocm: bool,
  1861. per_operator_headers: bool,
  1862. ) -> None:
  1863. if per_operator_headers:
  1864. gen_per_operator_headers(
  1865. native_functions=native_functions,
  1866. grouped_native_functions=grouped_native_functions,
  1867. static_dispatch_idx=static_dispatch_idx,
  1868. selector=selector,
  1869. backend_indices=backend_indices,
  1870. cpu_fm=cpu_fm,
  1871. device_fms=device_fms,
  1872. ops_fm=ops_fm,
  1873. dispatch_keys=dispatch_keys,
  1874. functions_keys=functions_keys,
  1875. rocm=rocm,
  1876. )
  1877. else:
  1878. gen_aggregated_headers(
  1879. native_functions=native_functions,
  1880. grouped_native_functions=grouped_native_functions,
  1881. structured_native_functions=structured_native_functions,
  1882. static_dispatch_idx=static_dispatch_idx,
  1883. selector=selector,
  1884. backend_indices=backend_indices,
  1885. cpu_fm=cpu_fm,
  1886. device_fms=device_fms,
  1887. dispatch_keys=dispatch_keys,
  1888. functions_keys=functions_keys,
  1889. rocm=rocm,
  1890. )
  1891. core_fm.write(
  1892. "TensorBody.h",
  1893. lambda: {
  1894. "tensor_method_declarations": list(
  1895. mapMaybe(
  1896. ComputeTensorMethod(
  1897. target=Target.DECLARATION,
  1898. static_dispatch_backend_indices=static_dispatch_idx,
  1899. ),
  1900. native_functions,
  1901. )
  1902. ),
  1903. "tensor_method_definitions": list(
  1904. mapMaybe(
  1905. ComputeTensorMethod(
  1906. target=Target.DEFINITION,
  1907. static_dispatch_backend_indices=static_dispatch_idx,
  1908. ),
  1909. native_functions,
  1910. )
  1911. ),
  1912. },
  1913. )
  1914. cpu_fm.write(
  1915. "RedispatchFunctions.h",
  1916. lambda: {
  1917. "function_redispatch_definitions": list(
  1918. mapMaybe(ComputeRedispatchFunction(), native_functions)
  1919. ),
  1920. },
  1921. )
  1922. cpu_fm.write(
  1923. "RegistrationDeclarations.h",
  1924. lambda: {
  1925. "registration_declarations": [
  1926. compute_registration_declarations(f, backend_indices)
  1927. for f in native_functions
  1928. ],
  1929. },
  1930. )
  1931. cpu_fm.write(
  1932. "VmapGeneratedPlumbing.h", lambda: gen_all_vmap_plumbing(native_functions)
  1933. )
  1934. def gen_aten_interned_strings() -> dict[str, str]:
  1935. attrs: set[str] = set() # All function argument names
  1936. names = set() # All ATen function names
  1937. for func in native_functions:
  1938. names.add(str(func.func.name.name))
  1939. # Some operators don't have a functional variant but we still create a
  1940. # symbol without the underscore
  1941. names.add(func.func.name.name.base)
  1942. attrs.update(arg.name for arg in func.func.schema_order_arguments())
  1943. # These are keywords in C++, so aren't valid symbol names
  1944. # https://en.cppreference.com/w/cpp/language/operator_alternative
  1945. names -= {
  1946. "and",
  1947. "and_eq",
  1948. "bitand",
  1949. "bitor",
  1950. "compl",
  1951. "not",
  1952. "not_eq",
  1953. "or",
  1954. "or_eq",
  1955. "xor",
  1956. "xor_eq",
  1957. }
  1958. return {
  1959. "aten_symbols": " \\\n".join(
  1960. [f"_(aten, {name})" for name in sorted(names)]
  1961. ),
  1962. "attr_symbols": " \\\n".join(
  1963. [f"_(attr, {name})" for name in sorted(attrs)]
  1964. ),
  1965. }
  1966. core_fm.write("aten_interned_strings.h", gen_aten_interned_strings)
  1967. def gen_tags_enum() -> dict[str, str]:
  1968. return {"enum_of_valid_tags": (",\n".join(sorted(valid_tags)))}
  1969. core_fm.write("enum_tag.h", gen_tags_enum)
  1970. def gen_source_files(
  1971. *,
  1972. native_functions: Sequence[NativeFunction],
  1973. grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
  1974. structured_native_functions: Sequence[NativeFunctionsGroup],
  1975. view_groups: Sequence[NativeFunctionsViewGroup],
  1976. selector: SelectiveBuilder,
  1977. static_dispatch_idx: list[BackendIndex],
  1978. backend_indices: dict[DispatchKey, BackendIndex],
  1979. aoti_fm: FileManager,
  1980. core_fm: FileManager,
  1981. cpu_vec_fm: FileManager,
  1982. cpu_fm: FileManager,
  1983. device_fms: dict[str, FileManager],
  1984. dispatch_keys: Sequence[DispatchKey],
  1985. functions_keys: set[DispatchKey],
  1986. rocm: bool,
  1987. force_schema_registration: bool,
  1988. per_operator_headers: bool,
  1989. skip_dispatcher_op_registration: bool,
  1990. update_aoti_c_shim: bool,
  1991. aoti_backends: set[DispatchKey | None],
  1992. extend_aoti_c_shim: bool,
  1993. ) -> None:
  1994. extra_cuda_headers = """\
  1995. #include <c10/cuda/CUDAGuard.h>
  1996. #include <ATen/cuda/ATenCUDAGeneral.h>
  1997. #include <ATen/cuda/CUDADevice.h>
  1998. #include <ATen/cuda/CUDAContext.h>"""
  1999. if rocm:
  2000. extra_cuda_headers = """\
  2001. #include <ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h>
  2002. #include <ATen/hip/ATenHIPGeneral.h>
  2003. #include <ATen/hip/HIPDevice.h>
  2004. #include <ATen/hip/HIPContext.h>"""
  2005. for dispatch_key in dispatch_keys:
  2006. fm = file_manager_from_dispatch_key(dispatch_key, device_fms, cpu_fm)
  2007. if per_operator_headers:
  2008. def operator_headers() -> list[str]:
  2009. headers = []
  2010. for g in grouped_native_functions:
  2011. is_registered = False
  2012. if backend_index.has_kernel(g):
  2013. is_registered = True
  2014. # The above has_kernel test on a group will only test for
  2015. # the existence of out dispatch, because that's how
  2016. # structured kernels work. But sometimes functions can be
  2017. # grouped but not be structured, and then you need to check
  2018. # each individual piece, as they may have manual dispatch
  2019. # entries.
  2020. elif isinstance(g, NativeFunctionsGroup) and any(
  2021. backend_index.has_kernel(fn) for fn in g.functions()
  2022. ):
  2023. is_registered = True
  2024. # TODO: this condition is a bit questionable
  2025. # (It has to do with the fact that structured kernels get generated kernels
  2026. # to the Meta + CompositeExplicitAutogradNonFunctional keys).
  2027. elif g.structured and dispatch_key in (
  2028. DispatchKey.Meta,
  2029. DispatchKey.CompositeExplicitAutogradNonFunctional,
  2030. ):
  2031. is_registered = True
  2032. if not is_registered:
  2033. continue
  2034. headers.append(f"#include <ATen/ops/{g.root_name}_native.h>")
  2035. if (
  2036. dispatch_key
  2037. == DispatchKey.CompositeExplicitAutogradNonFunctional
  2038. ):
  2039. headers.append(f"#include <ATen/ops/{g.root_name}.h>")
  2040. if dispatch_key in functions_keys:
  2041. headers.append(
  2042. f"#include <ATen/ops/{g.root_name}_{dispatch_namespace}_dispatch.h>"
  2043. )
  2044. return sorted(set(headers))
  2045. else:
  2046. def operator_headers() -> list[str]:
  2047. headers = ["#include <ATen/NativeFunctions.h>"]
  2048. if dispatch_key == DispatchKey.CompositeExplicitAutogradNonFunctional:
  2049. headers.append("#include <ATen/Functions.h>")
  2050. if dispatch_key in functions_keys:
  2051. headers.append(f"#include <ATen/{dispatch_key!s}Functions.h>")
  2052. return headers
  2053. backend_index = backend_indices[dispatch_key]
  2054. ns_grouped_native_functions = defaultdict(list)
  2055. for grouped_native_function in grouped_native_functions:
  2056. namespace = (
  2057. grouped_native_function.namespace
  2058. if isinstance(grouped_native_function, NativeFunction)
  2059. else grouped_native_function.functional.namespace
  2060. )
  2061. ns_grouped_native_functions[namespace].append(grouped_native_function)
  2062. dispatch_namespace = str(dispatch_key).lower()
  2063. # CompositeImplicitAutogradNestdTensor does not currently user the helpers generated
  2064. # compilation will fail when `-Werror=unused-function` flag is set
  2065. gen_dispatch_helpers: bool = (
  2066. dispatch_key != DispatchKey.CompositeImplicitAutogradNestedTensor
  2067. )
  2068. register_dispatch_key_base_env = {
  2069. "extra_cuda_headers": extra_cuda_headers
  2070. if is_cuda_dispatch_key(dispatch_key)
  2071. else "",
  2072. "external_backend_headers": "",
  2073. "dispatch_headers": dest.gen_registration_headers(
  2074. backend_index, per_operator_headers, rocm
  2075. ),
  2076. # ops_headers *could* be sharded, but doesn't seem necessary?
  2077. "ops_headers": operator_headers(),
  2078. "dispatch_helpers": (
  2079. dest.gen_registration_helpers(backend_index)
  2080. if gen_dispatch_helpers
  2081. else []
  2082. ),
  2083. }
  2084. def register_dispatch_key_env_callable(
  2085. gnf: NativeFunction | NativeFunctionsGroup,
  2086. ) -> dict[str, list[str]]:
  2087. return {
  2088. "dispatch_definitions": get_native_function_definitions(
  2089. fm=fm, # noqa: F821
  2090. grouped_native_functions=[gnf],
  2091. dispatch_key=dispatch_key,
  2092. backend_idx=backend_index,
  2093. selector=selector,
  2094. rocm=rocm,
  2095. symint=True,
  2096. skip_dispatcher_op_registration=skip_dispatcher_op_registration,
  2097. gen_dispatch_helpers=gen_dispatch_helpers,
  2098. )
  2099. }
  2100. fm.write_sharded_with_template(
  2101. f"Register{dispatch_key}.cpp",
  2102. "RegisterDispatchKey.cpp",
  2103. grouped_native_functions,
  2104. key_fn=lambda x: x.root_name,
  2105. env_callable=register_dispatch_key_env_callable,
  2106. num_shards=4 if dispatch_key == DispatchKey.CPU else 1,
  2107. base_env=register_dispatch_key_base_env,
  2108. sharded_keys={"dispatch_definitions"},
  2109. )
  2110. for g in structured_native_functions:
  2111. if not g.out.ufunc_inner_loop or not is_ufunc_dispatch_key(dispatch_key):
  2112. continue
  2113. name = g.functional.func.name.name
  2114. if dispatch_key is DispatchKey.CPU:
  2115. assert fm is cpu_fm
  2116. fm.write_with_template(
  2117. f"UfuncCPU_{name}.cpp",
  2118. "UfuncCPU.cpp",
  2119. lambda: {
  2120. "meta_declaration": compute_meta_function_declaration(g),
  2121. "native_declaration": dest.compute_native_function_declaration(
  2122. g, backend_indices[dispatch_key]
  2123. ),
  2124. "native_definitions": dest.compute_ufunc_cpu(g),
  2125. },
  2126. )
  2127. cpu_vec_fm.write_with_template(
  2128. f"UfuncCPUKernel_{name}.cpp",
  2129. "UfuncCPUKernel.cpp",
  2130. lambda: {
  2131. "name": name,
  2132. "native_definitions": dest.compute_ufunc_cpu_kernel(g),
  2133. },
  2134. )
  2135. elif dispatch_key is DispatchKey.CUDA:
  2136. cuda_headers = "#include <ATen/native/cuda/Loops.cuh>"
  2137. if rocm:
  2138. cuda_headers = "#include <ATen/native/hip/Loops.cuh>"
  2139. fm.write_with_template(
  2140. f"UfuncCUDA_{name}.cu",
  2141. "UfuncCUDA.cu",
  2142. lambda: {
  2143. "name": name,
  2144. "cuda_headers": cuda_headers,
  2145. "meta_declaration": compute_meta_function_declaration(g),
  2146. "native_declaration": dest.compute_native_function_declaration(
  2147. g, backend_indices[dispatch_key]
  2148. ),
  2149. "native_definitions": dest.compute_ufunc_cuda(g),
  2150. },
  2151. )
  2152. else:
  2153. raise AssertionError(f"unrecognized {dispatch_key} for ufunc")
  2154. del fm
  2155. gen_aoti_c_shim_files(
  2156. aoti_fm=aoti_fm,
  2157. aoti_backends=aoti_backends,
  2158. native_functions=native_functions,
  2159. backend_indices=backend_indices,
  2160. structured_native_functions=structured_native_functions,
  2161. extra_cuda_headers=extra_cuda_headers,
  2162. update_aoti_c_shim=update_aoti_c_shim,
  2163. extend_aoti_c_shim=extend_aoti_c_shim,
  2164. )
  2165. # BackendSelect is generated specially
  2166. def gen_backend_select() -> dict[str, list[str]]:
  2167. relevant_fns = [
  2168. fn for fn in native_functions if needs_backend_select(fn, selector)
  2169. ]
  2170. return {
  2171. "ops_headers": [
  2172. f"#include <ATen/ops/{fn.root_name}_ops.h>" for fn in relevant_fns
  2173. ],
  2174. "backend_select_method_definitions": list(
  2175. mapMaybe(
  2176. ComputeBackendSelect(Target.DEFINITION, selector), relevant_fns
  2177. )
  2178. ),
  2179. "backend_select_function_registrations": list(
  2180. mapMaybe(
  2181. ComputeBackendSelect(Target.REGISTRATION, selector), relevant_fns
  2182. )
  2183. ),
  2184. }
  2185. cpu_fm.write("RegisterBackendSelect.cpp", gen_backend_select)
  2186. schema_selector = selector
  2187. if force_schema_registration:
  2188. schema_selector = SelectiveBuilder.get_nop_selector()
  2189. (
  2190. aten_schema_registrations,
  2191. schema_registrations,
  2192. ) = get_native_function_schema_registrations(
  2193. native_functions=native_functions, schema_selector=schema_selector
  2194. )
  2195. cpu_fm.write(
  2196. "RegisterSchema.cpp",
  2197. lambda: {
  2198. "aten_schema_registrations": []
  2199. if skip_dispatcher_op_registration
  2200. else aten_schema_registrations,
  2201. "schema_registrations": []
  2202. if skip_dispatcher_op_registration
  2203. else schema_registrations,
  2204. },
  2205. )
  2206. def key_func(
  2207. fn: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup,
  2208. ) -> str:
  2209. return fn.root_name
  2210. cpu_fm.write_sharded(
  2211. "Operators.cpp",
  2212. native_functions,
  2213. key_fn=key_func,
  2214. env_callable=lambda fn: {
  2215. "operator_headers": [f"#include <ATen/ops/{fn.root_name}.h>"],
  2216. "definitions": [
  2217. ComputeOperators(
  2218. Target.DEFINITION,
  2219. static_dispatch_backend_indices=static_dispatch_idx,
  2220. )(fn)
  2221. ],
  2222. },
  2223. base_env={
  2224. "static_dispatch_extra_headers": static_dispatch_extra_headers(
  2225. static_dispatch_idx
  2226. ),
  2227. },
  2228. num_shards=5,
  2229. sharded_keys={
  2230. "operator_headers",
  2231. "definitions",
  2232. "static_dispatch_extra_headers",
  2233. },
  2234. )
  2235. cpu_fm.write("Functions.cpp", dict)
  2236. core_fm.write("TensorMethods.cpp", dict)
  2237. core_fm.write(
  2238. "ATenOpList.cpp",
  2239. lambda: {
  2240. "aten_ops": list(mapMaybe(compute_aten_op, native_functions)),
  2241. },
  2242. )
  2243. def gen_op_headers(
  2244. g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup,
  2245. ) -> list[str]:
  2246. if isinstance(g, NativeFunctionsViewGroup):
  2247. # view ops always get a functionalization kernel
  2248. headers = [
  2249. f"#include <ATen/ops/{g.view.root_name}_native.h>",
  2250. f"#include <ATen/ops/{g.view.root_name}_ops.h>",
  2251. ]
  2252. if g.view_copy is not None:
  2253. headers += [
  2254. f"#include <ATen/ops/{g.view_copy.root_name}_native.h>",
  2255. f"#include <ATen/ops/{g.view_copy.root_name}_ops.h>",
  2256. ]
  2257. return headers
  2258. elif isinstance(g, NativeFunctionsGroup):
  2259. headers = [
  2260. f"#include <ATen/ops/{g.functional.root_name}_native.h>",
  2261. f"#include <ATen/ops/{g.functional.root_name}_ops.h>",
  2262. f"#include <ATen/ops/{g.out.root_name}_native.h>",
  2263. f"#include <ATen/ops/{g.out.root_name}_ops.h>",
  2264. ]
  2265. if g.inplace is not None:
  2266. headers += [
  2267. f"#include <ATen/ops/{g.inplace.root_name}_native.h>",
  2268. f"#include <ATen/ops/{g.inplace.root_name}_ops.h>",
  2269. ]
  2270. if g.mutable is not None:
  2271. headers += [
  2272. f"#include <ATen/ops/{g.mutable.root_name}_native.h>",
  2273. f"#include <ATen/ops/{g.mutable.root_name}_ops.h>",
  2274. ]
  2275. return headers
  2276. else:
  2277. return [
  2278. f"#include <ATen/ops/{g.root_name}_native.h>",
  2279. f"#include <ATen/ops/{g.root_name}_ops.h>",
  2280. ]
  2281. def functionalization_env_callable(
  2282. g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup,
  2283. ) -> dict[str, list[str]]:
  2284. return {
  2285. "ops_headers": gen_op_headers(g),
  2286. "func_definitions": gen_functionalization_definition(
  2287. selector,
  2288. g,
  2289. ),
  2290. "func_registrations": gen_functionalization_registration(
  2291. selector,
  2292. g,
  2293. backend_indices[DispatchKey.CompositeImplicitAutograd],
  2294. ),
  2295. }
  2296. all_groups: list[
  2297. NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup
  2298. ] = list(structured_native_functions) + list(
  2299. view_groups # type: ignore[assignment, arg-type, operator]
  2300. )
  2301. # Note: all operators that functionalization needs to handle (mutable and aliasing ops) should be grouped properly.
  2302. # The only reason we really need to deal with direct NativeFunctions here (instead of the groups) is because:
  2303. # (1) We can provide better error checking (error out if someone introduces a mutable op that doesn't obey the grouping logic)
  2304. # (2) functionalization needs to manually register CompositeImplicitAutograd kernels, which might not be grouped.
  2305. # Although this could go away long-term if we add a dedicated dispatch key for decompositions.
  2306. structured_map: dict[OperatorName, NativeFunction] = {
  2307. f.func.name: f
  2308. for f in concatMap(lambda g: list(g.functions()), structured_native_functions)
  2309. }
  2310. view_map: dict[OperatorName, NativeFunction] = {
  2311. f.func.name: f for f in concatMap(lambda g: list(g.functions()), view_groups)
  2312. }
  2313. all_groups.extend(
  2314. f
  2315. for f in native_functions
  2316. if f.func.name not in structured_map and f.func.name not in view_map
  2317. )
  2318. cpu_fm.write_sharded(
  2319. "RegisterFunctionalization.cpp",
  2320. all_groups,
  2321. key_fn=key_func,
  2322. env_callable=functionalization_env_callable,
  2323. num_shards=4,
  2324. sharded_keys={
  2325. "ops_headers",
  2326. "func_definitions",
  2327. "func_registrations",
  2328. "func_add_back_views_definitions",
  2329. "func_add_back_views_registrations",
  2330. },
  2331. )
  2332. cpu_fm.write(
  2333. "FunctionalInverses.h",
  2334. lambda: {
  2335. "view_inverse_declarations": list(
  2336. mapMaybe(
  2337. lambda g: gen_functionalization_view_inverse_declaration(
  2338. selector, g
  2339. ),
  2340. view_groups,
  2341. )
  2342. )
  2343. },
  2344. )
  2345. cpu_fm.write(
  2346. "ViewMetaClasses.h",
  2347. lambda: {
  2348. "view_meta_declarations": list(
  2349. concatMap(
  2350. lambda g: gen_functionalization_view_meta_classes_decl(selector, g),
  2351. view_groups,
  2352. )
  2353. )
  2354. },
  2355. )
  2356. cpu_fm.write(
  2357. "ViewMetaClasses.cpp",
  2358. lambda: {
  2359. "view_meta_implementations": list(
  2360. concatMap(
  2361. lambda g: gen_functionalization_view_meta_classes_impl(selector, g),
  2362. view_groups,
  2363. )
  2364. ),
  2365. "op_headers": list(concatMap(gen_op_headers, view_groups)),
  2366. },
  2367. )
  2368. # Note [view_copy NativeFunctions]
  2369. # Every view operator in native_functions.yaml that is not CompositeImplicitAutograd
  2370. # needs to have a corresponding non-aliasing {view}_copy variant.
  2371. # Backends that use functionalization and don't know how to handle aliasing ops
  2372. # are expected to implement kernels for these {view}_copy kernels instead.
  2373. # The code for {view}_copy operators in core is pretty boilerplate-heavy however,
  2374. # so we codegen the following:
  2375. # (1) A CompositeExplicitAutogradNonFunctional kernel for every {view}_copy operator.
  2376. # These are never explicitly invoked by the functionalization pass,
  2377. # but they could theoretically be called from user code (I added these kernels for completeness,
  2378. # since the ops are part of the public API).
  2379. # (2) A derivative formula for every {view}_copy operator
  2380. # {view}_copy operators can reuse the same derivative formulas as their {view} op counterparts,
  2381. # so rather than stamping all of the entries out in derivatives.yaml,
  2382. # we codegen them in.
  2383. # This is similar to how autograd codegen doesn't require inplace ops to have a derivatives.yaml entry.
  2384. cpu_fm.write(
  2385. "CompositeViewCopyKernels.cpp",
  2386. lambda: {
  2387. "ops_headers": [
  2388. "\n".join(
  2389. f"#include <ATen/ops/{f.root_name}_ops.h>\n"
  2390. # NB: this include is important as it ensures we
  2391. # set the visibility on generated view_copy kernels
  2392. # correctly
  2393. f"#include <ATen/ops/{f.root_name}_native.h>"
  2394. for f in (
  2395. [g.view] if g.view_copy is None else [g.view, g.view_copy]
  2396. )
  2397. )
  2398. for g in view_groups
  2399. ]
  2400. + [
  2401. "\n".join(
  2402. f"#include <ATen/ops/{f.root_name}_ops.h>\n"
  2403. # NB: this include is also important for correct visibility
  2404. f"#include <ATen/ops/{f.root_name}_native.h>"
  2405. for f in [g.inplace, g.mutable, g.functional]
  2406. if f is not None and "generated" not in f.tags
  2407. )
  2408. for g in structured_native_functions
  2409. ],
  2410. "CompositeViewCopyKernel_Definitions": list(
  2411. mapMaybe(
  2412. GenCompositeViewCopyKernel(
  2413. backend_indices[
  2414. DispatchKey.CompositeExplicitAutogradNonFunctional
  2415. ]
  2416. ),
  2417. view_groups,
  2418. )
  2419. ),
  2420. "GeneratedCompositeFunctional_Definitions": list(
  2421. mapMaybe(
  2422. gen_composite_functional_kernel,
  2423. structured_native_functions,
  2424. )
  2425. ),
  2426. "GeneratedCompositeOut_Definitions": list(
  2427. mapMaybe(
  2428. gen_composite_out_kernel,
  2429. structured_native_functions,
  2430. )
  2431. ),
  2432. },
  2433. )
  2434. def gen_declarations_yaml(
  2435. cpu_fm: FileManager, native_functions: Sequence[NativeFunction]
  2436. ) -> None:
  2437. cpu_fm.write(
  2438. "Declarations.yaml",
  2439. lambda: format_yaml([compute_declaration_yaml(f) for f in native_functions]),
  2440. )
  2441. def get_torchgen_root() -> Path:
  2442. """
  2443. If you're depending on torchgen out-of-tree, you can use the root to figure
  2444. out the path to native_functions.yaml
  2445. """
  2446. return Path(__file__).parent.resolve()
  2447. def main() -> None:
  2448. parser = argparse.ArgumentParser(description="Generate ATen source files")
  2449. parser.add_argument(
  2450. "-s",
  2451. "--source-path",
  2452. help="path to source directory for ATen",
  2453. default="aten/src/ATen",
  2454. )
  2455. parser.add_argument(
  2456. "-o",
  2457. "--output-dependencies",
  2458. help="output a list of dependencies into the given file and exit",
  2459. )
  2460. parser.add_argument(
  2461. "--dry-run",
  2462. action="store_true",
  2463. help="run without writing any files (still updates outputs)",
  2464. )
  2465. parser.add_argument(
  2466. "--per-operator-headers",
  2467. action="store_true",
  2468. help="generate separate headers per operator in ATen/ops",
  2469. )
  2470. parser.add_argument(
  2471. "-d",
  2472. "--install-dir",
  2473. "--install_dir",
  2474. help="output directory",
  2475. default="build/aten/src/ATen",
  2476. )
  2477. parser.add_argument(
  2478. "--aoti-install-dir",
  2479. "--aoti_install_dir",
  2480. help="output directory for AOTInductor shim",
  2481. default="torch/csrc/inductor/aoti_torch/generated",
  2482. )
  2483. parser.add_argument(
  2484. "--rocm",
  2485. action="store_true",
  2486. help="reinterpret CUDA as ROCm/HIP and adjust filepaths accordingly",
  2487. )
  2488. parser.add_argument(
  2489. "--mps",
  2490. action="store_true",
  2491. help="Generate MPS registration code when set",
  2492. )
  2493. parser.add_argument(
  2494. "--xpu",
  2495. action="store_true",
  2496. help="Generate XPU registration code when set",
  2497. )
  2498. parser.add_argument(
  2499. "--mtia",
  2500. action="store_true",
  2501. help="Generate MTIA registration code when set",
  2502. )
  2503. # TODO: --op-registration-whitelist will be removed when all call-sites
  2504. # for gen.py are moved over to using the operator YAML file for mobile
  2505. # custom build.
  2506. parser.add_argument(
  2507. "--op-registration-whitelist",
  2508. "--op_registration_whitelist",
  2509. nargs="*",
  2510. help="filter op registrations by the whitelist (if set); "
  2511. "each item is `namespace`::`operator name` without overload name; "
  2512. "e.g.: aten::empty aten::conv2d ...",
  2513. )
  2514. parser.add_argument(
  2515. "--op-selection-yaml-path",
  2516. "--op_selection_yaml_path",
  2517. help="Provide a path to the operator selection (for custom build) YAML "
  2518. "that contains the information about the set of selected operators "
  2519. "and their categories (training, ...). Each operator is either a "
  2520. "full operator name with overload or just a bare operator name. "
  2521. "The operator names also contain the namespace prefix (e.g. aten::)",
  2522. )
  2523. parser.add_argument(
  2524. "--backend-whitelist",
  2525. "--backend_whitelist",
  2526. nargs="*",
  2527. help="filter dispatch backend by the whitelist (if set), "
  2528. "e.g.: CPU CUDA QuantizedCPU ...",
  2529. )
  2530. parser.add_argument(
  2531. "--static-dispatch-backend",
  2532. "--static_dispatch_backend",
  2533. nargs="*",
  2534. help="generate static dispatch code for the specific backend (if set)",
  2535. )
  2536. parser.add_argument(
  2537. "--skip-dispatcher-op-registration",
  2538. "--skip_dispatcher_op_registration",
  2539. action="store_true",
  2540. help="Avoid registering operators into the dispatcher.",
  2541. )
  2542. parser.add_argument(
  2543. "--force-schema-registration",
  2544. "--force_schema_registration",
  2545. action="store_true",
  2546. help="force it to generate schema-only registrations for all ops, including"
  2547. "those that are not listed on --op-registration-whitelist",
  2548. )
  2549. parser.add_argument(
  2550. "--generate",
  2551. type=str,
  2552. nargs="*",
  2553. choices=["headers", "sources", "declarations_yaml"],
  2554. default=["headers", "sources", "declarations_yaml"],
  2555. help="Generate only a subset of files",
  2556. )
  2557. parser.add_argument(
  2558. "--update-aoti-c-shim",
  2559. action="store_true",
  2560. help="Update AOTInductor C shim after adding an entry to inductor_fallback_ops in torchgen/aoti/fallback_ops.py. "
  2561. "WARNING: Do not use this unless you are sure what you are doing!!!",
  2562. )
  2563. parser.add_argument(
  2564. "--extend-aoti-c-shim",
  2565. action="store_true",
  2566. help="This Flag indicates the generation of c shims for out-of-tree ATen ops,"
  2567. "which is an extension to the In-tree ATen op c shims. This flag needs to be combined with"
  2568. "---source-path=<out-of-tree native_functions.yaml>"
  2569. "--aoti-install-dir=<in-tree aoti_install_dir>/extend"
  2570. " default is torch/csrc/inductor/aoti_torch/generated/extend"
  2571. "WARNING: Do not use this unless you are sure what you are doing!!!",
  2572. )
  2573. options = parser.parse_args()
  2574. selector = get_custom_build_selector(
  2575. options.op_registration_whitelist,
  2576. options.op_selection_yaml_path,
  2577. )
  2578. native_yaml_path = os.path.join(options.source_path, "native/native_functions.yaml")
  2579. tags_yaml_path = os.path.join(options.source_path, "native/tags.yaml")
  2580. from torchgen.model import dispatch_keys
  2581. # Only a limited set of dispatch keys get CPUFunctions.h headers generated
  2582. # for them; this is the set
  2583. functions_keys = {
  2584. DispatchKey.CPU,
  2585. DispatchKey.CUDA,
  2586. DispatchKey.CompositeImplicitAutograd,
  2587. DispatchKey.CompositeImplicitAutogradNestedTensor,
  2588. DispatchKey.CompositeExplicitAutograd,
  2589. DispatchKey.CompositeExplicitAutogradNonFunctional,
  2590. DispatchKey.Meta,
  2591. DispatchKey.MTIA,
  2592. }
  2593. aoti_backends = {
  2594. DispatchKey.CPU,
  2595. DispatchKey.CUDA,
  2596. # None will generate the aten shim based on aten_shimified_ops
  2597. # which does not bypass the dispatcher
  2598. None,
  2599. }
  2600. # TODO: stop generating CUDA kernels for non-CUDA builds
  2601. ignore_keys = set()
  2602. MPS_KEYS = {DispatchKey.MPS, DispatchKey.SparseMPS, DispatchKey.SparseCsrMPS}
  2603. if options.mps or options.update_aoti_c_shim:
  2604. functions_keys.update(MPS_KEYS)
  2605. aoti_backends.add(DispatchKey.MPS)
  2606. else:
  2607. ignore_keys.update(MPS_KEYS)
  2608. dispatch_keys[:] = [k for k in dispatch_keys if k not in MPS_KEYS]
  2609. if options.xpu or options.update_aoti_c_shim:
  2610. functions_keys.add(DispatchKey.XPU)
  2611. aoti_backends.add(DispatchKey.XPU)
  2612. else:
  2613. ignore_keys.add(DispatchKey.XPU)
  2614. if DispatchKey.XPU in dispatch_keys:
  2615. del dispatch_keys[dispatch_keys.index(DispatchKey.XPU)]
  2616. if not options.mtia:
  2617. ignore_keys.add(DispatchKey.MTIA)
  2618. if DispatchKey.MTIA in dispatch_keys:
  2619. del dispatch_keys[dispatch_keys.index(DispatchKey.MTIA)]
  2620. if options.backend_whitelist:
  2621. dispatch_keys = [
  2622. k
  2623. for k in dispatch_keys
  2624. if is_generic_dispatch_key(k) or str(k) in options.backend_whitelist
  2625. ]
  2626. parsed_yaml = parse_native_yaml(native_yaml_path, tags_yaml_path, ignore_keys)
  2627. valid_tags = _GLOBAL_PARSE_TAGS_YAML_CACHE[tags_yaml_path]
  2628. native_functions, backend_indices = (
  2629. parsed_yaml.native_functions,
  2630. parsed_yaml.backend_indices,
  2631. )
  2632. grouped_native_functions = get_grouped_native_functions(native_functions)
  2633. structured_native_functions = [
  2634. g for g in grouped_native_functions if isinstance(g, NativeFunctionsGroup)
  2635. ]
  2636. native_functions_with_view_groups = get_grouped_by_view_native_functions(
  2637. native_functions
  2638. )
  2639. view_groups = [
  2640. g
  2641. for g in native_functions_with_view_groups
  2642. if isinstance(g, NativeFunctionsViewGroup)
  2643. ]
  2644. # NB: It is mandatory to NOT use os.path.join here, as the install directory
  2645. # will eventually be ingested by cmake, which does not respect Windows style
  2646. # path slashes. If you switch this to use os.path.join, you'll get an error
  2647. # like:
  2648. #
  2649. # Syntax error in cmake code when parsing string
  2650. #
  2651. # C:/Jenkins/workspace/pytorch-builds/pytorch-win-ws2016-cuda9-cudnn7-py3-build/build/aten/src/ATen\core/TensorMethods.h
  2652. #
  2653. # Invalid character escape '\c'.
  2654. core_install_dir = f"{options.install_dir}/core"
  2655. Path(core_install_dir).mkdir(parents=True, exist_ok=True)
  2656. ops_install_dir = f"{options.install_dir}/ops"
  2657. Path(ops_install_dir).mkdir(parents=True, exist_ok=True)
  2658. aoti_install_dir = f"{options.aoti_install_dir}"
  2659. Path(aoti_install_dir).mkdir(parents=True, exist_ok=True)
  2660. core_fm = make_file_manager(options=options, install_dir=core_install_dir)
  2661. cpu_fm = make_file_manager(options=options)
  2662. cpu_vec_fm = make_file_manager(options=options)
  2663. cuda_fm = make_file_manager(options=options)
  2664. ops_fm = make_file_manager(options=options, install_dir=ops_install_dir)
  2665. aoti_fm = make_file_manager(options=options, install_dir=aoti_install_dir)
  2666. device_fms = {"cuda": cuda_fm}
  2667. if options.xpu:
  2668. device_fms["xpu"] = make_file_manager(options=options)
  2669. static_dispatch_idx: list[BackendIndex] = []
  2670. if options.static_dispatch_backend:
  2671. static_dispatch_idx = [
  2672. backend_indices[DispatchKey.parse(key)]
  2673. for key in options.static_dispatch_backend
  2674. ]
  2675. for key in options.static_dispatch_backend:
  2676. dp_key = DispatchKey.parse(key)
  2677. if dp_key not in functions_keys:
  2678. functions_keys.add(dp_key)
  2679. if "sources" in options.generate:
  2680. gen_source_files(
  2681. native_functions=native_functions,
  2682. grouped_native_functions=grouped_native_functions,
  2683. structured_native_functions=structured_native_functions,
  2684. view_groups=view_groups,
  2685. selector=selector,
  2686. static_dispatch_idx=static_dispatch_idx,
  2687. backend_indices=backend_indices,
  2688. aoti_fm=aoti_fm,
  2689. core_fm=core_fm,
  2690. cpu_vec_fm=cpu_vec_fm,
  2691. cpu_fm=cpu_fm,
  2692. device_fms=device_fms,
  2693. dispatch_keys=dispatch_keys,
  2694. functions_keys=functions_keys,
  2695. rocm=options.rocm,
  2696. force_schema_registration=options.force_schema_registration,
  2697. per_operator_headers=options.per_operator_headers,
  2698. skip_dispatcher_op_registration=options.skip_dispatcher_op_registration,
  2699. update_aoti_c_shim=options.update_aoti_c_shim,
  2700. aoti_backends=aoti_backends,
  2701. extend_aoti_c_shim=options.extend_aoti_c_shim,
  2702. )
  2703. if "headers" in options.generate:
  2704. gen_headers(
  2705. native_functions=native_functions,
  2706. valid_tags=valid_tags,
  2707. grouped_native_functions=grouped_native_functions,
  2708. structured_native_functions=structured_native_functions,
  2709. static_dispatch_idx=static_dispatch_idx,
  2710. selector=selector,
  2711. backend_indices=backend_indices,
  2712. core_fm=core_fm,
  2713. cpu_fm=cpu_fm,
  2714. device_fms=device_fms,
  2715. ops_fm=ops_fm,
  2716. dispatch_keys=dispatch_keys,
  2717. functions_keys=functions_keys,
  2718. rocm=options.rocm,
  2719. per_operator_headers=options.per_operator_headers,
  2720. )
  2721. if "declarations_yaml" in options.generate:
  2722. gen_declarations_yaml(native_functions=native_functions, cpu_fm=cpu_fm)
  2723. if options.output_dependencies:
  2724. depfile_path = Path(options.output_dependencies).resolve()
  2725. depfile_name = depfile_path.name
  2726. depfile_stem = depfile_path.stem
  2727. for fm, prefix in [
  2728. (cpu_fm, ""),
  2729. (cpu_vec_fm, "cpu_vec_"),
  2730. (core_fm, "core_"),
  2731. (ops_fm, "ops_"),
  2732. ] + [(device_fm, f"{device}_") for device, device_fm in device_fms.items()]:
  2733. varname = prefix + depfile_stem
  2734. path = depfile_path.parent / (prefix + depfile_name)
  2735. fm.write_outputs(varname, str(path))
  2736. if __name__ == "__main__":
  2737. main()