Merged
torch extension support pkg with single op #7686
丛吉钰Add on Jul 20
torch extension support pkg with single op #7686
Merged
Merged fromcong-jiyu/ops-nntorchintocann/ops-nnmaster
Total: 6 files changed+340-72
| @@ -27,7 +27,7 @@ SUPPORTED_LONG_OPTS=( | |||
| 27 | "help" "ops=" "soc=" "vendor_name=" "build-type=" "cov" "noexec" "noaicpu" "opkernel" "opkernel_aicpu" "opkernel_aicpu_test" "static" | 27 | "help" "ops=" "soc=" "vendor_name=" "build-type=" "cov" "noexec" "noaicpu" "opkernel" "opkernel_aicpu" "opkernel_aicpu_test" "static" |
| 28 | "jit" "pkg" "asan" "make_clean_all" "make_clean" "no_force" | 28 | "jit" "pkg" "asan" "make_clean_all" "make_clean" "no_force" |
| 29 | "ophost" "opgraph" "opapi" "run_example" "example_name=" "genop=" "genop_aicpu=" "experimental" "cann_3rd_lib_path=" "oom" "onnxplugin" "tfplugin" "dump_cce" | 29 | "ophost" "opgraph" "opapi" "run_example" "example_name=" "genop=" "genop_aicpu=" "experimental" "cann_3rd_lib_path=" "oom" "onnxplugin" "tfplugin" "dump_cce" |
| 30 | - "simulator" "bisheng_flags=" "kernel_template_input=" "module_extension=" "noaclnn" "mssanitizer" "rule_launch=" "ccache=" | 30 | + "simulator" "bisheng_flags=" "kernel_template_input=" "module_extension=" "noaclnn" "mssanitizer" "rule_launch=" "ccache=" "torch_extension" |
| 31 | ) | 31 | ) |
| 32 | 32 | ||
| 33 | source "./install_deps.sh" | 33 | source "./install_deps.sh" |
| @@ -389,6 +389,7 @@ usage() { | |||
| 389 | echo " --opkernel_aicpu_test build and run aicpu opkernel unit tests" | 389 | echo " --opkernel_aicpu_test build and run aicpu opkernel unit tests" |
| 390 | echo " --pkg build run pkg" | 390 | echo " --pkg build run pkg" |
| 391 | echo " --jit build run pkg without kernel bin" | 391 | echo " --jit build run pkg without kernel bin" |
| 392 | + echo " --torch_extension Build torch_extension whl only, support --ops for single op packaging" | ||
| 392 | echo " --experimental Build experimental version" | 393 | echo " --experimental Build experimental version" |
| 393 | echo " --run_example Compile and execute the example. use --run_example --help for more detail" | 394 | echo " --run_example Compile and execute the example. use --run_example --help for more detail" |
| 394 | echo " --genop Create the initial directory for op, like: --genop=op_class/op_name" | 395 | echo " --genop Create the initial directory for op, like: --genop=op_class/op_name" |
| @@ -672,6 +673,7 @@ checkopts() { | |||
| 672 | ENABLE_TEST=FALSE | 673 | ENABLE_TEST=FALSE |
| 673 | ENABLE_EXPERIMENTAL=FALSE | 674 | ENABLE_EXPERIMENTAL=FALSE |
| 674 | ENABLE_TORCH_EXTENSION=FALSE | 675 | ENABLE_TORCH_EXTENSION=FALSE |
| 676 | + ENABLE_TORCH_EXTENSION_ONLY=FALSE | ||
| 675 | NO_FORCE=FALSE | 677 | NO_FORCE=FALSE |
| 676 | AICPU_ONLY=FALSE | 678 | AICPU_ONLY=FALSE |
| 677 | NO_AICPU=FALSE | 679 | NO_AICPU=FALSE |
| @@ -863,6 +865,9 @@ checkopts() { | |||
| 863 | jit) | 865 | jit) |
| 864 | ENABLE_JIT=TRUE | 866 | ENABLE_JIT=TRUE |
| 865 | ;; | 867 | ;; |
| 868 | + torch_extension) | ||
| 869 | + ENABLE_TORCH_EXTENSION_ONLY=TRUE | ||
| 870 | + ;; | ||
| 866 | asan) ENABLE_ASAN=TRUE ;; | 871 | asan) ENABLE_ASAN=TRUE ;; |
| 867 | run_example) ENABLE_RUN_EXAMPLE=TRUE | 872 | run_example) ENABLE_RUN_EXAMPLE=TRUE |
| 868 | set_example_opt "$@" | 873 | set_example_opt "$@" |
| @@ -1627,6 +1632,20 @@ build_torch_extension_whl() { | |||
| 1627 | return 0 | 1632 | return 0 |
| 1628 | fi | 1633 | fi |
| 1629 | 1634 | ||
| 1635 | + if [[ -n "${COMPILED_OPS}" ]]; then | ||
| 1636 | + local ops_arg="${COMPILED_OPS//;/,}" | ||
| 1637 | + export TORCH_EXTENSION_OPS="${ops_arg}" | ||
| 1638 | + if [[ -n "${VENDOR_NAME}" ]]; then | ||
| 1639 | + export TORCH_EXTENSION_VENDOR="${VENDOR_NAME}" | ||
| 1640 | + else | ||
| 1641 | + export TORCH_EXTENSION_VENDOR="custom" | ||
| 1642 | + fi | ||
| 1643 | + echo "[INFO] Building torch_extension whl with ops: ${ops_arg}, vendor: ${TORCH_EXTENSION_VENDOR}" | ||
| 1644 | + else | ||
| 1645 | + unset TORCH_EXTENSION_OPS | ||
| 1646 | + unset TORCH_EXTENSION_VENDOR | ||
| 1647 | + fi | ||
| 1648 | + | ||
| 1630 | python3 -m build --wheel -n 2>&1 || { | 1649 | python3 -m build --wheel -n 2>&1 || { |
| 1631 | echo "[ERROR] Failed to build torch_extension whl package" | 1650 | echo "[ERROR] Failed to build torch_extension whl package" |
| 1632 | cd "${original_dir}" | 1651 | cd "${original_dir}" |
| @@ -1685,6 +1704,13 @@ main() { | |||
| 1685 | gen_aicpu_op | 1704 | gen_aicpu_op |
| 1686 | exit $? | 1705 | exit $? |
| 1687 | fi | 1706 | fi |
| 1707 | + if [[ "$ENABLE_TORCH_EXTENSION_ONLY" == "TRUE" ]]; then | ||
| 1708 | + build_torch_extension_whl || exit 1 | ||
| 1709 | + mkdir -p "${BUILD_OUT_PATH}" | ||
| 1710 | + cp -f "${BASE_PATH}/torch_extension/dist/"*.whl "${BUILD_OUT_PATH}/" 2>/dev/null | ||
| 1711 | + echo "[INFO] torch_extension whl copied to ${BUILD_OUT_PATH}" | ||
| 1712 | + exit 0 | ||
| 1713 | + fi | ||
| 1688 | assemble_cmake_args | 1714 | assemble_cmake_args |
| 1689 | echo "CMAKE_ARGS: ${CMAKE_ARGS}" | 1715 | echo "CMAKE_ARGS: ${CMAKE_ARGS}" |
| 1690 | 1716 | ||
| @@ -12,26 +12,110 @@ | |||
| 12 | - 框架:PyTorch>=2.6.0、torch_npu(需匹配 PyTorch 版本) | 12 | - 框架:PyTorch>=2.6.0、torch_npu(需匹配 PyTorch 版本) |
| 13 | - 工具包:Ascend CANN Toolkit | 13 | - 工具包:Ascend CANN Toolkit |
| 14 | 14 | ||
| 15 | -### 安装步骤 | 15 | +### 构建 Wheel 包 |
| 16 | 16 | ||
| 17 | -1. 安装依赖: | 17 | +支持两种构建方式:通过 `build.sh` 构建和直接使用 `python3 -m build` 构建。 |
| 18 | 18 | ||
| 19 | - ```sh | 19 | +#### 方式一:通过 build.sh 构建(推荐) |
| 20 | - python3 -m pip install -r requirements.txt | ||
| 21 | - ``` | ||
| 22 | 20 | ||
| 23 | -2. 构建 Wheel 包: | 21 | +```sh |
| 22 | +# 构建整包(包含所有算子) | ||
| 23 | +bash build.sh --torch_extension | ||
| 24 | 24 | ||
| 25 | - ```sh | 25 | +# 构建单算子包(仅包含指定算子) |
| 26 | - # -n: non-isolated build(使用当前环境已有依赖) | 26 | +bash build.sh --torch_extension --ops=swiglu_group --vendor_name=custom |
| 27 | - python3 -m build --wheel -n | ||
| 28 | - ``` | ||
| 29 | 27 | ||
| 30 | -3. 安装包: | 28 | +# 构建多算子包 |
| 29 | +bash build.sh --torch_extension --ops=swiglu_group,swiglu_group_quant --vendor_name=custom | ||
| 30 | +``` | ||
| 31 | 31 | ||
| 32 | - ```sh | 32 | +构建完成后,wheel 包会自动复制到 `build_out/` 目录。 |
| 33 | - python3 -m pip install dist/*.whl --force-reinstall --no-deps | 33 | + |
| 34 | - ``` | 34 | +**参数说明:** |
| 35 | + | ||
| 36 | +| 参数 | 说明 | | ||
| 37 | +| --- | --- | | ||
| 38 | +| `--torch_extension` | 仅构建 torch_extension wheel 包,不执行 cmake 编译 | | ||
| 39 | +| `--ops=op1,op2,...` | 指定编译的算子名(逗号分隔),不指定则编译所有算子 | | ||
| 40 | +| `--vendor_name=name` | 指定子包名,用于子包命名和隔离 | | ||
| 41 | + | ||
| 42 | +**包命名规则:** | ||
| 43 | + | ||
| 44 | +| 场景 | 包名 | 安装目录 | | ||
| 45 | +| --- | --- | --- | | ||
| 46 | +| 整包 | `cann_ops_nn` | `cann_ops_nn/` | | ||
| 47 | +| 单算子/多算子包 | `cann_ops_nn_<vendor>` | `cann_ops_nn_<vendor>/` | | ||
| 48 | + | ||
| 49 | +#### 方式二:直接使用 python3 -m build 构建 | ||
| 50 | + | ||
| 51 | +```sh | ||
| 52 | +# 安装依赖 | ||
| 53 | +python3 -m pip install -r requirements.txt | ||
| 54 | + | ||
| 55 | +# 构建整包 | ||
| 56 | +python3 -m build --wheel -n | ||
| 57 | + | ||
| 58 | +# 构建单算子包 | ||
| 59 | +TORCH_EXTENSION_OPS=swiglu_group TORCH_EXTENSION_VENDOR=custom python3 -m build --wheel -n | ||
| 60 | +``` | ||
| 61 | + | ||
| 62 | +### 安装 | ||
| 63 | + | ||
| 64 | +```sh | ||
| 65 | +# 安装整包 | ||
| 66 | +python3 -m pip install dist/cann_ops_nn-1.0.0-*.whl --no-deps | ||
| 67 | + | ||
| 68 | +# 安装单算子包 | ||
| 69 | +python3 -m pip install dist/cann_ops_nn_myvendor-1.0.0-*.whl --no-deps | ||
| 70 | +``` | ||
| 71 | + | ||
| 72 | +### 整包与子包共存机制 | ||
| 73 | + | ||
| 74 | +整包和单算子包可以同时安装,互不冲突: | ||
| 75 | + | ||
| 76 | +- **整包**安装到 `cann_ops_nn/` 目录,包含所有算子。 | ||
| 77 | +- **单算子包**安装到 `cann_ops_nn_<vendor>/` 目录,与整包物理隔离。 | ||
| 78 | +- 单算子包通过 **entry point** 机制注册算子,优先级高于整包。用户调用 `cann_ops_nn.swiglu_group(x)` 时,若子包已安装则使用子包的算子实现。 | ||
| 79 | +- 卸载单算子包后,整包的同名算子自动接管。 | ||
| 80 | + | ||
| 81 | +```sh | ||
| 82 | +# 安装整包 | ||
| 83 | +pip install cann_ops_nn-1.0.0-*.whl --no-deps | ||
| 84 | + | ||
| 85 | +# 安装单算子包(覆盖整包中的同名算子) | ||
| 86 | +pip install cann_ops_nn_myvendor-1.0.0-*.whl --no-deps | ||
| 87 | + | ||
| 88 | +# 卸载单算子包(整包算子自动恢复) | ||
| 89 | +pip uninstall cann-ops-nn-myvendor | ||
| 90 | +``` | ||
| 91 | + | ||
| 92 | +## 目录结构 | ||
| 93 | + | ||
| 94 | +``` | ||
| 95 | +├── torch_extension | ||
| 96 | +│ ├── build.sh # 构建脚本(支持 --torch_extension 参数) | ||
| 97 | +│ ├── setup.py # wheel 打包配置(支持单算子编包) | ||
| 98 | +│ ├── requirements.txt | ||
| 99 | +│ ├── cann_ops_nn # 整包安装目录 | ||
| 100 | +│ │ ├── __init__.py # 包入口,from .ops import * | ||
| 101 | +│ │ ├── op_builder/ | ||
| 102 | +│ │ │ └── builder.py # OpBuilder 基类,JIT 编译管理 | ||
| 103 | +│ │ ├── common/ | ||
| 104 | +│ │ │ └── aclnn_common.h # ACLNN_CMD 宏等公共能力 | ||
| 105 | +│ │ ├── csrc/ | ||
| 106 | +│ │ │ └── <category>/<op>.cpp # C++ kernel wrapper | ||
| 107 | +│ │ ├── ops/ | ||
| 108 | +│ │ │ ├── __init__.py # 自动发现算子 + entry point 加载 | ||
| 109 | +│ │ │ └── <category>/<op>/<op>.py # Python 前端 | ||
| 110 | +│ │ └── docs/ | ||
| 111 | +│ │ └── torch_extension_guidelines.md # 开发规范 | ||
| 112 | +│ └── dist/ # 构建产物输出目录 | ||
| 113 | +├── <category>/<op>/torch_extension/ # 分布式算子(仓库根目录下) | ||
| 114 | +│ ├── <op>.py | ||
| 115 | +│ ├── __init__.py | ||
| 116 | +│ └── csrc/<op>.cpp | ||
| 117 | +└── build_out/ # build.sh 输出目录 | ||
| 118 | +``` | ||
| 35 | 119 | ||
| 36 | ## 快速入门 | 120 | ## 快速入门 |
| 37 | 121 | ||
| @@ -41,16 +125,13 @@ import torch_npu | |||
| 41 | import cann_ops_nn | 125 | import cann_ops_nn |
| 42 | 126 | ||
| 43 | # 初始化 NPU 张量 | 127 | # 初始化 NPU 张量 |
| 44 | -x1 = torch.randn(16, 32, dtype=torch.float16).npu() | 128 | +x = torch.randn(16, 32, dtype=torch.float16).npu() |
| 45 | -x2 = torch.randn(32, 16, dtype=torch.float16).npu() | ||
| 46 | 129 | ||
| 47 | -# 调用自定义 NPU 算子 | 130 | +# 调用算子(两种方式等价) |
| 48 | -result = torch.ops.cann_ops_nn.{ops}(x1, x2) | 131 | +result = cann_ops_nn.swiglu_group(x) |
| 132 | +result = cann_ops_nn.ops.swiglu_group(x) | ||
| 49 | 133 | ||
| 50 | -# 验证结果 | 134 | +print(result.shape) # torch.Size([16, 16]) |
| 51 | -cpu_result = torch.{ops}(x1.cpu(), x2.cpu()) | ||
| 52 | -assert torch.allclose(result.cpu(), cpu_result, rtol=1e-3) | ||
| 53 | -print("验证成功!") | ||
| 54 | ``` | 135 | ``` |
| 55 | 136 | ||
| 56 | 137 | ||
| @@ -13,9 +13,9 @@ import logging | |||
| 13 | logger = logging.getLogger(__name__) | 13 | logger = logging.getLogger(__name__) |
| 14 | 14 | ||
| 15 | try: | 15 | try: |
| 16 | - import torch | 16 | + import torch # noqa: F401 |
| 17 | - import torch_npu | 17 | + import torch_npu # noqa: F401 |
| 18 | - from . import ops | 18 | + from .ops import * # noqa: F403 |
| 19 | except ImportError as e: | 19 | except ImportError as e: |
| 20 | logger.error(f"导入cann_ops_nn失败: {e},请检查torch/torch_npu是否已安装") | 20 | logger.error(f"导入cann_ops_nn失败: {e},请检查torch/torch_npu是否已安装") |
| 21 | raise | 21 | raise |
| @@ -22,7 +22,10 @@ _as_library = None | |||
| 22 | def get_as_library(): | 22 | def get_as_library(): |
| 23 | global _as_library | 23 | global _as_library |
| 24 | if _as_library is None: | 24 | if _as_library is None: |
| 25 | - _as_library = Library("cann_ops_nn", "DEF") | 25 | + try: |
| 26 | + _as_library = Library("cann_ops_nn", "DEF") | ||
| 27 | + except RuntimeError: | ||
| 28 | + _as_library = Library("cann_ops_nn", "FRAGMENT") | ||
| 26 | return _as_library | 29 | return _as_library |
| 27 | 30 | ||
| 28 | 31 | ||
| @@ -45,10 +48,9 @@ class OpBuilder(ABC): | |||
| 45 | if self._initialized: | 48 | if self._initialized: |
| 46 | return | 49 | return |
| 47 | import torch_npu | 50 | import torch_npu |
| 48 | - import cann_ops_nn | ||
| 49 | 51 | ||
| 50 | self._torch_npu_path = os.path.dirname(os.path.abspath(torch_npu.__file__)) | 52 | self._torch_npu_path = os.path.dirname(os.path.abspath(torch_npu.__file__)) |
| 51 | - self._package_path = os.path.dirname(os.path.abspath(cann_ops_nn.__file__)) | 53 | + self._package_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 52 | self._cann_path = self.get_cann_path() | 54 | self._cann_path = self.get_cann_path() |
| 53 | if not hasattr(torch.ops.cann_ops_nn, self.name): | 55 | if not hasattr(torch.ops.cann_ops_nn, self.name): |
| 54 | self.register_schema(self.schema()) | 56 | self.register_schema(self.schema()) |
| @@ -104,6 +106,7 @@ class OpBuilder(ABC): | |||
| 104 | os.path.join(self._torch_npu_path, "include"), | 106 | os.path.join(self._torch_npu_path, "include"), |
| 105 | os.path.join(self._torch_npu_path, "include/third_party/hccl/inc"), | 107 | os.path.join(self._torch_npu_path, "include/third_party/hccl/inc"), |
| 106 | os.path.join(self._torch_npu_path, "include/third_party/acl/inc"), | 108 | os.path.join(self._torch_npu_path, "include/third_party/acl/inc"), |
| 109 | + os.path.join(self._torch_npu_path, "include/third_party/op-plugin"), | ||
| 107 | os.path.join(self._package_path, "common"), | 110 | os.path.join(self._package_path, "common"), |
| 108 | ] | 111 | ] |
| 109 | return paths | 112 | return paths |
| @@ -9,16 +9,29 @@ | |||
| 9 | # ----------------------------------------------------------------------------------------------------------- | 9 | # ----------------------------------------------------------------------------------------------------------- |
| 10 | 10 | ||
| 11 | import os | 11 | import os |
| 12 | -import sys | ||
| 13 | import importlib | 12 | import importlib |
| 14 | import logging | 13 | import logging |
| 15 | 14 | ||
| 16 | logger = logging.getLogger(__name__) | 15 | logger = logging.getLogger(__name__) |
| 17 | 16 | ||
| 18 | 17 | ||
| 19 | -def _discover_ops(): | 18 | +def _discover_ops_from_entry_points(): |
| 19 | + ops = {} | ||
| 20 | + try: | ||
| 21 | + from importlib.metadata import entry_points | ||
| 22 | + | ||
| 23 | + eps = entry_points(group="cann_ops_nn.ops") | ||
| 24 | + for ep in eps: | ||
| 25 | + ops[ep.name] = ep.value | ||
| 26 | + except Exception: | ||
| 27 | + pass | ||
| 28 | + return ops | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def _discover_ops_from_dir(): | ||
| 20 | ops = {} | 32 | ops = {} |
| 21 | current_dir = os.path.dirname(os.path.abspath(__file__)) | 33 | current_dir = os.path.dirname(os.path.abspath(__file__)) |
| 34 | + package_name = __name__ | ||
| 22 | 35 | ||
| 23 | _skip = frozenset(("graph_convert",)) | 36 | _skip = frozenset(("graph_convert",)) |
| 24 | for entry in sorted(os.listdir(current_dir)): | 37 | for entry in sorted(os.listdir(current_dir)): |
| @@ -33,35 +46,55 @@ def _discover_ops(): | |||
| 33 | sub_path = os.path.join(entry_path, sub) | 46 | sub_path = os.path.join(entry_path, sub) |
| 34 | sub_init = os.path.join(sub_path, "__init__.py") | 47 | sub_init = os.path.join(sub_path, "__init__.py") |
| 35 | if os.path.isdir(sub_path) and os.path.isfile(sub_init) and sub not in ops: | 48 | if os.path.isdir(sub_path) and os.path.isfile(sub_init) and sub not in ops: |
| 36 | - ops[sub] = sub_path | 49 | + ops[sub] = "%s.%s.%s" % (package_name, entry, sub) |
| 37 | 50 | ||
| 38 | return ops | 51 | return ops |
| 39 | 52 | ||
| 40 | 53 | ||
| 41 | -for _name, _path in _discover_ops().items(): | 54 | +def _load_op(name, target): |
| 42 | - _has_module_file = os.path.isfile(os.path.join(_path, _name + ".py")) | 55 | + if ":" in target: |
| 43 | - _search_path = os.path.dirname(_path) if not _has_module_file else _path | 56 | + module_path, attr_name = target.split(":", 1) |
| 44 | - if _search_path not in sys.path: | 57 | + try: |
| 45 | - sys.path.insert(0, _search_path) | 58 | + _mod = importlib.import_module(module_path) |
| 46 | - | 59 | + if hasattr(_mod, attr_name): |
| 60 | + globals()[name] = getattr(_mod, attr_name) | ||
| 61 | + elif hasattr(_mod, name): | ||
| 62 | + globals()[name] = getattr(_mod, name) | ||
| 63 | + else: | ||
| 64 | + globals()[name] = _mod | ||
| 65 | + except (ImportError, RuntimeError) as e: | ||
| 66 | + logger.warning("Failed to load op '%s': %s", name, e) | ||
| 67 | + return | ||
| 47 | try: | 68 | try: |
| 48 | - _mod = importlib.import_module(_name) | 69 | + _mod = importlib.import_module(target) |
| 49 | - if hasattr(_mod, _name): | 70 | + if hasattr(_mod, name): |
| 50 | - globals()[_name] = getattr(_mod, _name) | 71 | + globals()[name] = getattr(_mod, name) |
| 51 | else: | 72 | else: |
| 52 | - globals()[_name] = _mod | 73 | + globals()[name] = _mod |
| 74 | + try: | ||
| 75 | + _gmod = importlib.import_module( | ||
| 76 | + "%s.graph_convert_%s" % (target.rsplit(".", 1)[0], name) | ||
| 77 | + ) | ||
| 78 | + _func = "convert_%s" % name | ||
| 79 | + if hasattr(_gmod, _func): | ||
| 80 | + globals()[_func] = getattr(_gmod, _func) | ||
| 81 | + except ImportError: | ||
| 82 | + pass | ||
| 53 | except (ImportError, RuntimeError) as e: | 83 | except (ImportError, RuntimeError) as e: |
| 54 | - logger.warning("Failed to load op '%s': %s", _name, e) | 84 | + logger.warning("Failed to load op '%s': %s", name, e) |
| 55 | - try: | ||
| 56 | - _gmod = importlib.import_module("graph_convert_%s" % _name) | ||
| 57 | - _func = "convert_%s" % _name | ||
| 58 | - if hasattr(_gmod, _func): | ||
| 59 | - globals()[_func] = getattr(_gmod, _func) | ||
| 60 | - except ImportError: | ||
| 61 | - pass | ||
| 62 | 85 | ||
| 63 | 86 | ||
| 87 | +_ep_ops = _discover_ops_from_entry_points() | ||
| 88 | +_dir_ops = _discover_ops_from_dir() | ||
| 89 | + | ||
| 90 | +_all_ops = dict(_dir_ops) | ||
| 91 | +_all_ops.update(_ep_ops) | ||
| 92 | + | ||
| 93 | +for _name, _target in _all_ops.items(): | ||
| 94 | + _load_op(_name, _target) | ||
| 95 | + | ||
| 64 | try: | 96 | try: |
| 65 | - del _discover_ops, _name, _path, _mod, _gmod, _func | 97 | + del _discover_ops_from_entry_points, _discover_ops_from_dir, _load_op |
| 98 | + del _ep_ops, _dir_ops, _all_ops, _name, _target | ||
| 66 | except NameError: | 99 | except NameError: |
| 67 | pass | 100 | pass |
| @@ -27,11 +27,63 @@ logger = logging.getLogger(__name__) | |||
| 27 | 27 | ||
| 28 | DESCRIPTION = "AscendOpsNn" | 28 | DESCRIPTION = "AscendOpsNn" |
| 29 | VERSION = "1.0.0" | 29 | VERSION = "1.0.0" |
| 30 | -PACKAGE_NAME = "cann_ops_nn" | 30 | +BASE_PACKAGE_NAME = "cann_ops_nn" |
| 31 | 31 | ||
| 32 | HERE = os.path.dirname(os.path.abspath(__file__)) | 32 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 33 | OPS_NN_ROOT = os.path.normpath(os.path.join(HERE, "..")) | 33 | OPS_NN_ROOT = os.path.normpath(os.path.join(HERE, "..")) |
| 34 | -_src_path = os.path.join(HERE, PACKAGE_NAME) | 34 | +_src_path = os.path.join(HERE, BASE_PACKAGE_NAME) |
| 35 | + | ||
| 36 | +_ops_env = os.environ.get("TORCH_EXTENSION_OPS", "").strip() | ||
| 37 | +_selected_ops = ( | ||
| 38 | + frozenset(op.strip() for op in _ops_env.split(",") if op.strip()) | ||
| 39 | + if _ops_env | ||
| 40 | + else None | ||
| 41 | +) | ||
| 42 | + | ||
| 43 | +_vendor_env = os.environ.get("TORCH_EXTENSION_VENDOR", "").strip() | ||
| 44 | + | ||
| 45 | +if _selected_ops: | ||
| 46 | + PACKAGE_NAME = "%s_%s" % (BASE_PACKAGE_NAME, _vendor_env or "custom") | ||
| 47 | +else: | ||
| 48 | + PACKAGE_NAME = BASE_PACKAGE_NAME | ||
| 49 | + | ||
| 50 | +if PACKAGE_NAME != BASE_PACKAGE_NAME and not os.path.isdir( | ||
| 51 | + os.path.join(HERE, PACKAGE_NAME) | ||
| 52 | +): | ||
| 53 | + os.symlink(BASE_PACKAGE_NAME, os.path.join(HERE, PACKAGE_NAME)) | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +_selected_op_categories = [] | ||
| 57 | + | ||
| 58 | +if _selected_ops is not None: | ||
| 59 | + _ops_dir = os.path.join(_src_path, "ops") | ||
| 60 | + for cat in os.listdir(_ops_dir): | ||
| 61 | + cat_path = os.path.join(_ops_dir, cat) | ||
| 62 | + if not os.path.isdir(cat_path): | ||
| 63 | + continue | ||
| 64 | + for name in os.listdir(cat_path): | ||
| 65 | + if name in _selected_ops: | ||
| 66 | + _selected_op_categories.append((cat, name)) | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def _non_python_files(directory): | ||
| 70 | + paths = [] | ||
| 71 | + for path, dirs, filenames in os.walk(directory): | ||
| 72 | + dirs[:] = [d for d in dirs if d != "__pycache__"] | ||
| 73 | + if _selected_ops is not None: | ||
| 74 | + rel = os.path.relpath(path, directory) | ||
| 75 | + parts = rel.split(os.sep) | ||
| 76 | + if ( | ||
| 77 | + len(parts) >= 2 | ||
| 78 | + and parts[0] in ("ops", "csrc") | ||
| 79 | + and parts[1] not in _selected_ops | ||
| 80 | + ): | ||
| 81 | + continue | ||
| 82 | + for filename in filenames: | ||
| 83 | + if filename.endswith((".h", ".cpp")): | ||
| 84 | + paths.append(os.path.join(path, filename)) | ||
| 85 | + return paths | ||
| 86 | + | ||
| 35 | 87 | ||
| 36 | _extra_packages = [] | 88 | _extra_packages = [] |
| 37 | for _subdir in ("csrc", "common"): | 89 | for _subdir in ("csrc", "common"): |
| @@ -42,16 +94,6 @@ for _subdir in ("csrc", "common"): | |||
| 42 | _extra_packages.append(rel) | 94 | _extra_packages.append(rel) |
| 43 | 95 | ||
| 44 | 96 | ||
| 45 | -def _non_python_files(directory): | ||
| 46 | - paths = [] | ||
| 47 | - for path, dirs, filenames in os.walk(directory): | ||
| 48 | - dirs[:] = [d for d in dirs if d != "__pycache__"] | ||
| 49 | - for filename in filenames: | ||
| 50 | - if filename.endswith((".h", ".cpp", ".md")): | ||
| 51 | - paths.append(os.path.join(path, filename)) | ||
| 52 | - return paths | ||
| 53 | - | ||
| 54 | - | ||
| 55 | # --- 收集 ops-nn/ 下所有 torch_extension/ 中的算子文件 --- | 97 | # --- 收集 ops-nn/ 下所有 torch_extension/ 中的算子文件 --- |
| 56 | _op_category_inits = {} | 98 | _op_category_inits = {} |
| 57 | _op_py_files = [] | 99 | _op_py_files = [] |
| @@ -67,10 +109,14 @@ for cat in sorted(os.listdir(OPS_NN_ROOT)): | |||
| 67 | _op_category_inits[cat] = cat_init_src | 109 | _op_category_inits[cat] = cat_init_src |
| 68 | 110 | ||
| 69 | for name in sorted(os.listdir(cat_path)): | 111 | for name in sorted(os.listdir(cat_path)): |
| 112 | + if _selected_ops is not None and name not in _selected_ops: | ||
| 113 | + continue | ||
| 114 | + | ||
| 70 | torch_extension = os.path.join(cat_path, name, "torch_extension") | 115 | torch_extension = os.path.join(cat_path, name, "torch_extension") |
| 71 | if not os.path.isdir(torch_extension): | 116 | if not os.path.isdir(torch_extension): |
| 72 | continue | 117 | continue |
| 73 | 118 | ||
| 119 | + _selected_op_categories.append((cat, name)) | ||
| 74 | for f in ("__init__.py", "%s.py" % name): | 120 | for f in ("__init__.py", "%s.py" % name): |
| 75 | f_src = os.path.join(torch_extension, f) | 121 | f_src = os.path.join(torch_extension, f) |
| 76 | if os.path.isfile(f_src): | 122 | if os.path.isfile(f_src): |
| @@ -94,6 +140,16 @@ for cat in sorted(os.listdir(OPS_NN_ROOT)): | |||
| 94 | ) | 140 | ) |
| 95 | 141 | ||
| 96 | 142 | ||
| 143 | +_sorted_selected_op_categories = sorted(set(_selected_op_categories)) | ||
| 144 | + | ||
| 145 | +_entry_points = [] | ||
| 146 | +if _selected_ops is not None: | ||
| 147 | + for _cat, _op_name in _sorted_selected_op_categories: | ||
| 148 | + _entry_points.append( | ||
| 149 | + "%s = %s.ops.%s.%s:%s" % (_op_name, PACKAGE_NAME, _cat, _op_name, _op_name) | ||
| 150 | + ) | ||
| 151 | + | ||
| 152 | + | ||
| 97 | class Clean(Command): | 153 | class Clean(Command): |
| 98 | description = "clean build artifacts" | 154 | description = "clean build artifacts" |
| 99 | user_options = [] | 155 | user_options = [] |
| @@ -110,6 +166,10 @@ class Clean(Command): | |||
| 110 | if os.path.isdir(path): | 166 | if os.path.isdir(path): |
| 111 | shutil.rmtree(path) | 167 | shutil.rmtree(path) |
| 112 | logger.info("removing %s", path) | 168 | logger.info("removing %s", path) |
| 169 | + if PACKAGE_NAME != BASE_PACKAGE_NAME: | ||
| 170 | + link = os.path.join(HERE, PACKAGE_NAME) | ||
| 171 | + if os.path.islink(link): | ||
| 172 | + os.remove(link) | ||
| 113 | 173 | ||
| 114 | 174 | ||
| 115 | class BuildPyWithOps(_build_py): | 175 | class BuildPyWithOps(_build_py): |
| @@ -117,28 +177,89 @@ class BuildPyWithOps(_build_py): | |||
| 117 | _clean_build_artifacts() | 177 | _clean_build_artifacts() |
| 118 | super().run() | 178 | super().run() |
| 119 | build_pkg = os.path.join(self.build_lib, PACKAGE_NAME) | 179 | build_pkg = os.path.join(self.build_lib, PACKAGE_NAME) |
| 120 | - for category, init_src in _op_category_inits.items(): | 180 | + if _selected_ops is not None: |
| 121 | - dst = os.path.join(build_pkg, "ops", category, "__init__.py") | 181 | + for subdir in ("ops", "csrc"): |
| 122 | - os.makedirs(os.path.dirname(dst), exist_ok=True) | 182 | + base_dir = os.path.join(build_pkg, subdir) |
| 123 | - shutil.copy2(init_src, dst) | 183 | + if not os.path.isdir(base_dir): |
| 184 | + continue | ||
| 185 | + for cat in os.listdir(base_dir): | ||
| 186 | + cat_dir = os.path.join(base_dir, cat) | ||
| 187 | + if not os.path.isdir(cat_dir): | ||
| 188 | + continue | ||
| 189 | + for name in os.listdir(cat_dir): | ||
| 190 | + if name not in _selected_ops and name != "__pycache__": | ||
| 191 | + target = os.path.join(cat_dir, name) | ||
| 192 | + if os.path.isdir(target): | ||
| 193 | + shutil.rmtree(target) | ||
| 194 | + logger.info( | ||
| 195 | + "removing centralized %s/%s/%s", subdir, cat, name | ||
| 196 | + ) | ||
| 197 | + ops_cat_inits = {} | ||
| 198 | + for cat, name in _sorted_selected_op_categories: | ||
| 199 | + if cat not in ops_cat_inits: | ||
| 200 | + ops_cat_inits[cat] = [] | ||
| 201 | + ops_cat_inits[cat].append(name) | ||
| 202 | + for cat, names in ops_cat_inits.items(): | ||
| 203 | + dst = os.path.join(build_pkg, "ops", cat, "__init__.py") | ||
| 204 | + os.makedirs(os.path.dirname(dst), exist_ok=True) | ||
| 205 | + with open(dst, "w") as f: | ||
| 206 | + for name in names: | ||
| 207 | + f.write("from .%s import %s\n" % (name, name)) | ||
| 208 | + else: | ||
| 209 | + for category, init_src in _op_category_inits.items(): | ||
| 210 | + dst = os.path.join(build_pkg, "ops", category, "__init__.py") | ||
| 211 | + os.makedirs(os.path.dirname(dst), exist_ok=True) | ||
| 212 | + shutil.copy2(init_src, dst) | ||
| 124 | for rel_path, src_abs in _op_py_files: | 213 | for rel_path, src_abs in _op_py_files: |
| 125 | dst = os.path.join(build_pkg, rel_path) | 214 | dst = os.path.join(build_pkg, rel_path) |
| 126 | os.makedirs(os.path.dirname(dst), exist_ok=True) | 215 | os.makedirs(os.path.dirname(dst), exist_ok=True) |
| 127 | - shutil.copy2(src_abs, dst) | 216 | + if PACKAGE_NAME != BASE_PACKAGE_NAME: |
| 217 | + with open(src_abs, "r") as _f: | ||
| 218 | + _content = _f.read() | ||
| 219 | + _content = _content.replace( | ||
| 220 | + "from cann_ops_nn.op_builder", | ||
| 221 | + "from %s.op_builder" % PACKAGE_NAME, | ||
| 222 | + ) | ||
| 223 | + _content = _content.replace( | ||
| 224 | + "import cann_ops_nn.op_builder", | ||
| 225 | + "import %s.op_builder" % PACKAGE_NAME, | ||
| 226 | + ) | ||
| 227 | + with open(dst, "w") as _f: | ||
| 228 | + _f.write(_content) | ||
| 229 | + else: | ||
| 230 | + shutil.copy2(src_abs, dst) | ||
| 128 | for rel_path, src_abs in _op_cpp_files: | 231 | for rel_path, src_abs in _op_cpp_files: |
| 129 | dst = os.path.join(build_pkg, rel_path) | 232 | dst = os.path.join(build_pkg, rel_path) |
| 130 | os.makedirs(os.path.dirname(dst), exist_ok=True) | 233 | os.makedirs(os.path.dirname(dst), exist_ok=True) |
| 131 | shutil.copy2(src_abs, dst) | 234 | shutil.copy2(src_abs, dst) |
| 132 | 235 | ||
| 133 | 236 | ||
| 237 | +_all_packages = find_packages() + _extra_packages | ||
| 238 | +if _selected_ops is not None: | ||
| 239 | + _prefix = BASE_PACKAGE_NAME + "." | ||
| 240 | + _all_packages = [ | ||
| 241 | + pkg.replace(_prefix, PACKAGE_NAME + ".", 1) if pkg.startswith(_prefix) else pkg | ||
| 242 | + for pkg in _all_packages | ||
| 243 | + if pkg == PACKAGE_NAME or pkg.startswith(PACKAGE_NAME + ".") | ||
| 244 | + ] | ||
| 245 | + | ||
| 246 | + | ||
| 247 | +def _clean_symlink(): | ||
| 248 | + if PACKAGE_NAME != BASE_PACKAGE_NAME: | ||
| 249 | + link = os.path.join(HERE, PACKAGE_NAME) | ||
| 250 | + if os.path.islink(link): | ||
| 251 | + os.remove(link) | ||
| 252 | + | ||
| 253 | + | ||
| 134 | class SdistWithClean(_sdist): | 254 | class SdistWithClean(_sdist): |
| 135 | def run(self): | 255 | def run(self): |
| 136 | _clean_build_artifacts() | 256 | _clean_build_artifacts() |
| 137 | super().run() | 257 | super().run() |
| 258 | + _clean_symlink() | ||
| 138 | 259 | ||
| 139 | 260 | ||
| 140 | def _clean_build_artifacts(): | 261 | def _clean_build_artifacts(): |
| 141 | - for pattern in ("build", "*.egg-info"): | 262 | + for pattern in ("build", "dist", "*.egg-info"): |
| 142 | for path in glob.glob(os.path.join(HERE, pattern)): | 263 | for path in glob.glob(os.path.join(HERE, pattern)): |
| 143 | if os.path.isdir(path): | 264 | if os.path.isdir(path): |
| 144 | shutil.rmtree(path) | 265 | shutil.rmtree(path) |
| @@ -149,8 +270,9 @@ if _bdist_wheel is not None: | |||
| 149 | 270 | ||
| 150 | class BdistWheelWithClean(_bdist_wheel): | 271 | class BdistWheelWithClean(_bdist_wheel): |
| 151 | def run(self): | 272 | def run(self): |
| 152 | - super().run() | ||
| 153 | _clean_build_artifacts() | 273 | _clean_build_artifacts() |
| 274 | + super().run() | ||
| 275 | + _clean_symlink() | ||
| 154 | else: | 276 | else: |
| 155 | BdistWheelWithClean = None | 277 | BdistWheelWithClean = None |
| 156 | 278 | ||
| @@ -169,9 +291,12 @@ setup( | |||
| 169 | version=VERSION, | 291 | version=VERSION, |
| 170 | description=DESCRIPTION, | 292 | description=DESCRIPTION, |
| 171 | author="CANN", | 293 | author="CANN", |
| 172 | - packages=find_packages() + _extra_packages, | 294 | + license="CANN Open Software License Agreement Version 2.0", |
| 173 | - include_package_data=True, | 295 | + url="https://gitcode.com/cann/ops-nn/tree/master/torch_extension", |
| 296 | + install_requires=["torch>=2.6.0", "torch_npu"], | ||
| 297 | + packages=_all_packages, | ||
| 174 | package_data={PACKAGE_NAME: _non_python_files(_src_path)}, | 298 | package_data={PACKAGE_NAME: _non_python_files(_src_path)}, |
| 299 | + entry_points={"cann_ops_nn.ops": _entry_points} if _entry_points else {}, | ||
| 175 | cmdclass=_cmdclass, | 300 | cmdclass=_cmdclass, |
| 176 | zip_safe=False, | 301 | zip_safe=False, |
| 177 | ) | 302 | ) |
【openlibing.ci】检测到当前PR中存在代码检查告警抑制 3 处,详情见下表,请Committer检视合理性。 / Detected 3 code check alert suppression(s) in this PR, see table below. Committers please review.
init.py
import torch # noqa: F401init.py
import torch_npu # noqa: F401init.py
from .ops import * # noqa: F403