gen_backend_stubs.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. from __future__ import annotations
  2. import argparse
  3. import os
  4. import re
  5. from collections import Counter, defaultdict, namedtuple
  6. from pathlib import Path
  7. from typing import TYPE_CHECKING
  8. import yaml
  9. import torchgen.api.dispatcher as dispatcher
  10. import torchgen.dest as dest
  11. from torchgen.api.types import DispatcherSignature
  12. from torchgen.code_template import CodeTemplate
  13. from torchgen.context import native_function_manager
  14. from torchgen.gen import get_grouped_native_functions, parse_native_yaml
  15. from torchgen.model import (
  16. BackendIndex,
  17. BackendMetadata,
  18. DispatchKey,
  19. NativeFunction,
  20. NativeFunctionsGroup,
  21. OperatorName,
  22. )
  23. from torchgen.selective_build.selector import SelectiveBuilder
  24. from torchgen.utils import concatMap, context, FileManager, NamespaceHelper, Target
  25. from torchgen.yaml_utils import YamlLoader
  26. if TYPE_CHECKING:
  27. from collections.abc import Sequence
  28. # Parses the external backend's yaml, and adds a new BackendIndex for the backend's dispatch key.
  29. # Returns a Tuple of (backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping)
  30. ParsedExternalYaml = namedtuple(
  31. "ParsedExternalYaml",
  32. ["backend_key", "autograd_key", "class_name", "cpp_namespace", "backend_indices"],
  33. )
  34. def parse_backend_yaml(
  35. backend_yaml_path: str,
  36. grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
  37. backend_indices: dict[DispatchKey, BackendIndex],
  38. ) -> ParsedExternalYaml:
  39. native_functions_map: dict[OperatorName, NativeFunction] = {
  40. f.func.name: f
  41. for f in concatMap(
  42. lambda f: [f] if isinstance(f, NativeFunction) else list(f.functions()),
  43. grouped_native_functions,
  44. )
  45. }
  46. with open(backend_yaml_path) as f:
  47. yaml_values = yaml.load(f, Loader=YamlLoader)
  48. assert isinstance(yaml_values, dict)
  49. valid_keys = [
  50. "backend",
  51. "class_name",
  52. "cpp_namespace",
  53. "extra_headers",
  54. "supported",
  55. "autograd",
  56. "full_codegen",
  57. "non_native",
  58. "ir_gen",
  59. "symint",
  60. ]
  61. backend = yaml_values.pop("backend", None)
  62. assert backend is not None, 'You must provide a value for "backend"'
  63. class_name = yaml_values.pop("class_name", None)
  64. cpp_namespace = yaml_values.pop("cpp_namespace", None)
  65. assert cpp_namespace is not None, 'You must provide a value for "cpp_namespace"'
  66. # Mostly just defaulting to false to stick with LazyTensor convention.
  67. use_out_as_primary = yaml_values.pop("use_out_as_primary", False)
  68. assert isinstance(use_out_as_primary, bool), (
  69. f"You must provide either True or False for use_out_as_primary. Provided: {use_out_as_primary}"
  70. )
  71. use_device_guard = yaml_values.pop("device_guard", False)
  72. assert isinstance(use_device_guard, bool), (
  73. f"You must provide either True or False for device_guard. Provided: {use_device_guard}"
  74. )
  75. supported = yaml_values.pop("supported", [])
  76. if supported is None:
  77. supported = [] # Allow an empty list of supported ops
  78. assert isinstance(supported, list), (
  79. f'expected "supported" to be a list, but got: {supported} (of type {type(supported)})'
  80. )
  81. symint = yaml_values.pop("symint", [])
  82. if symint is None:
  83. symint = [] # Allow an empty list of symint ops
  84. assert isinstance(symint, list), (
  85. f'expected "symint" to be a list, but got: {supported} (of type {type(supported)})'
  86. )
  87. symint_set = set(symint)
  88. supported_autograd = yaml_values.pop("autograd", [])
  89. assert isinstance(supported_autograd, list), (
  90. f'expected "autograd" to be a list, but got: {supported_autograd}'
  91. )
  92. # full_codegen is ignored by parse_backend_yaml, and re-parsed in gen_lazy_tensor.py
  93. full_codegen = yaml_values.pop("full_codegen", [])
  94. supported.extend(full_codegen)
  95. # non_native is ignored by parse_backend_yaml, and re-parsed in gen_lazy_tensor.py
  96. yaml_values.pop("non_native", {})
  97. # ir_gen is ignored by parse_backend_yaml, and re-parsed in gen_lazy_tensor.py
  98. yaml_values.pop("ir_gen", {})
  99. assert len(yaml_values.keys()) == 0, (
  100. f"{backend_yaml_path} contains unexpected keys: {', '.join(yaml_values.keys())}. "
  101. f"Only the following keys are supported: {', '.join(valid_keys)}"
  102. )
  103. def create_backend_index(
  104. backend_ops: list[str],
  105. symint_ops: set[str],
  106. dispatch_key: DispatchKey,
  107. *,
  108. use_out_as_primary: bool,
  109. use_device_guard: bool,
  110. ) -> BackendIndex:
  111. metadata: dict[OperatorName, BackendMetadata] = {}
  112. for op in backend_ops:
  113. op_name = OperatorName.parse(op)
  114. assert op_name in native_functions_map, (
  115. f"Found an invalid operator name: {op_name}"
  116. )
  117. # See Note [External Backends Follow Dispatcher API]
  118. kernel_name = dispatcher.name(native_functions_map[op_name].func)
  119. if op in symint_ops:
  120. kernel_name += "_symint"
  121. # TODO: allow structured external backends later.
  122. m = BackendMetadata(
  123. kernel=kernel_name, structured=False, cpp_namespace=cpp_namespace
  124. )
  125. metadata[op_name] = m
  126. return BackendIndex(
  127. dispatch_key=dispatch_key,
  128. use_out_as_primary=use_out_as_primary,
  129. external=True,
  130. device_guard=use_device_guard,
  131. index=metadata,
  132. )
  133. backend_key: DispatchKey | None = None
  134. if len(supported) > 0:
  135. with context(
  136. lambda: f'The provided value for "backend" must be a valid DispatchKey, but got {backend}.'
  137. ):
  138. backend_key = DispatchKey.parse(backend)
  139. backend_idx = create_backend_index(
  140. supported,
  141. symint_set,
  142. backend_key,
  143. use_out_as_primary=use_out_as_primary,
  144. use_device_guard=use_device_guard,
  145. )
  146. assert backend_key not in backend_indices
  147. backend_indices[backend_key] = backend_idx
  148. autograd_key: DispatchKey | None = None
  149. if len(supported_autograd) > 0:
  150. with context(
  151. lambda: f'The "autograd" key was specified, which indicates that you would like to override \
  152. the behavior of autograd for some operators on your backend. However "Autograd{backend}" is not a valid DispatchKey.'
  153. ):
  154. autograd_key = DispatchKey.parse(f"Autograd{backend}")
  155. autograd_idx = create_backend_index(
  156. supported_autograd,
  157. symint_set,
  158. autograd_key,
  159. use_out_as_primary=use_out_as_primary,
  160. use_device_guard=use_device_guard,
  161. )
  162. assert autograd_key not in backend_indices
  163. backend_indices[autograd_key] = autograd_idx
  164. for g in grouped_native_functions:
  165. if isinstance(g, NativeFunction):
  166. forward_kernels = (
  167. []
  168. if backend_key is None
  169. else [
  170. m
  171. for m in [backend_indices[backend_key].get_kernel(g)]
  172. if m is not None
  173. ]
  174. )
  175. backward_kernels = (
  176. []
  177. if autograd_key is None
  178. else [
  179. m
  180. for m in [backend_indices[autograd_key].get_kernel(g)]
  181. if m is not None
  182. ]
  183. )
  184. else:
  185. forward_kernels = (
  186. []
  187. if backend_key is None
  188. else [
  189. m
  190. for m in [
  191. backend_indices[backend_key].get_kernel(f)
  192. for f in g.functions()
  193. ]
  194. if m is not None
  195. ]
  196. )
  197. backward_kernels = (
  198. []
  199. if autograd_key is None
  200. else [
  201. m
  202. for m in [
  203. backend_indices[autograd_key].get_kernel(f)
  204. for f in g.functions()
  205. ]
  206. if m is not None
  207. ]
  208. )
  209. forward_kernels = [f for f in forward_kernels if f is not None]
  210. backward_kernels = [f for f in backward_kernels if f is not None]
  211. assert len(forward_kernels) == 0 or len(backward_kernels) == 0, (
  212. f'Currently, all variants of an op must either be registered to a backend key, or to a backend\'s \
  213. autograd key. They cannot be mix and matched. If this is something you need, feel free to create an issue! \
  214. {forward_kernels[0].kernel} is listed under "supported", but {backward_kernels[0].kernel} is listed under "autograd".'
  215. )
  216. return ParsedExternalYaml(
  217. backend_key, autograd_key, class_name, cpp_namespace, backend_indices
  218. )
  219. def error_on_missing_kernels(
  220. native_functions: Sequence[NativeFunction],
  221. backend_indices: dict[DispatchKey, BackendIndex],
  222. backend_key: DispatchKey,
  223. autograd_key: DispatchKey | None,
  224. class_name: str,
  225. kernel_defn_file_path: str,
  226. full_codegen: list[OperatorName] | None = None,
  227. ) -> None:
  228. try:
  229. with open(kernel_defn_file_path) as f:
  230. backend_defns = f.read()
  231. except OSError as e:
  232. raise AssertionError(
  233. f"Unable to read from the specified impl_path file: {kernel_defn_file_path}"
  234. ) from e
  235. if full_codegen is None:
  236. full_codegen = []
  237. indices = [backend_indices[backend_key].index] + (
  238. [] if autograd_key is None else [backend_indices[autograd_key].index]
  239. )
  240. # Quick mapping from each OperatorName used by the external backend
  241. # to its backend kernel name
  242. expected_backend_op_names: dict[OperatorName, str] = dict(
  243. list(
  244. concatMap(
  245. lambda index: [
  246. (op_name, metadata.kernel) for op_name, metadata in index.items()
  247. ],
  248. indices,
  249. )
  250. )
  251. )
  252. expected_backend_native_funcs: list[NativeFunction] = [
  253. f
  254. for f in native_functions
  255. if f.func.name in expected_backend_op_names.keys()
  256. and f.func.name not in full_codegen
  257. ]
  258. expected_backend_kernel_name_counts: dict[str, list[NativeFunction]] = defaultdict(
  259. list
  260. )
  261. for native_f in expected_backend_native_funcs:
  262. expected_backend_kernel_name_counts[
  263. expected_backend_op_names[native_f.func.name]
  264. ].append(native_f)
  265. # This just looks for lines containing "foo(", and assumes that the kernel foo has been implemented.
  266. # It might cause false negatives (we won't catch all cases), but that's ok - if we catch a missing kernel
  267. # here, then we get a nicer error message. If we miss it, you get a linker error.
  268. kernel_defn_regex = rf"(.*){class_name}::\s*([\w\d]*)\("
  269. actual_backend_kernel_name_counts = Counter(
  270. # A bit unwieldy (this could probably be moved into regex),
  271. # but we don't want to include kernel names that come from function calls,
  272. # like "return torch_xla::XLANativeFunctions::empty_strided_symint(...)".
  273. # Easy check is to ignore any lines with colons before the class name.
  274. [
  275. y
  276. for (x, y) in re.findall(kernel_defn_regex, backend_defns)
  277. if not x.endswith(":")
  278. ]
  279. )
  280. missing_kernels_err_msg = ""
  281. for expected_name, funcs in expected_backend_kernel_name_counts.items():
  282. expected_overload_count = len(funcs)
  283. actual_overload_count = actual_backend_kernel_name_counts[expected_name]
  284. if expected_overload_count != actual_overload_count:
  285. def create_decl(f: NativeFunction) -> str:
  286. with native_function_manager(f):
  287. return DispatcherSignature.from_schema(f.func).decl()
  288. expected_schemas_str = "\n".join([create_decl(f) for f in funcs])
  289. missing_kernels_err_msg += f"""
  290. {class_name} is missing a kernel definition for {expected_name}. We found {actual_overload_count} kernel(s) with that name,
  291. but expected {expected_overload_count} kernel(s). The expected function schemas for the missing operator are:
  292. {expected_schemas_str}
  293. """
  294. assert missing_kernels_err_msg == "", missing_kernels_err_msg
  295. def main() -> None:
  296. parser = argparse.ArgumentParser(description="Generate backend stub files")
  297. parser.add_argument(
  298. "-s",
  299. "--source-yaml",
  300. "--source_yaml",
  301. help="path to source yaml file containing operator external definitions",
  302. )
  303. parser.add_argument("-o", "--output-dir", "--output_dir", help="output directory")
  304. parser.add_argument(
  305. "--dry-run", "--dry_run", type=bool, default=False, help="output directory"
  306. )
  307. parser.add_argument(
  308. "--impl-path",
  309. "--impl_path",
  310. type=str,
  311. default=None,
  312. help="path to the source C++ file containing kernel definitions",
  313. )
  314. options = parser.parse_args()
  315. run(options.source_yaml, options.output_dir, options.dry_run, options.impl_path)
  316. def gen_dispatchkey_nativefunc_headers(
  317. fm: FileManager,
  318. class_name: str,
  319. cpp_namespace: str,
  320. backend_indices: dict[DispatchKey, BackendIndex],
  321. grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
  322. backend_dispatch_key: DispatchKey,
  323. autograd_dispatch_key: DispatchKey | None,
  324. backend_name: str = "",
  325. ) -> None:
  326. assert class_name is not None
  327. generated_comment = (
  328. "Autogenerated file by gen_backend_stubs.py. Do not edit directly!"
  329. )
  330. # Convert to a set first to remove duplicate kernel names.
  331. # Backends are allowed to repeat kernel names; only generate the declaration once!
  332. # Sort for deterministic output.
  333. backend_declarations = sorted(
  334. set(
  335. concatMap(
  336. lambda f: dest.compute_native_function_declaration(
  337. f, backend_indices[backend_dispatch_key]
  338. ),
  339. grouped_native_functions,
  340. )
  341. )
  342. )
  343. autograd_declarations = sorted(
  344. set(
  345. concatMap(
  346. lambda f: []
  347. if autograd_dispatch_key is None
  348. else dest.compute_native_function_declaration(
  349. f, backend_indices[autograd_dispatch_key]
  350. ),
  351. grouped_native_functions,
  352. )
  353. )
  354. )
  355. ns_helper = NamespaceHelper(cpp_namespace)
  356. fm.write_with_template(
  357. f"{backend_dispatch_key}NativeFunctions.h",
  358. "DispatchKeyNativeFunctions.h",
  359. lambda: {
  360. "generated_comment": generated_comment,
  361. "namespace_prologue": ns_helper.prologue,
  362. "class_name": class_name,
  363. "namespace_epilogue": ns_helper.epilogue,
  364. "dispatch_declarations": backend_declarations + autograd_declarations,
  365. "BackendName": backend_name,
  366. "DispatchKey": backend_dispatch_key,
  367. },
  368. )
  369. def gen_dispatcher_registrations(
  370. fm: FileManager,
  371. output_dir: str,
  372. class_name: str,
  373. backend_indices: dict[DispatchKey, BackendIndex],
  374. grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
  375. backend_dispatch_key: DispatchKey,
  376. dispatch_key: DispatchKey,
  377. selector: SelectiveBuilder,
  378. # build_in_tree is true for lazy TS backend and affects include paths, not used for external backends
  379. build_in_tree: bool = False,
  380. per_operator_headers: bool = False,
  381. backend_name: str = "",
  382. eager_registration: bool = True,
  383. ) -> None:
  384. headers = [
  385. f"{output_dir}/{backend_dispatch_key}NativeFunctions.h",
  386. ]
  387. if build_in_tree:
  388. external_backend_headers_str = "\n".join(f"#include <{h}>" for h in headers)
  389. else:
  390. external_backend_headers_str = "\n".join(f'#include "{h}"' for h in headers)
  391. assert class_name is not None
  392. backend_index = backend_indices[dispatch_key]
  393. dispatch_registrations_body = list(
  394. concatMap(
  395. dest.RegisterDispatchKey(
  396. backend_index,
  397. Target.REGISTRATION,
  398. selector,
  399. rocm=False,
  400. symint=True,
  401. class_method_name=f"{class_name}",
  402. skip_dispatcher_op_registration=False,
  403. ),
  404. grouped_native_functions,
  405. )
  406. )
  407. newline = "\n"
  408. ns_helper = NamespaceHelper(namespace_str="at")
  409. deferred_dispatch_registrations = ""
  410. static_init_dispatch_registrations = ""
  411. if eager_registration:
  412. static_template = CodeTemplate(
  413. """\
  414. TORCH_LIBRARY_IMPL(aten, $dispatch_key, m) {
  415. $dispatch_registrations_body
  416. }"""
  417. )
  418. static_init_dispatch_registrations = static_template.substitute(
  419. dispatch_key=dispatch_key,
  420. dispatch_registrations_body=dispatch_registrations_body,
  421. )
  422. else:
  423. deferred_template = CodeTemplate(
  424. """\
  425. TORCH_API void Register${backend_name}${dispatch_key}NativeFunctions();
  426. TORCH_API void Register${backend_name}${dispatch_key}NativeFunctions() {
  427. static auto m = MAKE_TORCH_LIBRARY_IMPL(aten, $dispatch_key);
  428. $dispatch_registrations_body
  429. }"""
  430. )
  431. deferred_dispatch_registrations = deferred_template.substitute(
  432. backend_name=backend_name,
  433. dispatch_key=dispatch_key,
  434. dispatch_registrations_body=dispatch_registrations_body,
  435. )
  436. fm.write_with_template(
  437. f"Register{dispatch_key}.cpp",
  438. "RegisterDispatchKey.cpp",
  439. lambda: {
  440. "extra_cuda_headers": "",
  441. "external_backend_headers": external_backend_headers_str,
  442. "ops_headers": "#include <ATen/Functions.h>"
  443. if not per_operator_headers
  444. else "",
  445. "DispatchKey": dispatch_key,
  446. "dispatch_namespace": dispatch_key.lower(),
  447. "dispatch_headers": dest.gen_registration_headers(
  448. backend_index, per_operator_headers=per_operator_headers, rocm=False
  449. ),
  450. "dispatch_helpers": dest.gen_registration_helpers(backend_index),
  451. "dispatch_definitions": fm.substitute_with_template(
  452. "RegisterDispatchDefinitions.ini",
  453. lambda: {
  454. "ns_prologue": ns_helper.prologue,
  455. "ns_epilogue": ns_helper.epilogue,
  456. "static_init_dispatch_registrations": static_init_dispatch_registrations,
  457. "deferred_dispatch_registrations": deferred_dispatch_registrations,
  458. "dispatch_namespace": dispatch_key.lower(),
  459. "dispatch_namespaced_definitions": "",
  460. "dispatch_anonymous_definitions": list(
  461. concatMap(
  462. dest.RegisterDispatchKey(
  463. backend_index,
  464. Target.ANONYMOUS_DEFINITION,
  465. selector,
  466. rocm=False,
  467. symint=True,
  468. class_method_name=f"{class_name}",
  469. skip_dispatcher_op_registration=False,
  470. ),
  471. grouped_native_functions,
  472. )
  473. ),
  474. },
  475. ).split(newline),
  476. },
  477. )
  478. def run(
  479. source_yaml: str, output_dir: str, dry_run: bool, impl_path: str | None = None
  480. ) -> None:
  481. # Assumes that this file lives at PYTORCH_ROOT/torchgen/gen_backend_stubs.py
  482. pytorch_root = Path(__file__).absolute().parent.parent
  483. template_dir = os.path.join(pytorch_root, "aten/src/ATen/templates")
  484. def make_file_manager(install_dir: str) -> FileManager:
  485. return FileManager(
  486. install_dir=install_dir, template_dir=template_dir, dry_run=dry_run
  487. )
  488. fm = make_file_manager(output_dir)
  489. native_yaml_path = os.path.join(
  490. pytorch_root, "aten/src/ATen/native/native_functions.yaml"
  491. )
  492. tags_yaml_path = os.path.join(pytorch_root, "aten/src/ATen/native/tags.yaml")
  493. parsed_yaml = parse_native_yaml(native_yaml_path, tags_yaml_path)
  494. native_functions, backend_indices = (
  495. parsed_yaml.native_functions,
  496. parsed_yaml.backend_indices,
  497. )
  498. grouped_native_functions = get_grouped_native_functions(native_functions)
  499. parsed_backend_yaml = parse_backend_yaml(
  500. source_yaml, grouped_native_functions, backend_indices
  501. )
  502. backend_key = parsed_backend_yaml.backend_key
  503. autograd_key = parsed_backend_yaml.autograd_key
  504. cpp_namespace = parsed_backend_yaml.cpp_namespace
  505. class_name = parsed_backend_yaml.class_name
  506. backend_indices = parsed_backend_yaml.backend_indices
  507. selector = SelectiveBuilder.get_nop_selector()
  508. if backend_key is None:
  509. # This could be useful if a backend wants to quickly set up a noop yaml file but doesn't have any kernels ready yet.
  510. return
  511. if class_name is None:
  512. # class_name is an optional argument to backend yaml file.
  513. # if specified it allows an external backend to override
  514. # the name of the class that all generated kernel definitions live under.
  515. # if not specified, its value is given as native_function_class_name.
  516. class_name = backend_indices[backend_key].native_function_class_name()
  517. assert class_name is not None
  518. if impl_path is not None:
  519. error_on_missing_kernels(
  520. native_functions,
  521. backend_indices,
  522. backend_key,
  523. autograd_key,
  524. class_name,
  525. impl_path,
  526. )
  527. gen_dispatchkey_nativefunc_headers(
  528. fm,
  529. class_name,
  530. cpp_namespace,
  531. backend_indices,
  532. grouped_native_functions,
  533. backend_key,
  534. autograd_key,
  535. )
  536. for dispatch_key in (
  537. [backend_key] if autograd_key is None else [backend_key, autograd_key]
  538. ):
  539. gen_dispatcher_registrations(
  540. fm,
  541. output_dir,
  542. class_name,
  543. backend_indices,
  544. grouped_native_functions,
  545. backend_key,
  546. dispatch_key,
  547. selector,
  548. )
  549. if __name__ == "__main__":
  550. main()