有device参数的API使用模板生成

This commit is contained in:
shibo19
2022-05-24 22:00:01 +08:00
parent f764203bc7
commit 2bfabedc7b
9 changed files with 534 additions and 59 deletions
+128 -13
View File
@@ -21,11 +21,17 @@
import argparse
from importlib.resources import open_binary
import re
from collections import defaultdict, namedtuple
from typing import Dict, Optional, List, Tuple, Set, Sequence, Callable
import yaml
try:
# use faster C loader if available
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader # type: ignore
from codegen.code_template import CodeTemplate
from codegen.api import cpp
@@ -55,7 +61,7 @@ _SKIP_PYTHON_BINDINGS = [
'.*_backward', '.*_backward_(out|input|weight|bias)', '.*_forward',
'.*_forward_out', '_unsafe_view', 'tensor', '_?sparse_coo_tensor.*',
'_?sparse_csr_tensor.*',
'_arange.*', '_range.*', 'linspace.*', 'logspace.*',
'_arange.*', '_range.*', '_linspace.*', '_logspace.*',
'_sparse_add_out', '_sparse_div.*', '_sparse_mul.*', '_sparse_sub.*', '_sparse_dense_add_out',
'index', 'unique_dim_consecutive',
'_cumsum.*', '_cumprod.*', '_sum.*', '_prod.*',
@@ -75,6 +81,7 @@ _SKIP_PYTHON_BINDINGS = [
'_fw_primal', 'fake_quantize_per_tensor_affine_cachemask',
'fake_quantize_per_channel_affine_cachemask',
'_reshape_alias',
'_cudnn.*', '.*_quantized', 'fft_.*',
]
SKIP_PYTHON_BINDINGS = list(map(lambda pattern: re.compile(rf'^{pattern}$'), _SKIP_PYTHON_BINDINGS))
@@ -166,6 +173,7 @@ def group_filter_overloads(
def create_python_bindings(
fm: FileManager,
pairs: Sequence[PythonSignatureNativeFunctionPair],
pairs_device: Sequence[PythonSignatureNativeFunctionPair],
pred: Callable[[NativeFunction], bool],
module: Optional[str],
filename: str,
@@ -176,8 +184,12 @@ def create_python_bindings(
py_methods: List[str] = []
py_method_defs: List[str] = []
py_forwards: List[str] = []
py_device_methods: List[str] = []
py_device_forwards: List[str] = []
py_device_method_defs: List[str] = []
grouped = group_filter_overloads(pairs, pred)
grouped_device = group_filter_overloads(pairs_device, pred)
for name in sorted(grouped.keys(), key=lambda x: str(x)):
overloads = grouped[name]
@@ -185,14 +197,66 @@ def create_python_bindings(
py_method_defs.append(method_def(name, module, overloads, method=method))
py_forwards.extend(forward_decls(name, overloads, method=method))
for name in sorted(grouped_device.keys(), key=lambda x: str(x)):
overloads = grouped_device[name]
py_device_methods.append(method_impl(name, module, overloads, method=method, custom=False))
py_device_method_defs.append(method_def(name, module, overloads, method=method))
py_device_forwards.extend(forward_decls(name, overloads, method=method))
fm.write_with_template(filename, filename, lambda: {
'generated_comment': '@' + f'generated from {fm.template_dir}/{filename}',
'py_forwards': py_forwards,
'py_methods': py_methods,
'py_device_methods': py_device_methods,
'py_method_defs': py_method_defs,
'py_device_forwards': py_device_forwards,
'py_device_method_defs': py_device_method_defs,
})
def create_python_device_bindings(
fm: FileManager,
pairs: Sequence[PythonSignatureNativeFunctionPair],
pred: Callable[[NativeFunction], bool],
module: Optional[str],
filename: str,
*,
method: bool,
) -> None:
"""Generates Python bindings to ATen functions"""
py_device_method_defs: List[str] = []
grouped = group_filter_overloads(pairs, pred)
PY_DEVICE_METHOD_DEF = CodeTemplate("""\
torch.${name} = torch_npu.${name}
""")
def method_device_def(name):
return PY_DEVICE_METHOD_DEF.substitute(name=name)
for name in sorted(grouped.keys(), key=lambda x: str(x)):
py_device_method_defs.append(method_device_def(name))
fm.write_with_template(filename, filename, lambda: {
'device_methods_def_py': py_device_method_defs,
})
def query_methods(filepath):
with open(filepath, 'r', encoding='UTF-8') as f:
read_lines = f.readlines()
def_methods = []
for read_line in read_lines:
if read_line.startswith("def"):
def_methods.append((read_line[4:read_line.index("(")]).strip())
return def_methods
device_methods = query_methods(fm.install_dir + filename)
if len(device_methods) != len(set(device_methods)):
raise RuntimeError("In device methods file " +
str(fm.install_dir + filename) + " has multi-definition function.")
def load_signatures(
native_functions: List[NativeFunction],
*,
@@ -321,7 +385,8 @@ def method_impl(
module: Optional[str],
overloads: Sequence[PythonSignatureNativeFunctionPair],
*,
method: bool
method: bool,
custom: bool = True
) -> str:
"""
Generate a python binding for all overloads of an op.
@@ -346,7 +411,7 @@ def method_impl(
for overload_index, overload in enumerate(grouped_overloads):
overload_signature = overload.signature.signature_str()
signatures.append(f'{cpp_string(str(overload_signature))},')
dispatch_body = emit_dispatch_case(overload, namedtuple_typenames)
dispatch_body = emit_dispatch_case(overload, namedtuple_typenames, custom)
dispatch.append(
PY_VARIABLE_CASE.substitute(overload_index=overload_index, body=dispatch_body)
if not is_singleton else dispatch_body)
@@ -382,6 +447,7 @@ if (_r.isNone(${out_idx})) {
def emit_dispatch_case(
overload: PythonSignatureGroup,
namedtuple_typenames: Dict[str, str],
custom: bool = True
) -> str:
"""
Emit dispatching code for a single parsed signature. This corresponds to either
@@ -394,14 +460,14 @@ def emit_dispatch_case(
return PY_VARIABLE_OUT.substitute(
out_idx=overload.signature.output_idx(),
call_dispatch=emit_single_dispatch(
overload.signature, overload.base, namedtuple_typenames),
overload.signature, overload.base, namedtuple_typenames, custom),
call_dispatch_out=emit_single_dispatch(
overload.signature, overload.outplace, namedtuple_typenames),
overload.signature, overload.outplace, namedtuple_typenames, custom),
)
else:
# no-output version only
return emit_single_dispatch(
overload.signature, overload.base, namedtuple_typenames)
overload.signature, overload.base, namedtuple_typenames, custom)
def forward_decls(
@@ -558,7 +624,7 @@ def sort_overloads(
def emit_single_dispatch(
ps: PythonSignature, f: NativeFunction, namedtuple_typenames: Dict[str, str]
ps: PythonSignature, f: NativeFunction, namedtuple_typenames: Dict[str, str], custom = True
) -> str:
"""
Emit dispatch code for a single native function.
@@ -570,18 +636,29 @@ def emit_single_dispatch(
# dispatch lambda signature
name = cpp.name(f.func)
lambda_formals = ', '.join(map(lambda a: f"{a.type_str} {a.name}",
if custom:
lambda_formals = ', '.join(map(lambda a: f"{a.type_str} {a.name}",
dispatch_lambda_args(ps, f, True)))
else:
lambda_formals = ', '.join(map(lambda a: f"{a.type_str} {a.name}",
dispatch_lambda_args(ps, f, False)))
lambda_return = dispatch_lambda_return_str(f)
# dispatch lambda body
record_func_define = cpp_record_func(f, custom=True)
dispatch_callee = cpp_dispatch_target(f, custom=True)
dispatch_args = ', '.join(cpp_dispatch_exprs(f, python_signature=ps, faithful=True))
record_func_define = cpp_record_func(f, custom=custom)
dispatch_callee = cpp_dispatch_target(f, custom=custom)
if custom:
dispatch_args = ', '.join(cpp_dispatch_exprs(f, python_signature=ps, faithful=True))
else:
dispatch_args = ', '.join(cpp_dispatch_exprs(f, python_signature=ps, faithful=False))
# from arg parser outputs to dispatch lambda arguments
parser_outputs = arg_parser_output_exprs(ps, f)
lambda_arg_exprs = dispatch_lambda_exprs(ps, f, True)
if custom:
lambda_arg_exprs = dispatch_lambda_exprs(ps, f, True)
else:
lambda_arg_exprs = dispatch_lambda_exprs(ps, f, False)
inits = '\n'.join(lambda_arg_exprs.inits)
lambda_args = ', '.join(lambda_arg_exprs.exprs)
@@ -618,6 +695,32 @@ return wrap({namedtuple_typeref}dispatch_{name}({lambda_args}){set_requires_grad
return go(f)
class LineLoader(Loader):
def construct_mapping(self, node, deep=False): # type: ignore
mapping = super().construct_mapping(node, deep=deep) # type: ignore
# Add 1 so line numbering starts at 1
mapping['__line__'] = node.start_mark.line + 1
return mapping
# Parse native_functions.yaml into a sequence of NativeFunctions
def parse_native_yaml(path: str) -> List[NativeFunction]:
from io import StringIO
f_str = StringIO()
with open(path, 'r') as f:
for line in f:
f_str.write(line)
f_str.seek(0)
es = yaml.safe_load(f_str)
assert isinstance(es, list)
rs: List[NativeFunction] = []
for e in es:
funcs = e.get('func')
if "Device" not in funcs:
continue
with context(lambda: f'in {path}:\n {funcs}'):
func, m = NativeFunction.from_yaml(e)
func.variants.discard(Variant.method)
rs.append(func)
return rs
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Generate functions binding files')
@@ -625,6 +728,10 @@ if __name__ == "__main__":
'-s',
'--source_yaml',
help='path to source yaml file containing operator external definitions')
parser.add_argument(
'-n',
'--native_yaml',
help='path to native yaml file containing operator external definitions with device arugment')
parser.add_argument(
'-o', '--output_dir', help='output directory')
parser.add_argument(
@@ -636,5 +743,13 @@ if __name__ == "__main__":
valid_native_functions = list(filter(should_generate_py_binding, parsed_native_functions))
functions = load_signatures(valid_native_functions, method=False)
create_python_bindings(file_manager, functions, lambda f: Variant.function in f.variants,
torch_native_functions = list(filter(should_generate_py_binding, parse_native_yaml(options.native_yaml)))
device_native_functions = load_signatures(torch_native_functions, method=False)
create_python_bindings(file_manager, functions, device_native_functions, lambda f: Variant.function in f.variants,
'torch_npu', 'python_custom_functions.cpp', method=False)
file_device_manager=FileManager(install_dir=options.output_dir +"../../utils/",
template_dir=options.template_path, dry_run=False)
create_python_device_bindings(file_device_manager, device_native_functions,
lambda f: Variant.function in f.variants, 'torch_npu', 'torch_funcs.py', method=False)