5
from collections import Counter, defaultdict, namedtuple
6
from typing import Dict, List, Optional, Sequence, Set, Union
10
import torchgen.api.dispatcher as dispatcher
11
import torchgen.dest as dest
12
from torchgen.api.types import DispatcherSignature
13
from torchgen.code_template import CodeTemplate
14
from torchgen.context import native_function_manager
15
from torchgen.gen import get_grouped_native_functions, parse_native_yaml
16
from torchgen.model import (
24
from torchgen.selective_build.selector import SelectiveBuilder
25
from torchgen.utils import concatMap, context, FileManager, NamespaceHelper, Target
26
from torchgen.yaml_utils import YamlLoader
31
ParsedExternalYaml = namedtuple(
33
["backend_key", "autograd_key", "class_name", "cpp_namespace", "backend_indices"],
37
def parse_backend_yaml(
38
backend_yaml_path: str,
39
grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
40
backend_indices: Dict[DispatchKey, BackendIndex],
41
) -> ParsedExternalYaml:
42
native_functions_map: Dict[OperatorName, NativeFunction] = {
45
lambda f: [f] if isinstance(f, NativeFunction) else list(f.functions()),
46
grouped_native_functions,
50
with open(backend_yaml_path) as f:
51
yaml_values = yaml.load(f, Loader=YamlLoader)
52
assert isinstance(yaml_values, dict)
67
backend = yaml_values.pop("backend", None)
68
assert backend is not None, 'You must provide a value for "backend"'
70
class_name = yaml_values.pop("class_name", None)
72
cpp_namespace = yaml_values.pop("cpp_namespace", None)
73
assert cpp_namespace is not None, 'You must provide a value for "cpp_namespace"'
76
use_out_as_primary = yaml_values.pop("use_out_as_primary", False)
78
use_out_as_primary, bool
79
), f"You must provide either True or False for use_out_as_primary. Provided: {use_out_as_primary}"
81
use_device_guard = yaml_values.pop("device_guard", False)
83
use_device_guard, bool
84
), f"You must provide either True or False for device_guard. Provided: {use_device_guard}"
86
supported = yaml_values.pop("supported", [])
91
), f'expected "supported" to be a list, but got: {supported} (of type {type(supported)})'
93
symint = yaml_values.pop("symint", [])
98
), f'expected "symint" to be a list, but got: {supported} (of type {type(supported)})'
99
symint_set = set(symint)
101
supported_autograd = yaml_values.pop("autograd", [])
103
supported_autograd, list
104
), f'expected "autograd" to be a list, but got: {supported_autograd}'
107
full_codegen = yaml_values.pop("full_codegen", [])
108
supported.extend(full_codegen)
111
non_native = yaml_values.pop("non_native", {})
114
_ = yaml_values.pop("ir_gen", {})
117
len(yaml_values.keys()) == 0
118
), f'{backend_yaml_path} contains unexpected keys: {", ".join(yaml_values.keys())}. \
119
Only the following keys are supported: {", ".join(valid_keys)}'
121
def create_backend_index(
122
backend_ops: List[str],
123
symint_ops: Set[str],
124
dispatch_key: DispatchKey,
126
use_out_as_primary: bool,
127
use_device_guard: bool,
129
metadata: Dict[OperatorName, BackendMetadata] = {}
130
for op in backend_ops:
131
op_name = OperatorName.parse(op)
133
op_name in native_functions_map
134
), f"Found an invalid operator name: {op_name}"
136
kernel_name = dispatcher.name(native_functions_map[op_name].func)
138
kernel_name += "_symint"
141
kernel=kernel_name, structured=False, cpp_namespace=cpp_namespace
143
metadata[op_name] = m
145
dispatch_key=dispatch_key,
146
use_out_as_primary=use_out_as_primary,
148
device_guard=use_device_guard,
152
backend_key: Optional[DispatchKey] = None
153
if len(supported) > 0:
155
lambda: f'The provided value for "backend" must be a valid DispatchKey, but got {backend}.'
157
backend_key = DispatchKey.parse(backend)
159
backend_idx = create_backend_index(
163
use_out_as_primary=use_out_as_primary,
164
use_device_guard=use_device_guard,
166
assert backend_key not in backend_indices
167
backend_indices[backend_key] = backend_idx
169
autograd_key: Optional[DispatchKey] = None
170
if len(supported_autograd) > 0:
172
lambda: f'The "autograd" key was specified, which indicates that you would like to override \
173
the behavior of autograd for some operators on your backend. However "Autograd{backend}" is not a valid DispatchKey.'
175
autograd_key = DispatchKey.parse(f"Autograd{backend}")
177
autograd_idx = create_backend_index(
181
use_out_as_primary=use_out_as_primary,
182
use_device_guard=use_device_guard,
184
assert autograd_key not in backend_indices
185
backend_indices[autograd_key] = autograd_idx
187
for g in grouped_native_functions:
188
if isinstance(g, NativeFunction):
191
if backend_key is None
194
for m in [backend_indices[backend_key].get_kernel(g)]
200
if autograd_key is None
203
for m in [backend_indices[autograd_key].get_kernel(g)]
210
if backend_key is None
214
backend_indices[backend_key].get_kernel(f)
215
for f in g.functions()
222
if autograd_key is None
226
backend_indices[autograd_key].get_kernel(f)
227
for f in g.functions()
233
forward_kernels = [f for f in forward_kernels if f is not None]
234
backward_kernels = [f for f in backward_kernels if f is not None]
236
len(forward_kernels) == 0 or len(backward_kernels) == 0
237
), f'Currently, all variants of an op must either be registered to a backend key, or to a backend\'s \
238
autograd key. They cannot be mix and matched. If this is something you need, feel free to create an issue! \
239
{forward_kernels[0].kernel} is listed under "supported", but {backward_kernels[0].kernel} is listed under "autograd".'
241
return ParsedExternalYaml(
242
backend_key, autograd_key, class_name, cpp_namespace, backend_indices
246
def error_on_missing_kernels(
247
native_functions: Sequence[NativeFunction],
248
backend_indices: Dict[DispatchKey, BackendIndex],
249
backend_key: DispatchKey,
250
autograd_key: Optional[DispatchKey],
252
kernel_defn_file_path: str,
253
full_codegen: Optional[List[OperatorName]] = None,
256
with open(kernel_defn_file_path) as f:
257
backend_defns = f.read()
259
raise AssertionError(
260
f"Unable to read from the specified impl_path file: {kernel_defn_file_path}"
263
if full_codegen is None:
266
indices = [backend_indices[backend_key].index] + (
267
[] if autograd_key is None else [backend_indices[autograd_key].index]
271
expected_backend_op_names: Dict[OperatorName, str] = dict(
275
(op_name, metadata.kernel) for op_name, metadata in index.items()
281
expected_backend_native_funcs: List[NativeFunction] = [
283
for f in native_functions
284
if f.func.name in expected_backend_op_names.keys()
285
and f.func.name not in full_codegen
287
expected_backend_kernel_name_counts: Dict[str, List[NativeFunction]] = defaultdict(
290
for native_f in expected_backend_native_funcs:
291
expected_backend_kernel_name_counts[
292
expected_backend_op_names[native_f.func.name]
298
kernel_defn_regex = rf"(.*){class_name}::\s*([\w\d]*)\("
299
actual_backend_kernel_name_counts = Counter(
306
for (x, y) in re.findall(kernel_defn_regex, backend_defns)
307
if not x.endswith(":")
311
missing_kernels_err_msg = ""
312
for expected_name, funcs in expected_backend_kernel_name_counts.items():
313
expected_overload_count = len(funcs)
314
actual_overload_count = actual_backend_kernel_name_counts[expected_name]
315
if expected_overload_count != actual_overload_count:
317
def create_decl(f: NativeFunction) -> str:
318
with native_function_manager(f):
319
return DispatcherSignature.from_schema(f.func).decl()
321
expected_schemas_str = "\n".join([create_decl(f) for f in funcs])
322
missing_kernels_err_msg += f"""
323
{class_name} is missing a kernel definition for {expected_name}. We found {actual_overload_count} kernel(s) with that name,
324
but expected {expected_overload_count} kernel(s). The expected function schemas for the missing operator are:
325
{expected_schemas_str}
328
assert missing_kernels_err_msg == "", missing_kernels_err_msg
332
parser = argparse.ArgumentParser(description="Generate backend stub files")
337
help="path to source yaml file containing operator external definitions",
339
parser.add_argument("-o", "--output-dir", "--output_dir", help="output directory")
341
"--dry-run", "--dry_run", type=bool, default=False, help="output directory"
348
help="path to the source C++ file containing kernel definitions",
350
options = parser.parse_args()
352
run(options.source_yaml, options.output_dir, options.dry_run, options.impl_path)
355
def gen_dispatchkey_nativefunc_headers(
359
backend_indices: Dict[DispatchKey, BackendIndex],
360
grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
361
backend_dispatch_key: DispatchKey,
362
autograd_dispatch_key: Optional[DispatchKey],
363
backend_name: str = "",
365
assert class_name is not None
366
generated_comment = (
367
"Autogenerated file by gen_backend_stubs.py. Do not edit directly!"
373
backend_declarations = sorted(
376
lambda f: dest.compute_native_function_declaration(
377
f, backend_indices[backend_dispatch_key]
379
grouped_native_functions,
383
autograd_declarations = sorted(
387
if autograd_dispatch_key is None
388
else dest.compute_native_function_declaration(
389
f, backend_indices[autograd_dispatch_key]
391
grouped_native_functions,
396
ns_helper = NamespaceHelper(cpp_namespace)
397
fm.write_with_template(
398
f"{backend_dispatch_key}NativeFunctions.h",
399
"DispatchKeyNativeFunctions.h",
401
"generated_comment": generated_comment,
402
"namespace_prologue": ns_helper.prologue,
403
"class_name": class_name,
404
"namespace_epilogue": ns_helper.epilogue,
405
"dispatch_declarations": backend_declarations + autograd_declarations,
406
"BackendName": backend_name,
407
"DispatchKey": backend_dispatch_key,
412
def gen_dispatcher_registrations(
416
backend_indices: Dict[DispatchKey, BackendIndex],
417
grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
418
backend_dispatch_key: DispatchKey,
419
dispatch_key: DispatchKey,
420
selector: "SelectiveBuilder",
422
build_in_tree: bool = False,
423
per_operator_headers: bool = False,
424
backend_name: str = "",
425
eager_registration: bool = True,
428
f"{output_dir}/{backend_dispatch_key}NativeFunctions.h",
431
external_backend_headers_str = "\n".join(f"#include <{h}>" for h in headers)
433
external_backend_headers_str = "\n".join(f'#include "{h}"' for h in headers)
435
assert class_name is not None
436
backend_index = backend_indices[dispatch_key]
438
dispatch_registrations_body = list(
440
dest.RegisterDispatchKey(
446
class_method_name=f"{class_name}",
447
skip_dispatcher_op_registration=False,
449
grouped_native_functions,
453
ns_helper = NamespaceHelper(namespace_str="at")
454
deferred_dispatch_registrations = ""
455
static_init_dispatch_registrations = ""
456
if eager_registration:
457
static_template = CodeTemplate(
459
TORCH_LIBRARY_IMPL(aten, $dispatch_key, m) {
460
$dispatch_registrations_body
463
static_init_dispatch_registrations = static_template.substitute(
464
dispatch_key=dispatch_key,
465
dispatch_registrations_body=dispatch_registrations_body,
468
deferred_template = CodeTemplate(
470
TORCH_API void Register${backend_name}${dispatch_key}NativeFunctions();
471
TORCH_API void Register${backend_name}${dispatch_key}NativeFunctions() {
472
static auto m = MAKE_TORCH_LIBRARY_IMPL(aten, $dispatch_key);
473
$dispatch_registrations_body
476
deferred_dispatch_registrations = deferred_template.substitute(
477
backend_name=backend_name,
478
dispatch_key=dispatch_key,
479
dispatch_registrations_body=dispatch_registrations_body,
482
fm.write_with_template(
483
f"Register{dispatch_key}.cpp",
484
"RegisterDispatchKey.cpp",
486
"extra_cuda_headers": "",
487
"external_backend_headers": external_backend_headers_str,
488
"ops_headers": "#include <ATen/Functions.h>"
489
if not per_operator_headers
491
"DispatchKey": dispatch_key,
492
"dispatch_namespace": dispatch_key.lower(),
493
"dispatch_headers": dest.gen_registration_headers(
494
backend_index, per_operator_headers=per_operator_headers, rocm=False
496
"dispatch_definitions": fm.substitute_with_template(
497
"RegisterDispatchDefinitions.ini",
499
"ns_prologue": ns_helper.prologue,
500
"ns_epilogue": ns_helper.epilogue,
501
"static_init_dispatch_registrations": static_init_dispatch_registrations,
502
"deferred_dispatch_registrations": deferred_dispatch_registrations,
503
"dispatch_helpers": dest.gen_registration_helpers(backend_index),
504
"dispatch_namespace": dispatch_key.lower(),
505
"dispatch_namespaced_definitions": "",
506
"dispatch_anonymous_definitions": list(
508
dest.RegisterDispatchKey(
510
Target.ANONYMOUS_DEFINITION,
514
class_method_name=f"{class_name}",
515
skip_dispatcher_op_registration=False,
517
grouped_native_functions,
527
source_yaml: str, output_dir: str, dry_run: bool, impl_path: Optional[str] = None
530
pytorch_root = pathlib.Path(__file__).parent.parent.absolute()
531
template_dir = os.path.join(pytorch_root, "aten/src/ATen/templates")
533
def make_file_manager(install_dir: str) -> FileManager:
535
install_dir=install_dir, template_dir=template_dir, dry_run=dry_run
538
fm = make_file_manager(output_dir)
540
native_yaml_path = os.path.join(
541
pytorch_root, "aten/src/ATen/native/native_functions.yaml"
543
tags_yaml_path = os.path.join(pytorch_root, "aten/src/ATen/native/tags.yaml")
544
parsed_yaml = parse_native_yaml(native_yaml_path, tags_yaml_path)
545
native_functions, backend_indices = (
546
parsed_yaml.native_functions,
547
parsed_yaml.backend_indices,
549
grouped_native_functions = get_grouped_native_functions(native_functions)
550
parsed_backend_yaml = parse_backend_yaml(
551
source_yaml, grouped_native_functions, backend_indices
553
backend_key = parsed_backend_yaml.backend_key
554
autograd_key = parsed_backend_yaml.autograd_key
555
cpp_namespace = parsed_backend_yaml.cpp_namespace
556
class_name = parsed_backend_yaml.class_name
557
backend_indices = parsed_backend_yaml.backend_indices
559
selector = SelectiveBuilder.get_nop_selector()
561
if backend_key is None:
565
if class_name is None:
570
class_name = backend_indices[backend_key].native_function_class_name()
571
assert class_name is not None
573
if impl_path is not None:
574
error_on_missing_kernels(
583
gen_dispatchkey_nativefunc_headers(
588
grouped_native_functions,
593
for dispatch_key in (
594
[backend_key] if autograd_key is None else [backend_key, autograd_key]
596
gen_dispatcher_registrations(
601
grouped_native_functions,
608
if __name__ == "__main__":