gen.py 112 KB

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