已合并
[feature] add torchnpugen packages #30025
梁松伟创建于 1月26日
[feature] add torchnpugen packages #30025
已合并
梁松伟创建于 1月26日
31 个文件变更+844-844
@@ -16,7 +16,7 @@ from distutils import file_util
16# Disable autoloading before running 'import torch' to avoid circular dependencies16# Disable autoloading before running 'import torch' to avoid circular dependencies
17os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0"17os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0"
18 18 
19-from codegen.utils import PathManager19+from torchnpugen.utils import PathManager
20 20 
21BASE_DIR = os.path.dirname(os.path.abspath(__file__))21BASE_DIR = os.path.dirname(os.path.abspath(__file__))
22PathManager.check_directory_path_readable(os.path.join(BASE_DIR, "version.txt"))22PathManager.check_directory_path_readable(os.path.join(BASE_DIR, "version.txt"))
@@ -23,19 +23,19 @@ testing_source_yaml="$CDIR/test/ops_unsupport_list.yaml"
23 23 
24op_plugin_functions_yaml_path="$op_plugin_config_path/npu_native_functions.yaml"24op_plugin_functions_yaml_path="$op_plugin_config_path/npu_native_functions.yaml"
25 25 
26-${python_execute} -m codegen.gen_backend_stubs \26+${python_execute} -m torchnpugen.gen_backend_stubs \
27 --output_dir="torch_npu/csrc/aten" \27 --output_dir="torch_npu/csrc/aten" \
28 --source_yaml="$source_yaml" \28 --source_yaml="$source_yaml" \
29 --impl_path="$CDIR/torch_npu/csrc/aten" \29 --impl_path="$CDIR/torch_npu/csrc/aten" \
30 --op_plugin_impl_path="$CDIR/third_party/op-plugin/op_plugin/ops" \30 --op_plugin_impl_path="$CDIR/third_party/op-plugin/op_plugin/ops" \
31 --op_plugin_yaml_path="$op_plugin_config_path/op_plugin_functions.yaml"31 --op_plugin_yaml_path="$op_plugin_config_path/op_plugin_functions.yaml"
32 32 
33-${python_execute} -m codegen.autograd.gen_autograd \33+${python_execute} -m torchnpugen.autograd.gen_autograd \
34 --out_dir="$CDIR/torch_npu/csrc/aten" \34 --out_dir="$CDIR/torch_npu/csrc/aten" \
35- --autograd_dir="$CDIR/codegen/autograd" \35+ --autograd_dir="$CDIR/torchnpugen/autograd" \
36 --npu_native_function_dir="$source_yaml"36 --npu_native_function_dir="$source_yaml"
37 37 
38-${python_execute} -m codegen.codegen_ops_info38+${python_execute} -m torchnpugen.codegen_ops_info
39 39 
40if [ -f $CDIR/third_party/op-plugin/codegen/templates/_op_plugin_docs.py ]; then40if [ -f $CDIR/third_party/op-plugin/codegen/templates/_op_plugin_docs.py ]; then
41 if [ -f $CDIR/torch_npu/_op_plugin_docs.py ]; then41 if [ -f $CDIR/torch_npu/_op_plugin_docs.py ]; then
@@ -29,7 +29,7 @@ from wheel.bdist_wheel import bdist_wheel
29# Disable autoloading before running 'import torch' to avoid circular dependencies29# Disable autoloading before running 'import torch' to avoid circular dependencies
30os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0"30os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0"
31 31 
32-from codegen.utils import PathManager32+from torchnpugen.utils import PathManager
33 33 
34BASE_DIR = os.path.dirname(os.path.realpath(__file__))34BASE_DIR = os.path.dirname(os.path.realpath(__file__))
35THIRD_PARTY_PATH = os.path.join(BASE_DIR, "third_party")35THIRD_PARTY_PATH = os.path.join(BASE_DIR, "third_party")
Rcodegen/__init__.pytorchnpugen/__init__.py+27-27
@@ -1,27 +1,27 @@
1-import os1+import os
2-import stat2+import stat
3- 3+ 
4-import torchgen.gen4+import torchgen.gen
5-from codegen.utils import PathManager5+from torchnpugen.utils import PathManager
6- 6+ 
7- 7+ 
8-def _write_if_changed_security(self, filename: str, contents: str) -> None:8+def _write_if_changed_security(self, filename: str, contents: str) -> None:
AtlasAccount
AtlasAccountAtlasAccount1月26日

函数设计: 函数 _write_if_changed_security 被定义为接受 self 参数,但从上下文看它被赋值给 torchgen.gen.FileManager._write_if_changed,这意味着它应该是一个实例方法。然而,函数内部并没有使用 self 参数,这可能导致混淆。如果它确实需要作为实例方法,应该使用 self 参数;否则,应该移除 self 参数。

问题类型: 函数设计 文件路径: torchnpugen/__init__.py 行号: 8 问题代码:

def _write_if_changed_security(self, filename: str, contents: str) -> None:

修改建议:

如果 `_write_if_changed_security` 需要作为 `FileManager` 的实例方法,请确保在函数内部使用 `self` 参数(例如,访问实例属性)。否则,移除 `self` 参数,将其定义为普通函数。

此评论由代码审查工具自动生成

likedislike
9- old_contents: Optional[str]9+ old_contents: Optional[str]
AtlasAccount
AtlasAccountAtlasAccount1月26日

变量和数据类型问题: 函数 _write_if_changed_security 中声明了 old_contents: Optional[str],但 Optional 类型未导入。这可能导致类型检查错误或运行时错误(如果使用严格类型检查)。

问题类型: 变量和数据类型问题 文件路径: torchnpugen/__init__.py 行号: 9 问题代码:

old_contents: Optional[str]

修改建议:

在文件顶部添加 `from typing import Optional` 以导入 `Optional` 类型。

此评论由代码审查工具自动生成

likedislike
10- filepath = os.path.realpath(filename)10+ filepath = os.path.realpath(filename)
11- try:11+ try:
12- with open(filepath, 'r') as f:12+ with open(filepath, 'r') as f:
13- old_contents = f.read()13+ old_contents = f.read()
14- except IOError:14+ except IOError:
15- old_contents = None15+ old_contents = None
16- if contents != old_contents:16+ if contents != old_contents:
17- PathManager.remove_path_safety(filepath)17+ PathManager.remove_path_safety(filepath)
18- with os.fdopen(os.open(filepath, os.O_RDWR | os.O_CREAT, stat.S_IWUSR | stat.S_IRUSR), "w") as f:18+ with os.fdopen(os.open(filepath, os.O_RDWR | os.O_CREAT, stat.S_IWUSR | stat.S_IRUSR), "w") as f:
AtlasAccount
AtlasAccountAtlasAccount1月26日

安全问题: 在创建文件时,使用了权限 stat.S_IWUSR | stat.S_IRUSR(用户读写),但后续通过 os.chmod 将权限更改为 stat.S_IRUSR | stat.S_IEXEC | stat.S_IRGRP | stat.S_IXGRP(用户读和执行,组读和执行)。这可能导致文件在创建后短暂时间内具有不安全的权限(用户可写),存在安全风险,尤其是在多用户环境中。

问题类型: 安全问题 文件路径: torchnpugen/__init__.py 行号: 18 问题代码:

with os.fdopen(os.open(filepath, os.O_RDWR | os.O_CREAT, stat.S_IWUSR | stat.S_IRUSR), "w") as f:
    f.write(contents)
os.chmod(filepath, stat.S_IRUSR | stat.S_IEXEC | stat.S_IRGRP | stat.S_IXGRP)

修改建议:

直接在 `os.open` 中使用最终所需的权限,避免权限更改的间隙。将 `os.open` 的权限参数改为 `stat.S_IRUSR | stat.S_IEXEC | stat.S_IRGRP | stat.S_IXGRP`,并移除 `os.chmod` 调用。注意:这可能会影响文件写入,因为初始权限不包括写权限。如果需要写入,可以临时添加写权限,但建议重新设计以避免安全漏洞。

此评论由代码审查工具自动生成

likedislike
19- f.write(contents)19+ f.write(contents)
20- os.chmod(filepath, stat.S_IRUSR | stat.S_IEXEC | stat.S_IRGRP | stat.S_IXGRP)20+ os.chmod(filepath, stat.S_IRUSR | stat.S_IEXEC | stat.S_IRGRP | stat.S_IXGRP)
21- 21+ 
22- 22+ 
23-def apply_codegen_patches():23+def apply_codegen_patches():
24- torchgen.gen.FileManager._write_if_changed = _write_if_changed_security24+ torchgen.gen.FileManager._write_if_changed = _write_if_changed_security
25- 25+
26- 26+ 
27-apply_codegen_patches()27+apply_codegen_patches()
Rcodegen/autograd/__init__.pytorchnpugen/autograd/__init__.py+2-2
@@ -20,8 +20,8 @@ from torchgen.model import (
20 TensorOptionsArguments20 TensorOptionsArguments
21)21)
22from torchgen.api.types import Binding22from torchgen.api.types import Binding
23-from codegen.gen_backend_stubs import parse_native_and_custom_yaml23+from torchnpugen.gen_backend_stubs import parse_native_and_custom_yaml
24-from codegen.utils import CUSTOM_YAML_NAME24+from torchnpugen.utils import CUSTOM_YAML_NAME
25 25 
26 26 
27def parse_native_and_custom_yaml_(*args, **kwargs):27def parse_native_and_custom_yaml_(*args, **kwargs):
Rcodegen/autograd/gen_autograd.pytorchnpugen/autograd/gen_autograd.py+3-3
@@ -2,10 +2,10 @@
2To run this file by hand from the root of the PyTorch2To run this file by hand from the root of the PyTorch
3repository, run:3repository, run:
4 4 
5-python -m codegen.autograd.gen_autograd \5+python -m torchnpugen.autograd.gen_autograd \
6 --npu_native_function_dir="./torch_npu/csrc/aten/npu_native_functions.yaml" \6 --npu_native_function_dir="./torch_npu/csrc/aten/npu_native_functions.yaml" \
7 --out_dir=$OUTPUT_DIR \7 --out_dir=$OUTPUT_DIR \
8- --autograd_dir="./codegen/autograd/"8+ --autograd_dir="./torchnpugen/autograd/"
9 9 
10Where $OUTPUT_DIR is where you would like the files to be10Where $OUTPUT_DIR is where you would like the files to be
11generated. In the full build system, OUTPUT_DIR is11generated. In the full build system, OUTPUT_DIR is
@@ -24,7 +24,7 @@ import os
24from torchgen.packaged.autograd.gen_inplace_or_view_type import gen_inplace_or_view_type24from torchgen.packaged.autograd.gen_inplace_or_view_type import gen_inplace_or_view_type
25from torchgen.packaged.autograd.gen_autograd_functions import gen_autograd_functions_lib25from torchgen.packaged.autograd.gen_autograd_functions import gen_autograd_functions_lib
26 26 
27-from codegen.utils import get_torchgen_dir, gen_custom_yaml_path27+from torchnpugen.utils import get_torchgen_dir, gen_custom_yaml_path
28from .gen_variable_type import (28from .gen_variable_type import (
29 gen_variable_type, gen_variable_type_head29 gen_variable_type, gen_variable_type_head
30)30)
Rcodegen/autograd/gen_autograd_functions.pytorchnpugen/autograd/gen_autograd_functions.py+0-0
文件重命名但无更改。
Rcodegen/autograd/gen_variable_factories.pytorchnpugen/autograd/gen_variable_factories.py+0-0
文件重命名但无更改。
Rcodegen/autograd/gen_variable_type.pytorchnpugen/autograd/gen_variable_type.py+0-0
文件重命名但无更改。
Rcodegen/autograd/templates/ADInplaceOrViewType.cpptorchnpugen/autograd/templates/ADInplaceOrViewType.cpp+0-0
文件重命名但无更改。
Rcodegen/autograd/templates/Functions.cpptorchnpugen/autograd/templates/Functions.cpp+0-0
文件重命名但无更改。
Rcodegen/autograd/templates/Functions.htorchnpugen/autograd/templates/Functions.h+0-0
文件重命名但无更改。
Rcodegen/autograd/templates/VariableType.cpptorchnpugen/autograd/templates/VariableType.cpp+0-0
文件重命名但无更改。
Rcodegen/autograd/templates/VariableType.htorchnpugen/autograd/templates/VariableType.h+0-0
文件重命名但无更改。
Rcodegen/autograd/templates/python_functions.cpptorchnpugen/autograd/templates/python_functions.cpp+0-0
文件重命名但无更改。
Rcodegen/autograd/templates/python_functions.htorchnpugen/autograd/templates/python_functions.h+0-0
文件重命名但无更改。
Rcodegen/autograd/utils.pytorchnpugen/autograd/utils.py+2-2
@@ -9,8 +9,8 @@ from torchgen.api.autograd import (
9)9)
10from torchgen.packaged.autograd.load_derivatives import load_derivatives10from torchgen.packaged.autograd.load_derivatives import load_derivatives
11 11 
12-from codegen.utils import get_torchgen_dir, CUSTOM_YAML_NAME, PathManager12+from torchnpugen.utils import get_torchgen_dir, CUSTOM_YAML_NAME, PathManager
13-from codegen.gen_backend_stubs import parse_native_and_custom_yaml13+from torchnpugen.gen_backend_stubs import parse_native_and_custom_yaml
14 14 
15 15 
16AUTOGRAD_BLACK_LIST = {'npu_format_cast.Tensor', 'npu_format_cast_', 'npu_format_cast_.acl_format'}16AUTOGRAD_BLACK_LIST = {'npu_format_cast.Tensor', 'npu_format_cast_', 'npu_format_cast_.acl_format'}
Rcodegen/codegen_ops_info.pytorchnpugen/codegen_ops_info.py+3-3
@@ -9,8 +9,8 @@ import yaml
9from torchgen.code_template import CodeTemplate9from torchgen.code_template import CodeTemplate
10from torchgen.gen import FileManager10from torchgen.gen import FileManager
11 11 
12-from codegen.autograd.utils import VERSION_PART12+from torchnpugen.autograd.utils import VERSION_PART
13-from codegen.utils import PathManager13+from torchnpugen.utils import PathManager
14 14 
15project_path = Path(os.path.dirname(__file__)).parent15project_path = Path(os.path.dirname(__file__)).parent
16op_plugin_info_path = os.path.realpath(os.path.join(16op_plugin_info_path = os.path.realpath(os.path.join(
@@ -96,7 +96,7 @@ def gen_ops_info(summary_dict):
96 skip_template = CodeTemplate(96 skip_template = CodeTemplate(
97 """\n'${op_name}': [${decorators}]"""97 """\n'${op_name}': [${decorators}]"""
98 )98 )
99- fm = FileManager(os.path.join("torch_npu", "testing"), os.path.join("codegen", "templates"), False)99+ fm = FileManager(os.path.join("torch_npu", "testing"), os.path.join("torchnpugen", "templates"), False)
100 100 
101 fm.write_with_template(f"_npu_testing_utils.py", "npu_testing_utils.py", lambda:{101 fm.write_with_template(f"_npu_testing_utils.py", "npu_testing_utils.py", lambda:{
102 "skip_detail": [skip_template.substitute(op_name=op, decorators=doc) for op, doc in skip_list.items()]102 "skip_detail": [skip_template.substitute(op_name=op, decorators=doc) for op, doc in skip_list.items()]
Rcodegen/custom_functions.pytorchnpugen/custom_functions.py+1-1
@@ -13,7 +13,7 @@ from torchgen.context import with_native_function, native_function_manager, meth
13from torchgen.api.types import DispatcherSignature13from torchgen.api.types import DispatcherSignature
14from torchgen.api import cpp14from torchgen.api import cpp
15from torchgen.dest.register_dispatch_key import RegisterDispatchKey15from torchgen.dest.register_dispatch_key import RegisterDispatchKey
16-from codegen.utils import (enable_opplugin, is_op_valid, field_tag, get_opplugin_wrap_name, parse_npu_yaml,16+from torchnpugen.utils import (enable_opplugin, is_op_valid, field_tag, get_opplugin_wrap_name, parse_npu_yaml,
17 gen_op_hook_post_code)17 gen_op_hook_post_code)
18 18 
19 19 
Rcodegen/gen_backend_stubs.pytorchnpugen/gen_backend_stubs.py+799-799
@@ -1,799 +1,799 @@
1-# Copyright (c) 2020 Huawei Technologies Co., Ltd1+# Copyright (c) 2020 Huawei Technologies Co., Ltd
2-# Copyright (c) 2019, Facebook CORPORATION.2+# Copyright (c) 2019, Facebook CORPORATION.
3-# All rights reserved.3+# All rights reserved.
4-#4+#
5-# Licensed under the BSD 3-Clause License (the "License");5+# Licensed under the BSD 3-Clause License (the "License");
6-# you may not use this file except in compliance with the License.6+# you may not use this file except in compliance with the License.
7-# You may obtain a copy of the License at7+# You may obtain a copy of the License at
8-#8+#
9-# https://opensource.org/licenses/BSD-3-Clause9+# https://opensource.org/licenses/BSD-3-Clause
10-#10+#
11-# Unless required by applicable law or agreed to in writing, software11+# Unless required by applicable law or agreed to in writing, software
12-# distributed under the License is distributed on an "AS IS" BASIS,12+# distributed under the License is distributed on an "AS IS" BASIS,
13-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14-# See the License for the specific language governing permissions and14+# See the License for the specific language governing permissions and
15-# limitations under the License.15+# limitations under the License.
16- 16+ 
17-import pathlib17+import pathlib
18-import argparse18+import argparse
19-import os19+import os
20-import stat20+import stat
21-import re21+import re
22-from collections import namedtuple, Counter, defaultdict22+from collections import namedtuple, Counter, defaultdict
23-from typing import List, Dict, Union, Sequence, Optional, Set, Callable23+from typing import List, Dict, Union, Sequence, Optional, Set, Callable
24-import yaml24+import yaml
25- 25+ 
26-import torchgen26+import torchgen
27-from torchgen.code_template import CodeTemplate27+from torchgen.code_template import CodeTemplate
28-from torchgen.gen import (parse_tags_yaml, FileManager, parse_native_yaml,28+from torchgen.gen import (parse_tags_yaml, FileManager, parse_native_yaml,
29- get_grouped_native_functions, error_check_native_functions)29+ get_grouped_native_functions, error_check_native_functions)
30-from torchgen.model import (BackendIndex, DispatchKey,30+from torchgen.model import (BackendIndex, DispatchKey,
31- NativeFunction, NativeFunctionsGroup, OperatorName,31+ NativeFunction, NativeFunctionsGroup, OperatorName,
32- BackendMetadata, is_cuda_dispatch_key)32+ BackendMetadata, is_cuda_dispatch_key)
33-from torchgen.native_function_generation import add_generated_native_functions33+from torchgen.native_function_generation import add_generated_native_functions
34-from torchgen.selective_build.selector import SelectiveBuilder34+from torchgen.selective_build.selector import SelectiveBuilder
35-from torchgen.utils import Target, concatMap, context, NamespaceHelper35+from torchgen.utils import Target, concatMap, context, NamespaceHelper
36-import torchgen.dest as dest36+import torchgen.dest as dest
37-import torchgen.api.dispatcher as dispatcher37+import torchgen.api.dispatcher as dispatcher
38-import torchgen.api.native as native38+import torchgen.api.native as native
39-from torchgen.api.cpp import JIT_TO_CPP_DEFAULT39+from torchgen.api.cpp import JIT_TO_CPP_DEFAULT
40-from torchgen.gen_backend_stubs import gen_dispatchkey_nativefunc_headers40+from torchgen.gen_backend_stubs import gen_dispatchkey_nativefunc_headers
41-from codegen.gen_functionalization_type import gen_functionalization_definition, gen_functionalization_registration41+from torchnpugen.gen_functionalization_type import gen_functionalization_definition, gen_functionalization_registration
42- 42+ 
43-from codegen.utils import (get_torchgen_dir, rename_privateuse1_dispatch_key, gen_unstructured, add_header_to_template_file,43+from torchnpugen.utils import (get_torchgen_dir, rename_privateuse1_dispatch_key, gen_unstructured, add_header_to_template_file,
44- get_grouped_native_functions_optional_out, parse_npu_yaml, get_opplugin_wrap_name,44+ get_grouped_native_functions_optional_out, parse_npu_yaml, get_opplugin_wrap_name,
45- get_target_functions, merge_custom_yaml, field_tag, gen_custom_yaml_path,45+ get_target_functions, merge_custom_yaml, field_tag, gen_custom_yaml_path,
46- update_opapi_info, is_opapi, update_internal_format_opapi_info, PathManager, filt_exposed_api, get_target_native_registration,46+ update_opapi_info, is_opapi, update_internal_format_opapi_info, PathManager, filt_exposed_api, get_target_native_registration,
47- NativeFunctionsGroupOptionalOut, gen_device_check, filt_compositeimplicitautograd_api,47+ NativeFunctionsGroupOptionalOut, gen_device_check, filt_compositeimplicitautograd_api,
48- DEVICE_NOCHECK_SET)48+ DEVICE_NOCHECK_SET)
49-from codegen.custom_functions import (parse_custom_yaml, gen_custom_trace, gen_custom_ops_patch,49+from torchnpugen.custom_functions import (parse_custom_yaml, gen_custom_trace, gen_custom_ops_patch,
50- gen_custom_functions_dispatch)50+ gen_custom_functions_dispatch)
51- 51+ 
52-torchgen.model.dispatch_keys.append(torchgen.model.DispatchKey.AutogradPrivateUse1)52+torchgen.model.dispatch_keys.append(torchgen.model.DispatchKey.AutogradPrivateUse1)
53- 53+ 
54- 54+ 
55-# Create backend_indices map for func retrieval with the key of each func we supported.55+# Create backend_indices map for func retrieval with the key of each func we supported.
56-def create_backend_index(backend_ops: List[str],56+def create_backend_index(backend_ops: List[str],
57- symint_ops: Set[str],57+ symint_ops: Set[str],
58- dispatch_key: DispatchKey,58+ dispatch_key: DispatchKey,
59- native_funcs_map: Dict[OperatorName, NativeFunction],59+ native_funcs_map: Dict[OperatorName, NativeFunction],
60- cpp_namespace: str,60+ cpp_namespace: str,
61- ) -> BackendIndex:61+ ) -> BackendIndex:
62- metadata: Dict[OperatorName, BackendMetadata] = {}62+ metadata: Dict[OperatorName, BackendMetadata] = {}
63- for op in backend_ops:63+ for op in backend_ops:
64- op_name = OperatorName.parse(op)64+ op_name = OperatorName.parse(op)
65- if op_name not in native_funcs_map:65+ if op_name not in native_funcs_map:
66- raise KeyError(f"Found an invalid operator name: {op_name}")66+ raise KeyError(f"Found an invalid operator name: {op_name}")
67- # See Note [External Backends Follow Dispatcher API]67+ # See Note [External Backends Follow Dispatcher API]
68- kernel_name = dispatcher.name(native_funcs_map[op_name].func)68+ kernel_name = dispatcher.name(native_funcs_map[op_name].func)
69- if op in symint_ops:69+ if op in symint_ops:
70- kernel_name += "_symint"70+ kernel_name += "_symint"
71- m = BackendMetadata(kernel=kernel_name, structured=False, cpp_namespace=cpp_namespace)71+ m = BackendMetadata(kernel=kernel_name, structured=False, cpp_namespace=cpp_namespace)
72- metadata[op_name] = m72+ metadata[op_name] = m
73- return BackendIndex(73+ return BackendIndex(
74- dispatch_key=dispatch_key,74+ dispatch_key=dispatch_key,
75- use_out_as_primary=False,75+ use_out_as_primary=False,
76- external=True,76+ external=True,
77- device_guard=True,77+ device_guard=True,
78- index=metadata)78+ index=metadata)
79- 79+ 
80- 80+ 
81-# Check whether the function is placed at the wrong place.81+# Check whether the function is placed at the wrong place.
82-def check_grouped_native_functions(82+def check_grouped_native_functions(
83- backend_key: DispatchKey,83+ backend_key: DispatchKey,
84- autograd_key: DispatchKey,84+ autograd_key: DispatchKey,
85- backend_indices: Dict[DispatchKey, BackendIndex],85+ backend_indices: Dict[DispatchKey, BackendIndex],
86- grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]]):86+ grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]]):
87- for g in grouped_native_functions:87+ for g in grouped_native_functions:
88- if isinstance(g, NativeFunction):88+ if isinstance(g, NativeFunction):
89- forward_kernels = [] if backend_key is None else \89+ forward_kernels = [] if backend_key is None else \
90- [m for m in [backend_indices[backend_key].get_kernel(g)] if m is not None]90+ [m for m in [backend_indices[backend_key].get_kernel(g)] if m is not None]
91- backward_kernels = [] if autograd_key is None else \91+ backward_kernels = [] if autograd_key is None else \
92- [m for m in [backend_indices[autograd_key].get_kernel(g)] if m is not None]92+ [m for m in [backend_indices[autograd_key].get_kernel(g)] if m is not None]
93- else:93+ else:
94- if backend_key is None:94+ if backend_key is None:
95- forward_kernels = []95+ forward_kernels = []
96- else:96+ else:
97- forward_kernels = []97+ forward_kernels = []
98- for f in g.functions():98+ for f in g.functions():
99- kernel = backend_indices[backend_key].get_kernel(f)99+ kernel = backend_indices[backend_key].get_kernel(f)
100- if kernel is not None:100+ if kernel is not None:
101- forward_kernels.append(kernel)101+ forward_kernels.append(kernel)
102- if autograd_key is None:102+ if autograd_key is None:
103- backward_kernels = []103+ backward_kernels = []
104- else:104+ else:
105- backward_kernels = []105+ backward_kernels = []
106- for f in g.functions():106+ for f in g.functions():
107- kernel = backend_indices[autograd_key].get_kernel(f)107+ kernel = backend_indices[autograd_key].get_kernel(f)
108- if kernel is not None:108+ if kernel is not None:
109- backward_kernels.append(kernel)109+ backward_kernels.append(kernel)
110- 110+ 
111- forward_kernels = [f for f in forward_kernels if f is not None]111+ forward_kernels = [f for f in forward_kernels if f is not None]
112- backward_kernels = [f for f in backward_kernels if f is not None]112+ backward_kernels = [f for f in backward_kernels if f is not None]
113- 113+ 
114- if len(forward_kernels) != 0 and len(backward_kernels) != 0:114+ if len(forward_kernels) != 0 and len(backward_kernels) != 0:
115- raise ValueError(f'Currently, all variants of an op must either be registered to a backend key, \115+ raise ValueError(f'Currently, all variants of an op must either be registered to a backend key, \
116- or to a backend\'s autograd key. They cannot be mix and matched. If this is \116+ or to a backend\'s autograd key. They cannot be mix and matched. If this is \
117- something you need, feel free to create an issue! {forward_kernels[0].kernel} \117+ something you need, feel free to create an issue! {forward_kernels[0].kernel} \
118- is listed under "supported", but {backward_kernels[0].kernel} is listed under "autograd".')118+ is listed under "supported", but {backward_kernels[0].kernel} is listed under "autograd".')
119- 119+ 
120-_GLOBAL_PARSE_NATIVE_YAML_CACHE = {}120+_GLOBAL_PARSE_NATIVE_YAML_CACHE = {}
121- 121+ 
122-# Parse native_functions.yaml into a sequence of NativeFunctions and Backend Indices.122+# Parse native_functions.yaml into a sequence of NativeFunctions and Backend Indices.
123-ParsedYaml = namedtuple('ParsedYaml', ['native_functions', 'backend_indices'])123+ParsedYaml = namedtuple('ParsedYaml', ['native_functions', 'backend_indices'])
124- 124+ 
125- 125+ 
126-def modify_func_in_native_yaml(func: str) -> str:126+def modify_func_in_native_yaml(func: str) -> str:
127- # func_to_modify: {old_value: new_value}127+ # func_to_modify: {old_value: new_value}
128- func_to_modify = {"matmul_backward(Tensor grad, Tensor self, Tensor other, bool[2] mask) -> (Tensor, Tensor)":128+ func_to_modify = {"matmul_backward(Tensor grad, Tensor self, Tensor other, bool[2] mask) -> (Tensor, Tensor)":
129- "matmul_backward(Tensor grad_out, Tensor self, Tensor other, bool[2] mask) -> (Tensor, Tensor)"}129+ "matmul_backward(Tensor grad_out, Tensor self, Tensor other, bool[2] mask) -> (Tensor, Tensor)"}
130- if func in func_to_modify:130+ if func in func_to_modify:
131- return func_to_modify[func]131+ return func_to_modify[func]
132- return func132+ return func
133- 133+ 
134- 134+ 
135-def parse_native_and_custom_yaml(path: str, tag_path: str, custom_path: str) -> ParsedYaml:135+def parse_native_and_custom_yaml(path: str, tag_path: str, custom_path: str) -> ParsedYaml:
136- global _GLOBAL_PARSE_NATIVE_YAML_CACHE136+ global _GLOBAL_PARSE_NATIVE_YAML_CACHE
137- if path not in _GLOBAL_PARSE_NATIVE_YAML_CACHE:137+ if path not in _GLOBAL_PARSE_NATIVE_YAML_CACHE:
138- valid_tags = parse_tags_yaml(tag_path)138+ valid_tags = parse_tags_yaml(tag_path)
139- PathManager.check_directory_path_readable(path)139+ PathManager.check_directory_path_readable(path)
140- with open(path, 'r') as f:140+ with open(path, 'r') as f:
141- es = yaml.safe_load(f)141+ es = yaml.safe_load(f)
142- if not isinstance(es, list):142+ if not isinstance(es, list):
143- raise TypeError("es is not list")143+ raise TypeError("es is not list")
144- rs: List[NativeFunction] = []144+ rs: List[NativeFunction] = []
145- bs: Dict[DispatchKey, Dict[OperatorName, BackendMetadata]] = defaultdict(dict)145+ bs: Dict[DispatchKey, Dict[OperatorName, BackendMetadata]] = defaultdict(dict)
146- for e in es:146+ for e in es:
147- e["func"] = modify_func_in_native_yaml(e["func"])147+ e["func"] = modify_func_in_native_yaml(e["func"])
148- func, m = NativeFunction.from_yaml(e, "Location", valid_tags)148+ func, m = NativeFunction.from_yaml(e, "Location", valid_tags)
149- rs.append(func)149+ rs.append(func)
150- BackendIndex.grow_index(bs, m)150+ BackendIndex.grow_index(bs, m)
151- 151+ 
152- source_es = parse_npu_yaml(custom_path)152+ source_es = parse_npu_yaml(custom_path)
153- custom_es = source_es.get('custom', []) + source_es.get('custom_autograd', [])153+ custom_es = source_es.get('custom', []) + source_es.get('custom_autograd', [])
154- supported_es = source_es.get('supported', []) + source_es.get('autograd', []) + custom_es154+ supported_es = source_es.get('supported', []) + source_es.get('autograd', []) + custom_es
155- for es in supported_es:155+ for es in supported_es:
156- update_opapi_info(es)156+ update_opapi_info(es)
157- update_internal_format_opapi_info(es)157+ update_internal_format_opapi_info(es)
158- custom_es = field_tag(custom_es)158+ custom_es = field_tag(custom_es)
159- for e in custom_es:159+ for e in custom_es:
160- func, m = NativeFunction.from_yaml(e, "Location", valid_tags)160+ func, m = NativeFunction.from_yaml(e, "Location", valid_tags)
161- rs.append(func)161+ rs.append(func)
162- BackendIndex.grow_index(bs, m)162+ BackendIndex.grow_index(bs, m)
163- 163+ 
164- error_check_native_functions(rs)164+ error_check_native_functions(rs)
165- # Default dict is to prevent the codegen from barfing when we have a dispatch key that has no kernels yet.165+ # Default dict is to prevent the codegen from barfing when we have a dispatch key that has no kernels yet.
166- indices: Dict[DispatchKey, BackendIndex] = defaultdict(lambda: BackendIndex(166+ indices: Dict[DispatchKey, BackendIndex] = defaultdict(lambda: BackendIndex(
167- dispatch_key=DispatchKey.Undefined,167+ dispatch_key=DispatchKey.Undefined,
168- use_out_as_primary=True,168+ use_out_as_primary=True,
169- device_guard=True,169+ device_guard=True,
170- external=False,170+ external=False,
171- index={}))171+ index={}))
172- add_generated_native_functions(rs, bs)172+ add_generated_native_functions(rs, bs)
173- for k, v in bs.items():173+ for k, v in bs.items():
174- # All structured in-tree operators are implemented in terms of their out operator.174+ # All structured in-tree operators are implemented in terms of their out operator.
175- indices[k] = BackendIndex(dispatch_key=k,175+ indices[k] = BackendIndex(dispatch_key=k,
176- use_out_as_primary=True,176+ use_out_as_primary=True,
177- external=False,177+ external=False,
178- device_guard=is_cuda_dispatch_key(k),178+ device_guard=is_cuda_dispatch_key(k),
179- index=v)179+ index=v)
180- _GLOBAL_PARSE_NATIVE_YAML_CACHE[path] = ParsedYaml(rs, indices)180+ _GLOBAL_PARSE_NATIVE_YAML_CACHE[path] = ParsedYaml(rs, indices)
181- 181+ 
182- return _GLOBAL_PARSE_NATIVE_YAML_CACHE[path]182+ return _GLOBAL_PARSE_NATIVE_YAML_CACHE[path]
183- 183+ 
184- 184+ 
185-# Parses the external backend's yaml, and adds a new BackendIndex for the backend's dispatch key.185+# Parses the external backend's yaml, and adds a new BackendIndex for the backend's dispatch key.
186-# Returns a Tuple of (true_backend, backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping)186+# Returns a Tuple of (true_backend, backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping)
187-ParsedExternalYaml = namedtuple('ParsedExternalYaml', [187+ParsedExternalYaml = namedtuple('ParsedExternalYaml', [
188- 'true_backend', 'backend_key', 'autograd_key', 'cpp_namespace', 'backend_indices'])188+ 'true_backend', 'backend_key', 'autograd_key', 'cpp_namespace', 'backend_indices'])
189- 189+ 
190- 190+ 
191-def parse_backend_yaml(191+def parse_backend_yaml(
192- native_yaml_path:str,192+ native_yaml_path:str,
193- backend_yaml_path: str,193+ backend_yaml_path: str,
194- grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],194+ grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
195- backend_indices: Dict[DispatchKey, BackendIndex]195+ backend_indices: Dict[DispatchKey, BackendIndex]
196-) -> ParsedExternalYaml:196+) -> ParsedExternalYaml:
197- 197+ 
198- native_functions_map = {}198+ native_functions_map = {}
199- for f in grouped_native_functions:199+ for f in grouped_native_functions:
200- if isinstance(f, NativeFunction):200+ if isinstance(f, NativeFunction):
201- native_functions_map[f.func.name] = f201+ native_functions_map[f.func.name] = f
202- else:202+ else:
203- for func in f.functions():203+ for func in f.functions():
204- native_functions_map[func.func.name] = func204+ native_functions_map[func.func.name] = func
205- 205+ 
206- PathManager.check_directory_path_readable(backend_yaml_path)206+ PathManager.check_directory_path_readable(backend_yaml_path)
207- with open(backend_yaml_path, 'r') as f:207+ with open(backend_yaml_path, 'r') as f:
208- yaml_values = yaml.safe_load(f)208+ yaml_values = yaml.safe_load(f)
209- if not isinstance(yaml_values, dict):209+ if not isinstance(yaml_values, dict):
210- raise TypeError("yaml_values is not dict")210+ raise TypeError("yaml_values is not dict")
211- 211+ 
212- valid_keys = ['backend', 'cpp_namespace', 'supported', 'autograd', 'custom', 'custom_autograd', 'symint', 'quant']212+ valid_keys = ['backend', 'cpp_namespace', 'supported', 'autograd', 'custom', 'custom_autograd', 'symint', 'quant']
213- 213+ 
214- yaml_backend = yaml_values.pop('backend', None)214+ yaml_backend = yaml_values.pop('backend', None)
215- true_backend = 'PrivateUse1' if yaml_backend == 'NPU' else yaml_backend215+ true_backend = 'PrivateUse1' if yaml_backend == 'NPU' else yaml_backend
216- if true_backend is None:216+ if true_backend is None:
217- raise ValueError("You must provide a value for 'backend'")217+ raise ValueError("You must provide a value for 'backend'")
218- backend = "NPU"218+ backend = "NPU"
219- 219+ 
220- cpp_namespace = yaml_values.pop('cpp_namespace', None)220+ cpp_namespace = yaml_values.pop('cpp_namespace', None)
221- if cpp_namespace is None:221+ if cpp_namespace is None:
222- raise ValueError("You must provide a value for 'cpp_namespace'")222+ raise ValueError("You must provide a value for 'cpp_namespace'")
223- 223+ 
224- supported = yaml_values.pop('supported', [])224+ supported = yaml_values.pop('supported', [])
225- if supported is None:225+ if supported is None:
226- supported = [] # Allow an empty list of supported ops226+ supported = [] # Allow an empty list of supported ops
227- if not isinstance(supported, list):227+ if not isinstance(supported, list):
228- raise TypeError(f'expected "supported" to be a list, but got type {type(supported)}')228+ raise TypeError(f'expected "supported" to be a list, but got type {type(supported)}')
229- 229+ 
230- symint = yaml_values.pop("symint", [])230+ symint = yaml_values.pop("symint", [])
231- if symint is None:231+ if symint is None:
232- symint = []232+ symint = []
233- if not (isinstance(symint, list)):233+ if not (isinstance(symint, list)):
234- raise RuntimeError(f'expected "symint" to be a list, but got: {supported} (of type {type(supported)})')234+ raise RuntimeError(f'expected "symint" to be a list, but got: {supported} (of type {type(supported)})')
235- symint = [op['func'].split("(")[0] if isinstance(op, Dict) else op for op in symint]235+ symint = [op['func'].split("(")[0] if isinstance(op, Dict) else op for op in symint]
236- symint_set = set(symint)236+ symint_set = set(symint)
237- 237+ 
238- supported_autograd = yaml_values.pop('autograd', [])238+ supported_autograd = yaml_values.pop('autograd', [])
239- if not isinstance(supported_autograd, list):239+ if not isinstance(supported_autograd, list):
240- raise TypeError(f'expected "autograd" to be a list, but got: {supported_autograd}')240+ raise TypeError(f'expected "autograd" to be a list, but got: {supported_autograd}')
241- 241+ 
242- supported_list = []242+ supported_list = []
243- for op in supported:243+ for op in supported:
244- if isinstance(op, Dict) and op.get('device_check', None) == 'NoCheck':244+ if isinstance(op, Dict) and op.get('device_check', None) == 'NoCheck':
245- DEVICE_NOCHECK_SET.add(op['func'].split("(")[0])245+ DEVICE_NOCHECK_SET.add(op['func'].split("(")[0])
246- if isinstance(op, Dict) and ({"impl_ns", "op_api", "device_check"} & set(op.keys())):246+ if isinstance(op, Dict) and ({"impl_ns", "op_api", "device_check"} & set(op.keys())):
247- supported_list.append(op['func'].split("(")[0])247+ supported_list.append(op['func'].split("(")[0])
248- elif not isinstance(op, Dict):248+ elif not isinstance(op, Dict):
249- supported_list.append(op)249+ supported_list.append(op)
250- supported = supported_list250+ supported = supported_list
251- 251+ 
252- supported_autograd = [op['func'].split("(")[0] if isinstance(op, Dict) else op for op in supported_autograd]252+ supported_autograd = [op['func'].split("(")[0] if isinstance(op, Dict) else op for op in supported_autograd]
253- supported_autograd += filt_compositeimplicitautograd_api(native_yaml_path, supported)253+ supported_autograd += filt_compositeimplicitautograd_api(native_yaml_path, supported)
254- 254+ 
255- custom = yaml_values.pop('custom', [])255+ custom = yaml_values.pop('custom', [])
256- if not isinstance(custom, list):256+ if not isinstance(custom, list):
257- raise TypeError(f'expected "autograd" to be a list, but got: {custom}')257+ raise TypeError(f'expected "autograd" to be a list, but got: {custom}')
258- 258+ 
259- for item in custom:259+ for item in custom:
260- try:260+ try:
261- supported.append(item['func'][:item['func'].index('(')])261+ supported.append(item['func'][:item['func'].index('(')])
262- except ValueError as e:262+ except ValueError as e:
263- raise Exception(f'Wrong format for function: {item["func"]}') from e263+ raise Exception(f'Wrong format for function: {item["func"]}') from e
264- 264+ 
265- custom_autograd = yaml_values.pop('custom_autograd', [])265+ custom_autograd = yaml_values.pop('custom_autograd', [])
266- if not isinstance(custom_autograd, list):266+ if not isinstance(custom_autograd, list):
267- raise TypeError(f'expected "autograd" to be a list, but got: {custom_autograd}')267+ raise TypeError(f'expected "autograd" to be a list, but got: {custom_autograd}')
268- for item in custom_autograd:268+ for item in custom_autograd:
269- supported_autograd.append(item['func'][:item['func'].index('(')])269+ supported_autograd.append(item['func'][:item['func'].index('(')])
270- 270+ 
271- quant = yaml_values.pop('quant', [])271+ quant = yaml_values.pop('quant', [])
272- if not isinstance(quant, list):272+ if not isinstance(quant, list):
273- raise TypeError(f'expected "quant" to be a list, but got: {quant}')273+ raise TypeError(f'expected "quant" to be a list, but got: {quant}')
274- quant = [op['func'].split("(")[0] if isinstance(op, Dict) else op for op in quant]274+ quant = [op['func'].split("(")[0] if isinstance(op, Dict) else op for op in quant]
275- 275+ 
276- # custom_supported is only supported for filt expose api, and is not useful here.276+ # custom_supported is only supported for filt expose api, and is not useful here.
277- yaml_values.pop('custom_supported', [])277+ yaml_values.pop('custom_supported', [])
278- if (len(yaml_values.keys()) > 0):278+ if (len(yaml_values.keys()) > 0):
279- raise KeyError(f'{backend_yaml_path} contains unexpected keys: {", ".join(yaml_values.keys())}. \279+ raise KeyError(f'{backend_yaml_path} contains unexpected keys: {", ".join(yaml_values.keys())}. \
280- Only the following keys are supported: {", ".join(valid_keys)}')280+ Only the following keys are supported: {", ".join(valid_keys)}')
281- 281+ 
282- backend_key: Optional[DispatchKey] = None282+ backend_key: Optional[DispatchKey] = None
283- opapi_key = "OpApi"283+ opapi_key = "OpApi"
284- if len(supported) > 0:284+ if len(supported) > 0:
285- with context(lambda: f'The provided value for "backend" must be a valid DispatchKey, but got {backend}.'):285+ with context(lambda: f'The provided value for "backend" must be a valid DispatchKey, but got {backend}.'):
286- backend_key = DispatchKey.parse(backend)286+ backend_key = DispatchKey.parse(backend)
287- 287+ 
288- backend_idx = create_backend_index(supported, symint_set, backend_key, native_functions_map, cpp_namespace)288+ backend_idx = create_backend_index(supported, symint_set, backend_key, native_functions_map, cpp_namespace)
289- opapi_backend_idx = create_backend_index([op for op in supported if is_opapi(op)],289+ opapi_backend_idx = create_backend_index([op for op in supported if is_opapi(op)],
290- symint_set, backend_key, native_functions_map, cpp_namespace)290+ symint_set, backend_key, native_functions_map, cpp_namespace)
291- if backend_key in backend_indices:291+ if backend_key in backend_indices:
292- raise KeyError("backend_key should not be in backend_indices.")292+ raise KeyError("backend_key should not be in backend_indices.")
293- backend_indices[backend_key] = backend_idx293+ backend_indices[backend_key] = backend_idx
294- backend_indices[str(backend_key) + opapi_key] = opapi_backend_idx294+ backend_indices[str(backend_key) + opapi_key] = opapi_backend_idx
295- 295+ 
296- autograd_key: Optional[DispatchKey] = None296+ autograd_key: Optional[DispatchKey] = None
297- if len(supported_autograd) > 0:297+ if len(supported_autograd) > 0:
298- with context(lambda: f'The "autograd" key was specified, which indicates that you would like to override \298+ with context(lambda: f'The "autograd" key was specified, which indicates that you would like to override \
299-the behavior of autograd for some operators on your backend. However "Autograd{backend}" is not a valid DispatchKey.'):299+the behavior of autograd for some operators on your backend. However "Autograd{backend}" is not a valid DispatchKey.'):
300- autograd_key = DispatchKey.parse(f'Autograd{backend}')300+ autograd_key = DispatchKey.parse(f'Autograd{backend}')
301- 301+ 
302- autograd_idx = create_backend_index(supported_autograd, symint_set,302+ autograd_idx = create_backend_index(supported_autograd, symint_set,
303- autograd_key, native_functions_map, cpp_namespace)303+ autograd_key, native_functions_map, cpp_namespace)
304- opapi_autograd_idx = create_backend_index([op for op in supported_autograd if is_opapi(op)],304+ opapi_autograd_idx = create_backend_index([op for op in supported_autograd if is_opapi(op)],
305- symint_set, autograd_key, native_functions_map, cpp_namespace)305+ symint_set, autograd_key, native_functions_map, cpp_namespace)
306- 306+ 
307- backend_indices[autograd_key] = autograd_idx307+ backend_indices[autograd_key] = autograd_idx
308- backend_indices[str(autograd_key) + opapi_key] = opapi_autograd_idx308+ backend_indices[str(autograd_key) + opapi_key] = opapi_autograd_idx
309- 309+ 
310- quant_key = "Quantize"310+ quant_key = "Quantize"
311- if len(quant) > 0:311+ if len(quant) > 0:
312- quant_idx = create_backend_index(quant, symint_set, backend_key, native_functions_map, cpp_namespace)312+ quant_idx = create_backend_index(quant, symint_set, backend_key, native_functions_map, cpp_namespace)
313- if quant_key in backend_indices:313+ if quant_key in backend_indices:
314- raise KeyError("quant_key should not be in backend_indices.")314+ raise KeyError("quant_key should not be in backend_indices.")
315- backend_indices[str(backend_key) + quant_key] = quant_idx315+ backend_indices[str(backend_key) + quant_key] = quant_idx
316- 316+ 
317- # check_grouped_native_functions(backend_key, autograd_key, backend_indices, grouped_native_functions)317+ # check_grouped_native_functions(backend_key, autograd_key, backend_indices, grouped_native_functions)
AtlasAccount
AtlasAccountAtlasAccount1月26日

注释掉的代码: 第317行有一行被注释掉的函数调用'check_grouped_native_functions'。这可能是调试时留下的代码,或者是暂时禁用的功能。长期保留注释掉的代码会影响代码可读性和维护性。

问题类型: 注释掉的代码 文件路径: torchnpugen/gen_backend_stubs.py 行号: 317 问题代码:

# check_grouped_native_functions(backend_key, autograd_key, backend_indices, grouped_native_functions)

修改建议:

如果这个检查不再需要,应该完全删除这行代码。如果将来可能重新启用,建议添加TODO注释说明原因和启用条件。例如:'# TODO: Re-enable after fixing issue #123'

此评论由代码审查工具自动生成

likedislike
318- return ParsedExternalYaml(true_backend, backend_key, autograd_key, cpp_namespace, backend_indices)318+ return ParsedExternalYaml(true_backend, backend_key, autograd_key, cpp_namespace, backend_indices)
319- 319+ 
320- 320+ 
321-def op_plugin_kernel_conut(op_plugin_ops_dir: str):321+def op_plugin_kernel_conut(op_plugin_ops_dir: str):
AtlasAccount
AtlasAccountAtlasAccount1月26日

函数名拼写错误: 第321行的函数名'op_plugin_kernel_conut'中的'conut'应该是'count'的拼写错误。虽然这只是一个内部函数,但拼写错误会影响代码的可读性和专业性。

问题类型: 函数名拼写错误 文件路径: torchnpugen/gen_backend_stubs.py 行号: 321 问题代码:

def op_plugin_kernel_conut(op_plugin_ops_dir: str):

修改建议:

将函数名改为'op_plugin_kernel_count'以保持一致性。同时检查代码中是否有其他调用该函数的地方,确保一并更新。

此评论由代码审查工具自动生成

likedislike
322- actual_backend_kernel_name_counts = Counter()322+ actual_backend_kernel_name_counts = Counter()
323- file_path = os.path.join(op_plugin_ops_dir, "OpInterface.h")323+ file_path = os.path.join(op_plugin_ops_dir, "OpInterface.h")
324- PathManager.check_directory_path_readable(file_path)324+ PathManager.check_directory_path_readable(file_path)
325- try:325+ try:
326- with open(file_path, 'r') as f:326+ with open(file_path, 'r') as f:
327- backend_defns = f.read()327+ backend_defns = f.read()
328- except IOError as e:328+ except IOError as e:
329- raise AssertionError(f'Unable to read from the specified impl_path file: {file_path}') from e329+ raise AssertionError(f'Unable to read from the specified impl_path file: {file_path}') from e
330- 330+ 
331- kernel_defn_regex = rf'\w+(?=\()'331+ kernel_defn_regex = rf'\w+(?=\()'
332- actual_backend_kernel_name_counts += Counter(re.findall(kernel_defn_regex, backend_defns))332+ actual_backend_kernel_name_counts += Counter(re.findall(kernel_defn_regex, backend_defns))
333- return actual_backend_kernel_name_counts333+ return actual_backend_kernel_name_counts
334- 334+ 
335- 335+ 
336-def pta_kernel_conut(class_name: str, pta_op_dir: str):336+def pta_kernel_conut(class_name: str, pta_op_dir: str):
AtlasAccount
AtlasAccountAtlasAccount1月26日

函数名拼写错误: 第336行的函数名'pta_kernel_conut'同样存在拼写错误,应该是'pta_kernel_count'。这种拼写错误在代码中重复出现,表明可能存在复制粘贴时未修正的问题。

问题类型: 函数名拼写错误 文件路径: torchnpugen/gen_backend_stubs.py 行号: 336 问题代码:

def pta_kernel_conut(class_name: str, pta_op_dir: str):

修改建议:

将函数名改为'pta_kernel_count'。建议在IDE中启用拼写检查,或者建立代码审查流程来捕获这类问题。

此评论由代码审查工具自动生成

likedislike
337- actual_backend_kernel_name_counts = Counter()337+ actual_backend_kernel_name_counts = Counter()
338- for cur_dir, _, filenames in os.walk(pta_op_dir):338+ for cur_dir, _, filenames in os.walk(pta_op_dir):
339- for filename in filenames:339+ for filename in filenames:
340- if not filename.endswith('.cpp'):340+ if not filename.endswith('.cpp'):
341- continue341+ continue
342- file_path = os.path.join(cur_dir, filename)342+ file_path = os.path.join(cur_dir, filename)
343- PathManager.check_directory_path_readable(file_path)343+ PathManager.check_directory_path_readable(file_path)
344- try:344+ try:
345- with open(file_path, 'r') as f:345+ with open(file_path, 'r') as f:
346- backend_defns = f.read()346+ backend_defns = f.read()
347- except IOError:347+ except IOError:
348- raise AssertionError(f'Unable to read from the specified impl_path file: {file_path}')348+ raise AssertionError(f'Unable to read from the specified impl_path file: {file_path}')
349- 349+ 
350- kernel_defn_regex = rf'{class_name}::([\w\d]*)\([^\)]*\)\s*{{'350+ kernel_defn_regex = rf'{class_name}::([\w\d]*)\([^\)]*\)\s*{{'
351- actual_backend_kernel_name_counts += Counter(re.findall(kernel_defn_regex, backend_defns))351+ actual_backend_kernel_name_counts += Counter(re.findall(kernel_defn_regex, backend_defns))
352- return actual_backend_kernel_name_counts352+ return actual_backend_kernel_name_counts
353- 353+ 
354- 354+ 
355-def check_op_plugin_kernels(355+def check_op_plugin_kernels(
356- native_functions: Sequence[NativeFunction],356+ native_functions: Sequence[NativeFunction],
357- expected_kernel_counts: Dict[str, List[NativeFunction]],357+ expected_kernel_counts: Dict[str, List[NativeFunction]],
358- actual_kernel_counts: Dict[str, List[NativeFunction]]):358+ actual_kernel_counts: Dict[str, List[NativeFunction]]):
359- for f in native_functions:359+ for f in native_functions:
360- wrap_name = get_opplugin_wrap_name(f)360+ wrap_name = get_opplugin_wrap_name(f)
361- expect_op_plugin_kernel_count = len(expected_kernel_counts[wrap_name])361+ expect_op_plugin_kernel_count = len(expected_kernel_counts[wrap_name])
362- if expect_op_plugin_kernel_count > actual_kernel_counts[wrap_name]:362+ if expect_op_plugin_kernel_count > actual_kernel_counts[wrap_name]:
363- return False363+ return False
364- return True364+ return True
365- 365+ 
366- 366+ 
367-def main() -> None:367+def main() -> None:
368- parser = argparse.ArgumentParser(description='Generate backend stub files')368+ parser = argparse.ArgumentParser(description='Generate backend stub files')
369- parser.add_argument(369+ parser.add_argument(
370- '-s',370+ '-s',
371- '--source_yaml',371+ '--source_yaml',
372- help='path to source yaml file containing operator external definitions')372+ help='path to source yaml file containing operator external definitions')
373- parser.add_argument(373+ parser.add_argument(
374- '-o', '--output_dir', help='output directory')374+ '-o', '--output_dir', help='output directory')
375- parser.add_argument(375+ parser.add_argument(
376- '--dry_run', type=bool, default=False, help='output directory')376+ '--dry_run', type=bool, default=False, help='output directory')
377- parser.add_argument(377+ parser.add_argument(
378- '--impl_path', type=str, default=None, help='path to the source C++ file containing kernel definitions')378+ '--impl_path', type=str, default=None, help='path to the source C++ file containing kernel definitions')
379- parser.add_argument(379+ parser.add_argument(
380- '--op_plugin_impl_path', type=str, default=None,380+ '--op_plugin_impl_path', type=str, default=None,
381- help='path to the source C++ file containing kernel definitions in op_plugin')381+ help='path to the source C++ file containing kernel definitions in op_plugin')
382- parser.add_argument(382+ parser.add_argument(
383- '--op_plugin_yaml_path', type=str, default=None,383+ '--op_plugin_yaml_path', type=str, default=None,
384- help='path to the source yaml file containing kernel definitions in op_plugin')384+ help='path to the source yaml file containing kernel definitions in op_plugin')
385- options = parser.parse_args()385+ options = parser.parse_args()
386- 386+ 
387- run(options.source_yaml, options.output_dir, options.dry_run,387+ run(options.source_yaml, options.output_dir, options.dry_run,
388- options.impl_path, options.op_plugin_impl_path, options.op_plugin_yaml_path)388+ options.impl_path, options.op_plugin_impl_path, options.op_plugin_yaml_path)
389- 389+ 
390- 390+ 
391-def gen_dispatcher_registrations(391+def gen_dispatcher_registrations(
392- fm: FileManager,392+ fm: FileManager,
393- class_name: str,393+ class_name: str,
394- backend_indices: Dict[DispatchKey, BackendIndex],394+ backend_indices: Dict[DispatchKey, BackendIndex],
395- grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],395+ grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
396- backend_dispatch_key: DispatchKey,396+ backend_dispatch_key: DispatchKey,
397- dispatch_key: DispatchKey,397+ dispatch_key: DispatchKey,
398- selector: "SelectiveBuilder",398+ selector: "SelectiveBuilder",
399- dispatch_key_name: str,399+ dispatch_key_name: str,
400- register_dispatch_key_func: Callable,400+ register_dispatch_key_func: Callable,
401- native_function_registrations: str = '',401+ native_function_registrations: str = '',
402-):402+):
403- backend_index = backend_indices[backend_dispatch_key]403+ backend_index = backend_indices[backend_dispatch_key]
404- ns_helper = NamespaceHelper(namespace_str="at")404+ ns_helper = NamespaceHelper(namespace_str="at")
405- native_func_header = """\405+ native_func_header = """\
406-#include "torch_npu/csrc/core/npu/NPURecovery.h"406+#include "torch_npu/csrc/core/npu/NPURecovery.h"
407-#include "torch_npu/csrc/core/npu/NpuVariables.h"407+#include "torch_npu/csrc/core/npu/NpuVariables.h"
408-#include "torch_npu/csrc/core/npu/NPUException.h"408+#include "torch_npu/csrc/core/npu/NPUException.h"
409-#ifndef BUILD_LIBTORCH409+#ifndef BUILD_LIBTORCH
410-#include "torch_npu/csrc/profiler/utils.h"410+#include "torch_npu/csrc/profiler/utils.h"
411-#endif411+#endif
412- 412+ 
413-#include "torch_npu/csrc/aten/NPUNativeFunctions.h"413+#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
414-#include "torch_npu/csrc/framework/interface/EnvVariables.h"414+#include "torch_npu/csrc/framework/interface/EnvVariables.h"
415-#include "torch_npu/csrc/aten/NPUOpApiNativeFunctions.h"415+#include "torch_npu/csrc/aten/NPUOpApiNativeFunctions.h"
416-#include "torch_npu/csrc/framework/FormatHelper.h"416+#include "torch_npu/csrc/framework/FormatHelper.h"
417-#include "torch_npu/csrc/framework/utils/ForceAclnnList.h"417+#include "torch_npu/csrc/framework/utils/ForceAclnnList.h"
418-#include "torch_npu/csrc/framework/OpHook.h"418+#include "torch_npu/csrc/framework/OpHook.h"
419-#include "op_plugin/OpInterface.h"419+#include "op_plugin/OpInterface.h"
420-"""420+"""
421- static_template = CodeTemplate(421+ static_template = CodeTemplate(
422- """\422+ """\
423-TORCH_LIBRARY_IMPL(aten, $dispatch_key, m) {423+TORCH_LIBRARY_IMPL(aten, $dispatch_key, m) {
424-$dispatch_registrations_body424+$dispatch_registrations_body
425-};"""425+};"""
426- )426+ )
427- static_init_dispatch_registrations = static_template.substitute(427+ static_init_dispatch_registrations = static_template.substitute(
428- dispatch_key=dispatch_key_name,428+ dispatch_key=dispatch_key_name,
429- dispatch_registrations_body=list(429+ dispatch_registrations_body=list(
430- concatMap(430+ concatMap(
431- register_dispatch_key_func(431+ register_dispatch_key_func(
432- backend_index,432+ backend_index,
433- Target.REGISTRATION,433+ Target.REGISTRATION,
434- selector,434+ selector,
435- rocm=False,435+ rocm=False,
436- symint=True,436+ symint=True,
437- class_method_name=f"{class_name}",437+ class_method_name=f"{class_name}",
438- skip_dispatcher_op_registration=False,438+ skip_dispatcher_op_registration=False,
439- ),439+ ),
440- grouped_native_functions,440+ grouped_native_functions,
441- )441+ )
442- ),442+ ),
443- )443+ )
444- fm.write_with_template(f'Register{dispatch_key}.cpp', 'RegisterDispatchKey.cpp', lambda: {444+ fm.write_with_template(f'Register{dispatch_key}.cpp', 'RegisterDispatchKey.cpp', lambda: {
445- 'extra_cuda_headers': '',445+ 'extra_cuda_headers': '',
446- 'external_backend_headers': native_func_header,446+ 'external_backend_headers': native_func_header,
447- 'namespaced_headers': '',447+ 'namespaced_headers': '',
448- 'DispatchKey': dispatch_key,448+ 'DispatchKey': dispatch_key,
449- 'dispatch_headers': dest.gen_registration_headers(449+ 'dispatch_headers': dest.gen_registration_headers(
450- backend_index, per_operator_headers=False, rocm=False450+ backend_index, per_operator_headers=False, rocm=False
451- ),451+ ),
452- 'ops_headers': '',452+ 'ops_headers': '',
453- 'dispatch_helpers': dest.gen_registration_helpers(backend_index),453+ 'dispatch_helpers': dest.gen_registration_helpers(backend_index),
454- 'dispatch_definitions': fm.substitute_with_template(454+ 'dispatch_definitions': fm.substitute_with_template(
455- 'RegisterDispatchDefinitions.ini',455+ 'RegisterDispatchDefinitions.ini',
456- lambda: {456+ lambda: {
457- 'ns_prologue': ns_helper.prologue,457+ 'ns_prologue': ns_helper.prologue,
458- 'ns_epilogue': ns_helper.epilogue,458+ 'ns_epilogue': ns_helper.epilogue,
459- 'static_init_dispatch_registrations': static_init_dispatch_registrations,459+ 'static_init_dispatch_registrations': static_init_dispatch_registrations,
460- 'deferred_dispatch_registrations': '',460+ 'deferred_dispatch_registrations': '',
461- 'dispatch_namespace': dispatch_key.lower(),461+ 'dispatch_namespace': dispatch_key.lower(),
462- 'dispatch_namespaced_definitions': native_function_registrations,462+ 'dispatch_namespaced_definitions': native_function_registrations,
463- 'dispatch_anonymous_definitions': list(463+ 'dispatch_anonymous_definitions': list(
464- concatMap(464+ concatMap(
465- register_dispatch_key_func(465+ register_dispatch_key_func(
466- backend_index,466+ backend_index,
467- Target.ANONYMOUS_DEFINITION,467+ Target.ANONYMOUS_DEFINITION,
468- selector,468+ selector,
469- rocm=False,469+ rocm=False,
470- symint=True,470+ symint=True,
471- class_method_name=f'{class_name}',471+ class_method_name=f'{class_name}',
472- skip_dispatcher_op_registration=False,472+ skip_dispatcher_op_registration=False,
473- ),473+ ),
474- grouped_native_functions,474+ grouped_native_functions,
475- )475+ )
476- ),476+ ),
477- },477+ },
478- ).split('\n'),478+ ).split('\n'),
479- })479+ })
480- 480+ 
481- 481+ 
482-def get_supported_grouped_native_functions(482+def get_supported_grouped_native_functions(
483- grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],483+ grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
484- backend_index: BackendIndex,484+ backend_index: BackendIndex,
485- ) -> Sequence[Union[NativeFunction, NativeFunctionsGroup]]:485+ ) -> Sequence[Union[NativeFunction, NativeFunctionsGroup]]:
486- supported_grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]] = []486+ supported_grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]] = []
487- for funcs in grouped_native_functions:487+ for funcs in grouped_native_functions:
488- if isinstance(funcs, NativeFunctionsGroup) and not backend_index.has_kernel(funcs.out):488+ if isinstance(funcs, NativeFunctionsGroup) and not backend_index.has_kernel(funcs.out):
489- for f in funcs.functions():489+ for f in funcs.functions():
490- if backend_index.has_kernel(f):490+ if backend_index.has_kernel(f):
491- supported_grouped_native_functions.append(f)491+ supported_grouped_native_functions.append(f)
492- continue492+ continue
493- supported_grouped_native_functions.append(funcs)493+ supported_grouped_native_functions.append(funcs)
494- return supported_grouped_native_functions494+ return supported_grouped_native_functions
495- 495+ 
496- 496+ 
497-def gen_foreach_register(497+def gen_foreach_register(
498- fm: FileManager,498+ fm: FileManager,
499- tags_yaml_path: str,499+ tags_yaml_path: str,
500- native_yaml_path: str,500+ native_yaml_path: str,
501- grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],501+ grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
502- backend_indices: BackendIndex,502+ backend_indices: BackendIndex,
503-):503+):
504- cpu_backend_indices = parse_native_yaml(native_yaml_path, tags_yaml_path).backend_indices[DispatchKey.CPU]504+ cpu_backend_indices = parse_native_yaml(native_yaml_path, tags_yaml_path).backend_indices[DispatchKey.CPU]
505- foreach_dict: Dict[str, str] = {}505+ foreach_dict: Dict[str, str] = {}
506- header_set = set()506+ header_set = set()
507- 507+ 
508- def get_foreach_kernel(func: NativeFunction):508+ def get_foreach_kernel(func: NativeFunction):
509- schema = func.func.name509+ schema = func.func.name
510- if not str(schema).startswith("_foreach"):510+ if not str(schema).startswith("_foreach"):
511- return511+ return
512- if schema in cpu_backend_indices.index and schema not in backend_indices.index:512+ if schema in cpu_backend_indices.index and schema not in backend_indices.index:
513- foreach_dict[str(schema)] = cpu_backend_indices.index[schema].kernel513+ foreach_dict[str(schema)] = cpu_backend_indices.index[schema].kernel
514- 514+ 
515- for f in grouped_native_functions:515+ for f in grouped_native_functions:
516- if isinstance(f, NativeFunctionsGroup):516+ if isinstance(f, NativeFunctionsGroup):
517- header_set.add(str(f.signature().name.name.base))517+ header_set.add(str(f.signature().name.name.base))
518- for func in f.functions():518+ for func in f.functions():
519- get_foreach_kernel(func)519+ get_foreach_kernel(func)
520- else:520+ else:
521- header_set.add(str(f.func.name.name.base))521+ header_set.add(str(f.func.name.name.base))
522- get_foreach_kernel(f)522+ get_foreach_kernel(f)
523- 523+ 
524- kernel_template = CodeTemplate(524+ kernel_template = CodeTemplate(
525- """\525+ """\
526-m.impl("${schema}", TORCH_FN(at::native::${kernel}));"""526+m.impl("${schema}", TORCH_FN(at::native::${kernel}));"""
527- )527+ )
528- header_template = CodeTemplate(528+ header_template = CodeTemplate(
529- """\529+ """\
530-#include <ATen/ops/${function}_native.h>"""530+#include <ATen/ops/${function}_native.h>"""
531- )531+ )
532- fm.write_with_template(f'ForeachRegister.cpp', 'ForeachRegister.cpp', lambda: {532+ fm.write_with_template(f'ForeachRegister.cpp', 'ForeachRegister.cpp', lambda: {
533- 'include_headers': [header_template.substitute(function=h) for h in header_set if h.startswith("_foreach")],533+ 'include_headers': [header_template.substitute(function=h) for h in header_set if h.startswith("_foreach")],
534- 'foreach_kernel': [kernel_template.substitute(schema=kv[0], kernel=kv[1]) for kv in foreach_dict.items()]534+ 'foreach_kernel': [kernel_template.substitute(schema=kv[0], kernel=kv[1]) for kv in foreach_dict.items()]
535- })535+ })
536- 536+ 
537- 537+ 
538-def gen_quantize_register(538+def gen_quantize_register(
539- fm: FileManager,539+ fm: FileManager,
540- backend_indices: BackendIndex,540+ backend_indices: BackendIndex,
541-):541+):
542- ns_helper = NamespaceHelper(namespace_str="at")542+ ns_helper = NamespaceHelper(namespace_str="at")
543- 543+ 
544- quantize_dict: Dict[str, str] = {}544+ quantize_dict: Dict[str, str] = {}
545- for op_name, metadata in backend_indices.index.items():545+ for op_name, metadata in backend_indices.index.items():
546- quantize_dict[op_name] = metadata.kernel546+ quantize_dict[op_name] = metadata.kernel
547- 547+ 
548- native_func_header = """\548+ native_func_header = """\
549-#include <ATen/ops/quantize_per_tensor.h>549+#include <ATen/ops/quantize_per_tensor.h>
550-#include "op_plugin/OpInterface.h"550+#include "op_plugin/OpInterface.h"
551-"""551+"""
552- static_template = CodeTemplate(552+ static_template = CodeTemplate(
553- """\553+ """\
554-TORCH_LIBRARY_IMPL(aten, $dispatch_key, m) {554+TORCH_LIBRARY_IMPL(aten, $dispatch_key, m) {
555-$dispatch_registrations_body555+$dispatch_registrations_body
556-m.impl("q_scale", TORCH_FN(at::native::q_scale_quant));556+m.impl("q_scale", TORCH_FN(at::native::q_scale_quant));
557-m.impl("q_per_channel_scales", TORCH_FN(at::native::q_per_channel_scales));557+m.impl("q_per_channel_scales", TORCH_FN(at::native::q_per_channel_scales));
558-m.impl("q_zero_point", TORCH_FN(at::native::q_zero_point_quant));558+m.impl("q_zero_point", TORCH_FN(at::native::q_zero_point_quant));
559-m.impl("q_per_channel_zero_points", TORCH_FN(at::native::q_per_channel_zero_points));559+m.impl("q_per_channel_zero_points", TORCH_FN(at::native::q_per_channel_zero_points));
560-m.impl("q_per_channel_axis", TORCH_FN(at::native::q_per_channel_axis));560+m.impl("q_per_channel_axis", TORCH_FN(at::native::q_per_channel_axis));
561-m.impl("qscheme", TORCH_FN(at::native::qscheme_quant));561+m.impl("qscheme", TORCH_FN(at::native::qscheme_quant));
562-};"""562+};"""
563- )563+ )
564- kernel_template = CodeTemplate(564+ kernel_template = CodeTemplate(
565- """\565+ """\
566-m.impl("${schema}", TORCH_FN(op_plugin::${kernel}));"""566+m.impl("${schema}", TORCH_FN(op_plugin::${kernel}));"""
567- )567+ )
568- static_init_dispatch_registrations = static_template.substitute(568+ static_init_dispatch_registrations = static_template.substitute(
569- dispatch_key="QuantizedPrivateUse1",569+ dispatch_key="QuantizedPrivateUse1",
570- dispatch_registrations_body=[kernel_template.substitute(schema=kv[0], kernel=kv[1]) for kv in quantize_dict.items()]570+ dispatch_registrations_body=[kernel_template.substitute(schema=kv[0], kernel=kv[1]) for kv in quantize_dict.items()]
571- )571+ )
572- fm.write_with_template(f'QuantizedRegister.cpp', 'RegisterDispatchKey.cpp', lambda: {572+ fm.write_with_template(f'QuantizedRegister.cpp', 'RegisterDispatchKey.cpp', lambda: {
573- 'extra_cuda_headers': '',573+ 'extra_cuda_headers': '',
574- 'external_backend_headers': native_func_header,574+ 'external_backend_headers': native_func_header,
575- 'namespaced_headers': '',575+ 'namespaced_headers': '',
576- 'DispatchKey': 'NPU',576+ 'DispatchKey': 'NPU',
577- 'dispatch_headers': '',577+ 'dispatch_headers': '',
578- 'ops_headers': '',578+ 'ops_headers': '',
579- 'dispatch_helpers': '',579+ 'dispatch_helpers': '',
580- 'dispatch_definitions': fm.substitute_with_template(580+ 'dispatch_definitions': fm.substitute_with_template(
581- 'RegisterDispatchDefinitions.ini',581+ 'RegisterDispatchDefinitions.ini',
582- lambda: {582+ lambda: {
583- 'ns_prologue': ns_helper.prologue,583+ 'ns_prologue': ns_helper.prologue,
584- 'ns_epilogue': ns_helper.epilogue,584+ 'ns_epilogue': ns_helper.epilogue,
585- 'static_init_dispatch_registrations': static_init_dispatch_registrations,585+ 'static_init_dispatch_registrations': static_init_dispatch_registrations,
586- 'deferred_dispatch_registrations': '',586+ 'deferred_dispatch_registrations': '',
587- 'dispatch_namespace': '',587+ 'dispatch_namespace': '',
588- 'dispatch_namespaced_definitions': '',588+ 'dispatch_namespaced_definitions': '',
589- 'dispatch_anonymous_definitions': '',589+ 'dispatch_anonymous_definitions': '',
590- },590+ },
591- ).split('\n'),591+ ).split('\n'),
592- })592+ })
593- 593+ 
594- 594+ 
595-def gen_functionalization(fm: FileManager,595+def gen_functionalization(fm: FileManager,
596- selector: "SelectiveBuilder",596+ selector: "SelectiveBuilder",
597- grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroupOptionalOut]],597+ grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroupOptionalOut]],
598- ):598+ ):
599- def key_func(599+ def key_func(
600- fn: Union[NativeFunction, NativeFunctionsGroupOptionalOut]600+ fn: Union[NativeFunction, NativeFunctionsGroupOptionalOut]
601- ) -> str:601+ ) -> str:
602- return fn.root_name602+ return fn.root_name
603- 603+ 
604- def functionalization_env_callable(g):604+ def functionalization_env_callable(g):
605- definition = gen_functionalization_definition(selector, g)605+ definition = gen_functionalization_definition(selector, g)
606- register = gen_functionalization_registration(selector, g)606+ register = gen_functionalization_registration(selector, g)
607- return {607+ return {
608- "func_definitions": definition,608+ "func_definitions": definition,
609- "func_registrations": register,609+ "func_registrations": register,
610- }610+ }
611- 611+ 
612- fm.write_sharded(612+ fm.write_sharded(
613- "RegisterFunctionalization.cpp",613+ "RegisterFunctionalization.cpp",
614- grouped_native_functions,614+ grouped_native_functions,
615- key_fn=key_func,615+ key_fn=key_func,
616- env_callable=functionalization_env_callable,616+ env_callable=functionalization_env_callable,
617- num_shards=2,617+ num_shards=2,
618- sharded_keys={618+ sharded_keys={
619- "func_definitions",619+ "func_definitions",
620- "func_registrations",620+ "func_registrations",
621- },621+ },
622- )622+ )
623- return623+ return
624- 624+ 
625- 625+ 
626-def gen_target_registration(626+def gen_target_registration(
627- target_op_type: str,627+ target_op_type: str,
628- dispatch_key: DispatchKey,628+ dispatch_key: DispatchKey,
629- backend_indices: Dict[DispatchKey, BackendIndex],629+ backend_indices: Dict[DispatchKey, BackendIndex],
630- grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],630+ grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
631- op_plugin_yaml_path: str,631+ op_plugin_yaml_path: str,
632- fm: FileManager,632+ fm: FileManager,
633- selector: "SelectiveBuilder",633+ selector: "SelectiveBuilder",
634- native_functions: List[NativeFunction] = None,634+ native_functions: List[NativeFunction] = None,
635-):635+):
636- target_ops = get_target_functions(op_plugin_yaml_path, target_op_type=target_op_type)636+ target_ops = get_target_functions(op_plugin_yaml_path, target_op_type=target_op_type)
637- target_native_functions = []637+ target_native_functions = []
638- for f in grouped_native_functions:638+ for f in grouped_native_functions:
639- if isinstance(f, NativeFunctionsGroup):639+ if isinstance(f, NativeFunctionsGroup):
640- for func in f.functions():640+ for func in f.functions():
641- if func.func in target_ops:641+ if func.func in target_ops:
642- target_native_functions.append(func)642+ target_native_functions.append(func)
643- elif f.func in target_ops:643+ elif f.func in target_ops:
644- target_native_functions.append(f)644+ target_native_functions.append(f)
645- 645+ 
646- metadata: Dict[OperatorName, BackendMetadata] = {}646+ metadata: Dict[OperatorName, BackendMetadata] = {}
647- for op in target_ops:647+ for op in target_ops:
648- kernel_name = dispatcher.name(op)648+ kernel_name = dispatcher.name(op)
649- metadata[op.name] = BackendMetadata(kernel=kernel_name, structured=False, cpp_namespace=target_op_type)649+ metadata[op.name] = BackendMetadata(kernel=kernel_name, structured=False, cpp_namespace=target_op_type)
650- backend_indices[dispatch_key] = BackendIndex(650+ backend_indices[dispatch_key] = BackendIndex(
651- dispatch_key=dispatch_key,651+ dispatch_key=dispatch_key,
652- use_out_as_primary=False,652+ use_out_as_primary=False,
653- external=True,653+ external=True,
654- device_guard=True,654+ device_guard=True,
655- index=metadata)655+ index=metadata)
656- 656+ 
657- native_registration = get_target_native_registration(dispatch_key, backend_indices, metadata, native_functions)657+ native_registration = get_target_native_registration(dispatch_key, backend_indices, metadata, native_functions)
658- gen_dispatcher_registrations(658+ gen_dispatcher_registrations(
659- fm,659+ fm,
660- backend_indices[dispatch_key].native_function_class_name(),660+ backend_indices[dispatch_key].native_function_class_name(),
661- backend_indices,661+ backend_indices,
662- target_native_functions,662+ target_native_functions,
663- dispatch_key,663+ dispatch_key,
664- dispatch_key,664+ dispatch_key,
665- selector,665+ selector,
666- dispatch_key_name=dispatch_key.name,666+ dispatch_key_name=dispatch_key.name,
667- register_dispatch_key_func=dest.RegisterDispatchKey,667+ register_dispatch_key_func=dest.RegisterDispatchKey,
668- native_function_registrations=native_registration,668+ native_function_registrations=native_registration,
669- )669+ )
670- 670+ 
671- 671+ 
672-def run(source_yaml: str, output_dir: str, dry_run: bool,672+def run(source_yaml: str, output_dir: str, dry_run: bool,
673- impl_path: Optional[str], op_plugin_impl_path: Optional[str], op_plugin_yaml_path: Optional[str]) -> None:673+ impl_path: Optional[str], op_plugin_impl_path: Optional[str], op_plugin_yaml_path: Optional[str]) -> None:
674- rename_privateuse1_dispatch_key()674+ rename_privateuse1_dispatch_key()
675- torchgen_path = get_torchgen_dir()675+ torchgen_path = get_torchgen_dir()
676- 676+ 
677- template_dir = os.path.join(torchgen_path, "packaged/ATen/templates")677+ template_dir = os.path.join(torchgen_path, "packaged/ATen/templates")
678- 678+ 
679- def make_file_manager(install_dir: str) -> FileManager:679+ def make_file_manager(install_dir: str) -> FileManager:
680- return FileManager(install_dir=install_dir, template_dir=template_dir, dry_run=dry_run)680+ return FileManager(install_dir=install_dir, template_dir=template_dir, dry_run=dry_run)
681- 681+ 
682- fm = make_file_manager(output_dir)682+ fm = make_file_manager(output_dir)
683- merge_custom_yaml(source_yaml, op_plugin_yaml_path)683+ merge_custom_yaml(source_yaml, op_plugin_yaml_path)
684- source_yaml = gen_custom_yaml_path(source_yaml)684+ source_yaml = gen_custom_yaml_path(source_yaml)
685- tags_yaml_path = os.path.join(torchgen_path, 'packaged/ATen/native/tags.yaml')685+ tags_yaml_path = os.path.join(torchgen_path, 'packaged/ATen/native/tags.yaml')
686- native_yaml_path = os.path.join(torchgen_path, 'packaged/ATen/native/native_functions.yaml')686+ native_yaml_path = os.path.join(torchgen_path, 'packaged/ATen/native/native_functions.yaml')
687- parsed_yaml = parse_native_and_custom_yaml(native_yaml_path, tags_yaml_path, source_yaml)687+ parsed_yaml = parse_native_and_custom_yaml(native_yaml_path, tags_yaml_path, source_yaml)
688- get_target_functions(op_plugin_yaml_path)688+ get_target_functions(op_plugin_yaml_path)
689- native_functions, backend_indices = parsed_yaml.native_functions, parsed_yaml.backend_indices689+ native_functions, backend_indices = parsed_yaml.native_functions, parsed_yaml.backend_indices
690- grouped_native_functions = get_grouped_native_functions(native_functions)690+ grouped_native_functions = get_grouped_native_functions(native_functions)
691- parsed_backend_yaml = parse_backend_yaml(native_yaml_path, source_yaml, grouped_native_functions, backend_indices)691+ parsed_backend_yaml = parse_backend_yaml(native_yaml_path, source_yaml, grouped_native_functions, backend_indices)
692- true_backend = parsed_backend_yaml.true_backend692+ true_backend = parsed_backend_yaml.true_backend
693- backend_key = parsed_backend_yaml.backend_key693+ backend_key = parsed_backend_yaml.backend_key
694- autograd_key = parsed_backend_yaml.autograd_key694+ autograd_key = parsed_backend_yaml.autograd_key
695- cpp_namespace = parsed_backend_yaml.cpp_namespace695+ cpp_namespace = parsed_backend_yaml.cpp_namespace
696- backend_indices = parsed_backend_yaml.backend_indices696+ backend_indices = parsed_backend_yaml.backend_indices
697- selector = SelectiveBuilder.get_nop_selector()697+ selector = SelectiveBuilder.get_nop_selector()
698- if backend_key is not None:698+ if backend_key is not None:
699- backend_dispatch_key: DispatchKey = backend_key699+ backend_dispatch_key: DispatchKey = backend_key
700- autograd_dispatch_key: DispatchKey = autograd_key700+ autograd_dispatch_key: DispatchKey = autograd_key
701- class_name = backend_indices[backend_dispatch_key].native_function_class_name()701+ class_name = backend_indices[backend_dispatch_key].native_function_class_name()
702- gen_dispatchkey_nativefunc_headers(702+ gen_dispatchkey_nativefunc_headers(
703- fm,703+ fm,
704- class_name,704+ class_name,
705- cpp_namespace,705+ cpp_namespace,
706- backend_indices,706+ backend_indices,
707- grouped_native_functions,707+ grouped_native_functions,
708- backend_key,708+ backend_key,
709- None,709+ None,
710- )710+ )
711- 711+ 
712- gen_dispatchkey_nativefunc_headers(712+ gen_dispatchkey_nativefunc_headers(
713- fm,713+ fm,
714- "NPUNativeOpApiFunctions",714+ "NPUNativeOpApiFunctions",
715- cpp_namespace,715+ cpp_namespace,
716- backend_indices,716+ backend_indices,
717- grouped_native_functions,717+ grouped_native_functions,
718- str(backend_key) + "OpApi",718+ str(backend_key) + "OpApi",
719- None,719+ None,
720- )720+ )
721- 721+ 
722- for dispatch_key in [backend_dispatch_key, autograd_dispatch_key]:722+ for dispatch_key in [backend_dispatch_key, autograd_dispatch_key]:
723- if not dispatch_key:723+ if not dispatch_key:
724- continue724+ continue
725- gen_dispatcher_registrations(725+ gen_dispatcher_registrations(
726- fm,726+ fm,
727- class_name,727+ class_name,
728- backend_indices,728+ backend_indices,
729- get_supported_grouped_native_functions(grouped_native_functions, backend_indices[dispatch_key]),729+ get_supported_grouped_native_functions(grouped_native_functions, backend_indices[dispatch_key]),
730- dispatch_key,730+ dispatch_key,
731- dispatch_key,731+ dispatch_key,
732- selector,732+ selector,
733- dispatch_key_name=dispatch_key.name.replace("NPU", true_backend),733+ dispatch_key_name=dispatch_key.name.replace("NPU", true_backend),
734- register_dispatch_key_func=dest.RegisterDispatchKey,734+ register_dispatch_key_func=dest.RegisterDispatchKey,
735- )735+ )
736- 736+ 
737- gen_quantize_register(fm, backend_indices=backend_indices["NPUQuantize"])737+ gen_quantize_register(fm, backend_indices=backend_indices["NPUQuantize"])
738- 738+ 
739- pta_template_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "templates")739+ pta_template_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "templates")
740- fm = FileManager(install_dir=output_dir, template_dir=pta_template_dir, dry_run=dry_run)740+ fm = FileManager(install_dir=output_dir, template_dir=pta_template_dir, dry_run=dry_run)
741- 741+
742- custom_functions, custom_backend_indices = parse_custom_yaml(source_yaml, tags_yaml_path)742+ custom_functions, custom_backend_indices = parse_custom_yaml(source_yaml, tags_yaml_path)
743- grouped_custom_functions = get_grouped_native_functions_optional_out(custom_functions)743+ grouped_custom_functions = get_grouped_native_functions_optional_out(custom_functions)
744- gen_functionalization(fm, selector, grouped_custom_functions)744+ gen_functionalization(fm, selector, grouped_custom_functions)
745- gen_custom_trace(fm, custom_functions, custom_backend_indices)745+ gen_custom_trace(fm, custom_functions, custom_backend_indices)
746- gen_custom_functions_dispatch(fm, custom_functions)746+ gen_custom_functions_dispatch(fm, custom_functions)
747- 747+ 
748- gen_foreach_register(fm,748+ gen_foreach_register(fm,
749- tags_yaml_path,749+ tags_yaml_path,
750- native_yaml_path,750+ native_yaml_path,
751- grouped_native_functions,751+ grouped_native_functions,
752- backend_indices[backend_dispatch_key])752+ backend_indices[backend_dispatch_key])
753- 753+ 
754- custom_ops_patch_dir = os.path.join(output_dir, "../../utils/")754+ custom_ops_patch_dir = os.path.join(output_dir, "../../utils/")
AtlasAccount
AtlasAccountAtlasAccount1月26日

文件路径硬编码: 第759行使用硬编码路径'../../utils/'来构建custom_ops_patch_dir。这种相对路径依赖可能在不同执行环境下导致问题,特别是当脚本被其他模块调用或工作目录改变时。

问题类型: 文件路径硬编码 文件路径: torchnpugen/gen_backend_stubs.py 行号: 754 问题代码:

custom_ops_patch_dir = os.path.join(output_dir, "../../utils/")

修改建议:

建议使用更可靠的方式构建路径,例如基于当前脚本位置或配置变量。可以考虑使用pathlib.Path的parent属性或从配置文件中读取路径。例如:custom_ops_patch_dir = pathlib.Path(output_dir).parent.parent / 'utils'

此评论由代码审查工具自动生成

likedislike
755- fm = FileManager(install_dir=custom_ops_patch_dir, template_dir=pta_template_dir, dry_run=dry_run)755+ fm = FileManager(install_dir=custom_ops_patch_dir, template_dir=pta_template_dir, dry_run=dry_run)
756- gen_custom_ops_patch(fm, custom_functions)756+ gen_custom_ops_patch(fm, custom_functions)
757- 757+ 
758- filt_exposed_list = filt_exposed_api(source_yaml)758+ filt_exposed_list = filt_exposed_api(source_yaml)
759- exposed_path = pathlib.Path(__file__).parents[1].joinpath('torch_npu/utils/exposed_api.py')759+ exposed_path = pathlib.Path(__file__).parents[1].joinpath('torch_npu/utils/exposed_api.py')
760- PathManager.remove_path_safety(exposed_path)760+ PathManager.remove_path_safety(exposed_path)
761- with os.fdopen(os.open(exposed_path, os.O_RDWR | os.O_CREAT, stat.S_IWUSR | stat.S_IRUSR), 'w') as f:761+ with os.fdopen(os.open(exposed_path, os.O_RDWR | os.O_CREAT, stat.S_IWUSR | stat.S_IRUSR), 'w') as f:
762- f.write(f'public_npu_functions = {filt_exposed_list}')762+ f.write(f'public_npu_functions = {filt_exposed_list}')
763- os.chmod(exposed_path, stat.S_IRUSR | stat.S_IEXEC | stat.S_IRGRP | stat.S_IXGRP)763+ os.chmod(exposed_path, stat.S_IRUSR | stat.S_IEXEC | stat.S_IRGRP | stat.S_IXGRP)
AtlasAccount
AtlasAccountAtlasAccount1月26日

文件权限设置不当: 第760行创建exposed_api.py文件时设置了执行权限(stat.S_IEXEC)。对于Python配置文件,通常不需要执行权限,这可能存在安全隐患。

问题类型: 文件权限设置不当 文件路径: torchnpugen/gen_backend_stubs.py 行号: 763 问题代码:

os.chmod(exposed_path, stat.S_IRUSR | stat.S_IEXEC | stat.S_IRGRP | stat.S_IXGRP)

修改建议:

移除执行权限,只保留读写权限。建议改为:os.chmod(exposed_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP)。如果确实需要执行权限,请在代码注释中说明原因。

此评论由代码审查工具自动生成

likedislike
764- fm = make_file_manager(output_dir)764+ fm = make_file_manager(output_dir)
765- gen_target_registration(765+ gen_target_registration(
766- "sparse",766+ "sparse",
767- DispatchKey.SparsePrivateUse1,767+ DispatchKey.SparsePrivateUse1,
768- backend_indices,768+ backend_indices,
769- grouped_native_functions,769+ grouped_native_functions,
770- op_plugin_yaml_path,770+ op_plugin_yaml_path,
771- fm,771+ fm,
772- selector,772+ selector,
773- native_functions773+ native_functions
774- )774+ )
775- 775+ 
776- gen_target_registration(776+ gen_target_registration(
777- "sparse_csr",777+ "sparse_csr",
778- DispatchKey.SparseCsrPrivateUse1,778+ DispatchKey.SparseCsrPrivateUse1,
779- backend_indices,779+ backend_indices,
780- grouped_native_functions,780+ grouped_native_functions,
781- op_plugin_yaml_path,781+ op_plugin_yaml_path,
782- fm,782+ fm,
783- selector,783+ selector,
784- native_functions784+ native_functions
785- )785+ )
786- 786+ 
787- 787+ 
788-def apply_torchgen_patch():788+def apply_torchgen_patch():
789- dest.RegisterDispatchKey.gen_unstructured = gen_unstructured789+ dest.RegisterDispatchKey.gen_unstructured = gen_unstructured
790- dest.RegisterDispatchKey.gen_device_check = gen_device_check790+ dest.RegisterDispatchKey.gen_device_check = gen_device_check
791- # generate default arguments791+ # generate default arguments
792- JIT_TO_CPP_DEFAULT["contiguous_format"] = "c10::MemoryFormat::Contiguous"792+ JIT_TO_CPP_DEFAULT["contiguous_format"] = "c10::MemoryFormat::Contiguous"
793- add_header_to_template_file()793+ add_header_to_template_file()
794- dispatcher.arguments = native.arguments794+ dispatcher.arguments = native.arguments
795- 795+ 
796- 796+ 
797-if __name__ == '__main__':797+if __name__ == '__main__':
798- apply_torchgen_patch()798+ apply_torchgen_patch()
799- main()799+ main()
Rcodegen/gen_functionalization_type.pytorchnpugen/gen_functionalization_type.py+0-0
文件重命名但无更改。
Rcodegen/templates/CustomFunctions.cpptorchnpugen/templates/CustomFunctions.cpp+0-0
文件重命名但无更改。
Rcodegen/templates/CustomFunctions.htorchnpugen/templates/CustomFunctions.h+0-0
文件重命名但无更改。
Rcodegen/templates/CustomRedispatch.cpptorchnpugen/templates/CustomRedispatch.cpp+0-0
文件重命名但无更改。
Rcodegen/templates/CustomRedispatch.htorchnpugen/templates/CustomRedispatch.h+0-0
文件重命名但无更改。
Rcodegen/templates/CustomRegisterSchema.cpptorchnpugen/templates/CustomRegisterSchema.cpp+0-0
文件重命名但无更改。
Rcodegen/templates/ForeachRegister.cpptorchnpugen/templates/ForeachRegister.cpp+0-0
文件重命名但无更改。
Rcodegen/templates/RegisterFunctionalization.cpptorchnpugen/templates/RegisterFunctionalization.cpp+0-0
文件重命名但无更改。
Rcodegen/templates/custom_ops.pytorchnpugen/templates/custom_ops.py+0-0
文件重命名但无更改。
Rcodegen/templates/npu_testing_utils.pytorchnpugen/templates/npu_testing_utils.py+0-0
文件重命名但无更改。
Rcodegen/utils.pytorchnpugen/utils.py+1-1
@@ -198,7 +198,7 @@ def filt_compositeimplicitautograd_api(native_yaml_path, npu_supported):
198 with open(native_yaml_path, 'r') as f:198 with open(native_yaml_path, 'r') as f:
199 es = yaml.safe_load(f)199 es = yaml.safe_load(f)
200 200 
201- from codegen.autograd.utils import TORCH_AUTOGRAD_FUNCTION201+ from torchnpugen.autograd.utils import TORCH_AUTOGRAD_FUNCTION
202 supported_autograd = []202 supported_autograd = []
203 for e in es:203 for e in es:
204 api_name = e['func'].split('(')[0]204 api_name = e['func'].split('(')[0]