已合并
feat(build): Support whl format. #1075
Alizarin创建于 11 天前
feat(build): Support whl format. #1075
已合并
共 35 个文件变更+1933-943
| @@ -47,6 +47,7 @@ option(ENABLE_TESTS "Enable tests" OFF) # 算子级 dispatcher 据此派发 tes | |||
| 47 | include(cmake/config.cmake) | 47 | include(cmake/config.cmake) |
| 48 | include(cmake/func.cmake) | 48 | include(cmake/func.cmake) |
| 49 | include(cmake/obj_func.cmake) | 49 | include(cmake/obj_func.cmake) |
| 50 | +include(cmake/aicpu.cmake) | ||
| 50 | 51 | ||
| 51 | ######################################################################################################################## | 52 | ######################################################################################################################## |
| 52 | # 编译流程 | 53 | # 编译流程 |
| @@ -60,7 +61,7 @@ if (ENABLE_TESTS) | |||
| 60 | add_subdirectory(tests) | 61 | add_subdirectory(tests) |
| 61 | endif() | 62 | endif() |
| 62 | if (ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) | 63 | if (ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) |
| 63 | - add_subdirectory(torch_extension) | 64 | + add_subdirectory(python) |
| 64 | endif() | 65 | endif() |
| 65 | 66 | ||
| 66 | # 算子接入: 发现 ops/{pro,tensor} 树, add 算子级目录(dispatcher 派发 op_host/tests). | 67 | # 算子接入: 发现 ops/{pro,tensor} 树, add 算子级目录(dispatcher 派发 op_host/tests). |
| @@ -73,6 +74,11 @@ if (ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) | |||
| 73 | gym_finalize_torch_bindings() | 74 | gym_finalize_torch_bindings() |
| 74 | endif() | 75 | endif() |
| 75 | 76 | ||
| 77 | +# AICPU kernel 汇总: 所有算子接入后链接单一 .so 并合并 opInfo json(仅存在 aicpu kernel 时生效) | ||
| 78 | +if (NOT PREPARE_BUILD) | ||
| 79 | + gym_finalize_aicpu_kernels() | ||
| 80 | +endif() | ||
| 81 | + | ||
| 76 | # 读回算子登记, 创建 host 侧目标(三 .so/核对程序)与 kernel 编译链 | 82 | # 读回算子登记, 创建 host 侧目标(三 .so/核对程序)与 kernel 编译链 |
| 77 | include(cmake/custom_build.cmake) # TODO 看看能不能去掉 | 83 | include(cmake/custom_build.cmake) # TODO 看看能不能去掉 |
| 78 | 84 | ||
| @@ -85,48 +91,58 @@ include(cmake/custom_build.cmake) # TODO 看看能不能去掉 | |||
| 85 | include(version.cmake) | 91 | include(version.cmake) |
| 86 | add_cann_version_info_targets() | 92 | add_cann_version_info_targets() |
| 87 | 93 | ||
| 88 | -# run 包脚本骨架安装: install.sh 入口 + help/cleanup + version.info. | 94 | +# run 包专属安装(安装器脚本骨架 + version.info -> share/info): whl 布局不需要 |
| 89 | -# 组件名与 install COMPONENT 一致(set_cann_cpack_config 按组件收集 staging). | 95 | +# (wheel 无安装器, Python 层由 pip 承载), GYM_WHL_LAYOUT 时整体跳过. |
| 90 | -set(_GymScriptPrefix "${PYPTO_GYM_SRC_DIR}/scripts/package/${VENDOR_NAME}/scripts") | 96 | +if (NOT GYM_WHL_LAYOUT) |
| 91 | -install(DIRECTORY "${_GymScriptPrefix}/" | 97 | + # run 包脚本骨架安装: install.sh 入口 + help/cleanup + version.info. |
| 92 | - DESTINATION share/info/${VENDOR_NAME}/script | 98 | + # 组件名与 install COMPONENT 一致(set_cann_cpack_config 按组件收集 staging). |
| 93 | - FILE_PERMISSIONS | 99 | + set(_GymScriptPrefix "${PYPTO_GYM_SRC_DIR}/scripts/package/${VENDOR_NAME}/scripts") |
| 94 | - OWNER_READ OWNER_WRITE OWNER_EXECUTE # 文件权限 | 100 | + install(DIRECTORY "${_GymScriptPrefix}/" |
| 95 | - GROUP_READ GROUP_EXECUTE | 101 | + DESTINATION share/info/${VENDOR_NAME}/script |
| 96 | - WORLD_READ WORLD_EXECUTE | 102 | + FILE_PERMISSIONS |
| 97 | - DIRECTORY_PERMISSIONS | 103 | + OWNER_READ OWNER_WRITE OWNER_EXECUTE # 文件权限 |
| 98 | - OWNER_READ OWNER_WRITE OWNER_EXECUTE # 目录权限 | 104 | + GROUP_READ GROUP_EXECUTE |
| 99 | - GROUP_READ GROUP_EXECUTE | 105 | + WORLD_READ WORLD_EXECUTE |
| 100 | - WORLD_READ WORLD_EXECUTE | 106 | + DIRECTORY_PERMISSIONS |
| 101 | - COMPONENT ${VENDOR_NAME} | 107 | + OWNER_READ OWNER_WRITE OWNER_EXECUTE # 目录权限 |
| 102 | -) | 108 | + GROUP_READ GROUP_EXECUTE |
| 109 | + WORLD_READ WORLD_EXECUTE | ||
| 110 | + COMPONENT ${VENDOR_NAME} | ||
| 111 | + ) | ||
| 103 | 112 | ||
| 104 | -# cann-cmake 公共脚本 | 113 | + # cann-cmake 公共脚本 |
| 105 | -set(SCRIPTS_FILES | 114 | + set(SCRIPTS_FILES |
| 106 | - ${CANN_CMAKE_DIR}/scripts/install/check_version_required.awk | 115 | + ${CANN_CMAKE_DIR}/scripts/install/check_version_required.awk |
| 107 | - ${CANN_CMAKE_DIR}/scripts/install/common_func_v2.inc | 116 | + ${CANN_CMAKE_DIR}/scripts/install/common_func_v2.inc |
| 108 | - ${CANN_CMAKE_DIR}/scripts/install/common_func.inc | 117 | + ${CANN_CMAKE_DIR}/scripts/install/common_func.inc |
| 109 | - ${CANN_CMAKE_DIR}/scripts/install/common_installer.inc | 118 | + ${CANN_CMAKE_DIR}/scripts/install/common_installer.inc |
| 110 | - ${CANN_CMAKE_DIR}/scripts/install/common_interface.csh | 119 | + ${CANN_CMAKE_DIR}/scripts/install/common_interface.csh |
| 111 | - ${CANN_CMAKE_DIR}/scripts/install/common_interface.fish | 120 | + ${CANN_CMAKE_DIR}/scripts/install/common_interface.fish |
| 112 | - ${CANN_CMAKE_DIR}/scripts/install/common_interface.sh | 121 | + ${CANN_CMAKE_DIR}/scripts/install/common_interface.sh |
| 113 | - ${CANN_CMAKE_DIR}/scripts/install/install_common_parser.sh | 122 | + ${CANN_CMAKE_DIR}/scripts/install/install_common_parser.sh |
| 114 | - ${CANN_CMAKE_DIR}/scripts/install/multi_version.inc | 123 | + ${CANN_CMAKE_DIR}/scripts/install/multi_version.inc |
| 115 | - ${CANN_CMAKE_DIR}/scripts/install/script_operator.inc | 124 | + ${CANN_CMAKE_DIR}/scripts/install/script_operator.inc |
| 116 | - ${CANN_CMAKE_DIR}/scripts/install/version_cfg.inc | 125 | + ${CANN_CMAKE_DIR}/scripts/install/version_cfg.inc |
| 117 | - ${CANN_CMAKE_DIR}/scripts/install/version_compatiable.inc | 126 | + ${CANN_CMAKE_DIR}/scripts/install/version_compatiable.inc |
| 118 | -) | 127 | + ) |
| 119 | -install(FILES ${SCRIPTS_FILES} | 128 | + install(FILES ${SCRIPTS_FILES} |
| 120 | - DESTINATION share/info/${VENDOR_NAME}/script | 129 | + DESTINATION share/info/${VENDOR_NAME}/script |
| 121 | - COMPONENT ${VENDOR_NAME} | 130 | + COMPONENT ${VENDOR_NAME} |
| 122 | -) | 131 | + ) |
| 123 | 132 | ||
| 124 | -# version 配置 | 133 | + # version 配置 |
| 125 | -# 由 add_cann_version_info_targets 命令产出 | 134 | + # 由 add_cann_version_info_targets 命令产出 |
| 126 | -install(FILES ${CMAKE_BINARY_DIR}/version.${VENDOR_NAME}.info | 135 | + install(FILES ${CMAKE_BINARY_DIR}/version.${VENDOR_NAME}.info |
| 127 | - DESTINATION share/info/${VENDOR_NAME} | 136 | + DESTINATION share/info/${VENDOR_NAME} |
| 128 | - RENAME version.info | 137 | + RENAME version.info |
| 129 | - COMPONENT ${VENDOR_NAME} | 138 | + COMPONENT ${VENDOR_NAME} |
| 130 | -) | 139 | + ) |
| 131 | 140 | ||
| 132 | -set_cann_cpack_config(${VENDOR_NAME} COMPUTE_UNIT ${ASCEND_COMPUTE_UNIT} PACKAGE_TYPE "${PACKAGE_TYPE}") | 141 | + # CPack/.run 打包配置: 仅 run 产物主 configure 需要。set_cann_cpack_config 内部会 |
| 142 | + # 无条件预取 makeself 到 CANN_3RD_LIB_PATH(缺省 third_party/), 而 makeself 只被 | ||
| 143 | + # `package` 目标消费 —— whl 布局与 prepare 二次 configure 都不打包, 跳过以避免 | ||
| 144 | + # 无谓的三方件下载(whl 流程不应触碰 third_party/)。 | ||
| 145 | + if (NOT PREPARE_BUILD) | ||
| 146 | + set_cann_cpack_config(${VENDOR_NAME} COMPUTE_UNIT ${ASCEND_COMPUTE_UNIT} PACKAGE_TYPE "${PACKAGE_TYPE}") | ||
| 147 | + endif () | ||
| 148 | +endif () | ||
| @@ -12,7 +12,7 @@ PyPTO-Gym 是基于 PyPTO 编程框架构建的样例仓库,面向华为昇腾 | |||
| 12 | - **编程框架**:PyPTO,基于 Tile 的编程模型 | 12 | - **编程框架**:PyPTO,基于 Tile 的编程模型 |
| 13 | - **内容**:融合算子样例 + 大模型适配样例 | 13 | - **内容**:融合算子样例 + 大模型适配样例 |
| 14 | 14 | ||
| 15 | -Pro 算子的构建、安装与测试见[构建指南](docs/build-guide.md),预编译 Torch 接口和新算子接入见[Torch 绑定说明](torch_extension/README.md)。 | 15 | +Pro 算子的构建、安装与测试见[构建指南](docs/build-guide.md),算子接口的获取方式见 `pypto_gym` 包内文档(`help(pypto_gym)`、`get_ops()`、`prewarm()`)。 |
| 16 | `.run` 使用 `--ops ALL`(或省略 `--ops`)时,只构建 [ops/pro/build_ops.yaml](ops/pro/build_ops.yaml) 中列出的算子;路径相对于 `ops/pro`,注释对应行即可取消该算子的构建。 | 16 | `.run` 使用 `--ops ALL`(或省略 `--ops`)时,只构建 [ops/pro/build_ops.yaml](ops/pro/build_ops.yaml) 中列出的算子;路径相对于 `ops/pro`,注释对应行即可取消该算子的构建。 |
| 17 | 17 | ||
| 18 | ## 核心特性 | 18 | ## 核心特性 |
| @@ -12,10 +12,12 @@ | |||
| 12 | 12 | ||
| 13 | This file provides a unified build entry point for PyPTO-GYM project, supporting dual product modes: | 13 | This file provides a unified build entry point for PyPTO-GYM project, supporting dual product modes: |
| 14 | 14 | ||
| 15 | - whl: jit direct-call mode, python -m build -> build_out/whl/<soc>/*.whl | 15 | + whl: aot native wheel (torch bindings + vendor binaries), CMake chain -> |
| 16 | + stage (cmake --install, whl layout) -> python -m build -> build_out/whl/<soc>/*.whl | ||
| 16 | run: built-in mode, CMake full chain -> build_out/run/<soc>/ producing custom run packages | 17 | run: built-in mode, CMake full chain -> build_out/run/<soc>/ producing custom run packages |
| 17 | configure -> build -> package (.run) | 18 | configure -> build -> package (.run) |
| 18 | - stest: -s/--stest runs on-board system tests (whl -> jit / run -> aclnn or torch) | 19 | + stest: -s/--stest runs on-board system tests (run -> aclnn or torch / |
| 20 | + whl -> torch, from the wheel installed under build_out) | ||
| 19 | 21 | ||
| 20 | Multi-soc semantics: --soc accepts a comma-separated list; each soc runs a FULL | 22 | Multi-soc semantics: --soc accepts a comma-separated list; each soc runs a FULL |
| 21 | build round in its own binary dir (build/<soc>), producing one .run per soc | 23 | build round in its own binary dir (build/<soc>), producing one .run per soc |
| @@ -0,0 +1,152 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +#[[ | ||
| 11 | +PyPTO AICPU 自定义算子打包链路 | ||
| 12 | + configure 期: pypto_pro codegen 由 op_kernel_aicpu/<op>.py 生成 CpuKernel 适配 TU + Args 头 + opInfo json | ||
| 13 | + 构建期: ARM 交叉编译适配 TU -> 汇总链接 lib<vendor>_aicpu_kernels.so | ||
| 14 | + 安装期: 合并 cust_aicpu_kernel.json, 与 .so 一起落到 vendors/<v>/op_impl/cpu/{aicpu_kernel/impl,config} | ||
| 15 | +与手写 AICPU 算子同一条 custom 包路径: aclnn 侧 ADD_TO_LAUNCHER_LIST_AICPU 拉起, 不经过 Python. | ||
| 16 | +]] | ||
| 17 | + | ||
| 18 | +set(GYM_AICPU_ARM_CXX ${ASCEND_CANN_PACKAGE_PATH}/toolkit/toolchain/hcc/bin/aarch64-target-linux-gnu-g++) | ||
| 19 | + | ||
| 20 | +set(GYM_AICPU_CXX_FLAGS | ||
| 21 | + -std=c++17 -O2 -fPIC -fvisibility=hidden -fvisibility-inlines-hidden -fstack-protector-all | ||
| 22 | + -D_GLIBCXX_USE_CXX11_ABI=1 -Dgoogle=ascend_private -D_FORTIFY_SOURCE=2) | ||
| 23 | + | ||
| 24 | +set(GYM_AICPU_INCLUDES | ||
| 25 | + ${ASCEND_CANN_PACKAGE_PATH}/include | ||
| 26 | + ${ASCEND_CANN_PACKAGE_PATH}/include/external | ||
| 27 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/include | ||
| 28 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/include/external | ||
| 29 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/include/aicpu | ||
| 30 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/include/aicpu/context/common | ||
| 31 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/pkg_inc/aicpu | ||
| 32 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/pkg_inc/aicpu/common | ||
| 33 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/pkg_inc/aicpu/cpu_kernels | ||
| 34 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/pkg_inc/aicpu/aicpu_schedule | ||
| 35 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/pkg_inc/aicpu/queue_schedule | ||
| 36 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/pkg_inc/aicpu/tsd) | ||
| 37 | + | ||
| 38 | +set(GYM_AICPU_INCLUDE_FLAGS "") | ||
| 39 | +foreach(_gym_aicpu_inc IN LISTS GYM_AICPU_INCLUDES) | ||
| 40 | + list(APPEND GYM_AICPU_INCLUDE_FLAGS -I${_gym_aicpu_inc}) | ||
| 41 | +endforeach() | ||
| 42 | + | ||
| 43 | +# enable_pypto_aicpu_kernel(<op_file> [OP_TYPE <type>] [ARCH <arch>]) | ||
| 44 | +# 在算子的 op_kernel_aicpu/CMakeLists.txt 中调用一次; <op_file>.py 即 PyPTO AICPU kernel 源. | ||
| 45 | +function(enable_pypto_aicpu_kernel op_file) | ||
| 46 | + cmake_parse_arguments(PAICPU "" "OP_TYPE;ARCH" "" ${ARGN}) | ||
| 47 | + if(NOT EXISTS ${GYM_AICPU_ARM_CXX}) | ||
| 48 | + message(FATAL_ERROR "enable_pypto_aicpu_kernel: ARM cross compiler not found: ${GYM_AICPU_ARM_CXX}") | ||
| 49 | + endif() | ||
| 50 | + | ||
| 51 | + execute_process( | ||
| 52 | + COMMAND ${Python3_EXECUTABLE} -c | ||
| 53 | + "import os, pypto_pro.runtime.opc as opc; print(os.path.join(os.path.dirname(opc.__file__), 'pypto_aicpu_codegen_cli.py'))" | ||
| 54 | + OUTPUT_VARIABLE _gym_codegen_py | ||
| 55 | + OUTPUT_STRIP_TRAILING_WHITESPACE | ||
| 56 | + RESULT_VARIABLE _gym_codegen_rc | ||
| 57 | + ERROR_QUIET) | ||
| 58 | + if(NOT _gym_codegen_rc EQUAL 0 OR NOT EXISTS "${_gym_codegen_py}") | ||
| 59 | + message(FATAL_ERROR "enable_pypto_aicpu_kernel: pypto_pro aicpu codegen CLI not found") | ||
| 60 | + endif() | ||
| 61 | + | ||
| 62 | + set(_py ${CMAKE_CURRENT_SOURCE_DIR}/${op_file}.py) | ||
| 63 | + if(NOT EXISTS ${_py}) | ||
| 64 | + message(FATAL_ERROR "enable_pypto_aicpu_kernel: kernel python file not found: ${_py}") | ||
| 65 | + endif() | ||
| 66 | + set(_gen ${CMAKE_BINARY_DIR}/aicpu_gen/${op_file}) | ||
| 67 | + file(MAKE_DIRECTORY ${_gen}) | ||
| 68 | + | ||
| 69 | + set(_cmd ${Python3_EXECUTABLE} ${_gym_codegen_py} | ||
| 70 | + --py-file ${_py} --out-dir ${_gen} --op-file ${op_file} --soc ${ASCEND_COMPUTE_UNIT}) | ||
| 71 | + if(PAICPU_ARCH) | ||
| 72 | + list(APPEND _cmd --arch ${PAICPU_ARCH}) | ||
| 73 | + endif() | ||
| 74 | + if(PAICPU_OP_TYPE) | ||
| 75 | + list(APPEND _cmd --op-type ${PAICPU_OP_TYPE}) | ||
| 76 | + endif() | ||
| 77 | + message(STATUS "pypto aicpu codegen: ${op_file} -> ${_gen}") | ||
| 78 | + execute_process(COMMAND ${_cmd} RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _err) | ||
| 79 | + if(NOT _rc EQUAL 0) | ||
| 80 | + message(FATAL_ERROR "pypto aicpu codegen failed for ${op_file}\n${_err}\n${_out}") | ||
| 81 | + endif() | ||
| 82 | + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${_py}) | ||
| 83 | + | ||
| 84 | + # 编译/链接规则统一在顶层 finalize 创建: custom command 的输出仅在定义目录可见, | ||
| 85 | + # 而汇总 .so 在根作用域生成. 此处只登记 codegen 产物. | ||
| 86 | + set_property(GLOBAL APPEND PROPERTY GYM_AICPU_KERNELS "${_gen}|${_py}|${op_file}") | ||
| 87 | + set_property(GLOBAL APPEND PROPERTY GYM_AICPU_ONLY_OPS ${op_file}) | ||
| 88 | + set_property(GLOBAL APPEND PROPERTY GYM_AICPU_JSONS ${_gen}/${op_file}_aicpu.json) | ||
| 89 | +endfunction() | ||
| 90 | + | ||
| 91 | +# gym_finalize_aicpu_kernels(): 所有算子接入后调用, 链接单一 AICPU .so 并合并 opInfo json. | ||
| 92 | +function(gym_finalize_aicpu_kernels) | ||
| 93 | + get_property(_kernels GLOBAL PROPERTY GYM_AICPU_KERNELS) | ||
| 94 | + if(NOT _kernels) | ||
| 95 | + return() | ||
| 96 | + endif() | ||
| 97 | + set(_objs "") | ||
| 98 | + foreach(_entry IN LISTS _kernels) | ||
| 99 | + string(REPLACE "|" ";" _parts "${_entry}") | ||
| 100 | + list(GET _parts 0 _gen) | ||
| 101 | + list(GET _parts 1 _py) | ||
| 102 | + list(GET _parts 2 _op_file) | ||
| 103 | + set(_obj ${_gen}/${_op_file}_aicpu_kernel.o) | ||
| 104 | + add_custom_command(OUTPUT ${_obj} | ||
| 105 | + COMMAND ${GYM_AICPU_ARM_CXX} -c ${_gen}/${_op_file}_aicpu_kernel.cpp -o ${_obj} | ||
| 106 | + -I${_gen} ${GYM_AICPU_INCLUDE_FLAGS} ${GYM_AICPU_CXX_FLAGS} | ||
| 107 | + DEPENDS ${_gen}/${_op_file}_aicpu_kernel.cpp ${_py} | ||
| 108 | + COMMENT "Compiling PyPTO AICPU kernel ${_op_file} (aarch64)" | ||
| 109 | + VERBATIM) | ||
| 110 | + list(APPEND _objs ${_obj}) | ||
| 111 | + endforeach() | ||
| 112 | + get_property(_jsons GLOBAL PROPERTY GYM_AICPU_JSONS) | ||
| 113 | + set(_lib_name lib${VENDOR_NAME}_aicpu_kernels.so) | ||
| 114 | + set(_so ${CMAKE_BINARY_DIR}/${_lib_name}) | ||
| 115 | + | ||
| 116 | + if(EXISTS ${ASCEND_CANN_PACKAGE_PATH}/ops_base/lib64/libaicpu_context.a) | ||
| 117 | + set(_aicpu_context ${ASCEND_CANN_PACKAGE_PATH}/ops_base/lib64/libaicpu_context.a) | ||
| 118 | + else() | ||
| 119 | + set(_aicpu_context ${ASCEND_CANN_PACKAGE_PATH}/lib64/libaicpu_context.a) | ||
| 120 | + endif() | ||
| 121 | + if(EXISTS ${ASCEND_CANN_PACKAGE_PATH}/ops_base/lib64/libbase_ascend_protobuf.a) | ||
| 122 | + set(_protobuf ${ASCEND_CANN_PACKAGE_PATH}/ops_base/lib64/libbase_ascend_protobuf.a) | ||
| 123 | + else() | ||
| 124 | + set(_protobuf ${ASCEND_CANN_PACKAGE_PATH}/lib64/libbase_ascend_protobuf.a) | ||
| 125 | + endif() | ||
| 126 | + | ||
| 127 | + add_custom_command(OUTPUT ${_so} | ||
| 128 | + COMMAND ${GYM_AICPU_ARM_CXX} -shared ${_objs} | ||
| 129 | + -Wl,--whole-archive ${_aicpu_context} ${_protobuf} -Wl,--no-whole-archive | ||
| 130 | + -Wl,-Bsymbolic -Wl,--exclude-libs=libbase_ascend_protobuf.a -Wl,-z,now -s | ||
| 131 | + -o ${_so} | ||
| 132 | + DEPENDS ${_objs} | ||
| 133 | + COMMENT "Linking ${_lib_name} (aarch64)" | ||
| 134 | + COMMAND_EXPAND_LISTS VERBATIM) | ||
| 135 | + add_custom_target(gym_aicpu_kernels ALL DEPENDS ${_so}) | ||
| 136 | + | ||
| 137 | + set(_merged ${CMAKE_BINARY_DIR}/cust_aicpu_kernel.json) | ||
| 138 | + add_custom_command(OUTPUT ${_merged} | ||
| 139 | + COMMAND ${Python3_EXECUTABLE} ${PYPTO_GYM_SRC_DIR}/cmake/scripts/merge_aicpu_json.py | ||
| 140 | + --output ${_merged} --kernel-so ${_lib_name} ${_jsons} | ||
| 141 | + DEPENDS ${_jsons} ${PYPTO_GYM_SRC_DIR}/cmake/scripts/merge_aicpu_json.py | ||
| 142 | + COMMENT "Merging AICPU opInfo json -> ${_merged}" | ||
| 143 | + COMMAND_EXPAND_LISTS VERBATIM) | ||
| 144 | + add_custom_target(gym_aicpu_json ALL DEPENDS ${_merged}) | ||
| 145 | + | ||
| 146 | + install(FILES ${_so} | ||
| 147 | + DESTINATION ${GYM_VENDOR_DEST}/op_impl/cpu/aicpu_kernel/impl | ||
| 148 | + COMPONENT ${VENDOR_NAME}) | ||
| 149 | + install(FILES ${_merged} | ||
| 150 | + DESTINATION ${GYM_VENDOR_DEST}/op_impl/cpu/config | ||
| 151 | + COMPONENT ${VENDOR_NAME}) | ||
| 152 | +endfunction() | ||
| @@ -69,6 +69,22 @@ else () | |||
| 69 | endif () | 69 | endif () |
| 70 | message(STATUS "ASCEND_CANN_PACKAGE_PATH=${ASCEND_CANN_PACKAGE_PATH}") | 70 | message(STATUS "ASCEND_CANN_PACKAGE_PATH=${ASCEND_CANN_PACKAGE_PATH}") |
| 71 | 71 | ||
| 72 | +# 产物安装布局(单一事实来源, 供全部 install 规则消费): | ||
| 73 | +# run 布局(默认): vendor 载荷 packages/vendors/<vendor>/, Python 入口嵌于其 python/ 下; | ||
| 74 | +# whl 布局(GYM_WHL_LAYOUT=ON): 入口包置顶 pypto_gym/(wheel 根), vendor 树嵌于 | ||
| 75 | +# pypto_gym/_opp/vendors/<vendor>/ —— `cmake --install --prefix <whl_src>` 一步 | ||
| 76 | +# 产出 wheel 源码树, 无需二次重排(whl_stage.py 已退役). | ||
| 77 | +# 由 build_ci.py 按 --pkg-type 显式传值(ON/OFF 都显式, 避免同 build 目录切换流程时缓存粘滞). | ||
| 78 | +option(GYM_WHL_LAYOUT "Emit the wheel layout instead of the run vendor layout" OFF) | ||
| 79 | +if (GYM_WHL_LAYOUT) | ||
| 80 | + set(GYM_VENDOR_DEST "pypto_gym/_opp/vendors/${VENDOR_NAME}") | ||
| 81 | + set(GYM_PY_ENTRY_DEST "pypto_gym") | ||
| 82 | +else () | ||
| 83 | + set(GYM_VENDOR_DEST "packages/vendors/${VENDOR_NAME}") | ||
| 84 | + set(GYM_PY_ENTRY_DEST "packages/vendors/${VENDOR_NAME}/python/pypto_gym") | ||
| 85 | +endif () | ||
| 86 | +message(STATUS "GYM_WHL_LAYOUT=${GYM_WHL_LAYOUT} GYM_VENDOR_DEST=${GYM_VENDOR_DEST}") | ||
| 87 | + | ||
| 72 | # CANN 包完整性: op_build 工具存在性 | 88 | # CANN 包完整性: op_build 工具存在性 |
| 73 | set(OP_BUILD_TOOL ${ASCEND_CANN_PACKAGE_PATH}/tools/opbuild/op_build CACHE STRING "op_build tool") | 89 | set(OP_BUILD_TOOL ${ASCEND_CANN_PACKAGE_PATH}/tools/opbuild/op_build CACHE STRING "op_build tool") |
| 74 | if (NOT EXISTS ${OP_BUILD_TOOL}) | 90 | if (NOT EXISTS ${OP_BUILD_TOOL}) |
| @@ -96,18 +112,34 @@ if (NOT PREPARE_BUILD) | |||
| 96 | endforeach() | 112 | endforeach() |
| 97 | endif() | 113 | endif() |
| 98 | 114 | ||
| 99 | -# Torch 依赖(测试桥或正式 Torch 绑定按需启用): | 115 | +# Python3 环境感知(单一感知点): 调 cmake/scripts/analysis_python3_environ.py 生成 |
| 100 | -# 1. 未启用 ENABLE_TESTS/ENABLE_TORCH_BINDINGS 时,run/kernel 构建不依赖 torch. | 116 | +# PY3_MOD_* 变量文件, 供本文件(Torch/torch_npu 查找)与 build_ci.py(wheel 版本标签)消费. |
| 101 | -# 2. 必须在本文件(根作用域 include)中查找: imported target 为目录作用域, 根作用域创建后 | 117 | +# 定义在 config.cmake 而非 func.cmake: 本文件先于 func.cmake 被 include(CMakeLists.txt 顺序). |
| 102 | -# 才能被后续 add_subdirectory 引入的算子 tests 子目录链接. | 118 | +function(gym_analysis_python3_environ OUTPUT_FILE) |
| 103 | -if (ENABLE_TESTS OR ENABLE_TORCH_BINDINGS) | 119 | + get_filename_component(_PyScript "${PYPTO_GYM_SRC_DIR}/cmake/scripts/analysis_python3_environ.py" REALPATH) |
| 104 | execute_process( | 120 | execute_process( |
| 105 | - COMMAND ${Python3_EXECUTABLE} -c "import torch.utils; print(torch.utils.cmake_prefix_path)" | 121 | + COMMAND ${Python3_EXECUTABLE} ${_PyScript} -o=${OUTPUT_FILE} |
| 106 | - OUTPUT_VARIABLE _gym_torch_cmake_prefix | 122 | + RESULT_VARIABLE _Rst) |
| 107 | - OUTPUT_STRIP_TRAILING_WHITESPACE | 123 | + if (NOT ${_Rst} EQUAL 0) |
| 108 | - ERROR_QUIET) | 124 | + message(FATAL_ERROR "Analysis python3 environ failed (rc=${_Rst}).") |
| 109 | - if (_gym_torch_cmake_prefix) | 125 | + endif() |
| 110 | - list(APPEND CMAKE_PREFIX_PATH ${_gym_torch_cmake_prefix}) | 126 | + if (NOT EXISTS ${OUTPUT_FILE}) |
| 127 | + message(FATAL_ERROR "Analysis python3 environ failed, ${OUTPUT_FILE} not exist.") | ||
| 128 | + endif() | ||
| 129 | +endfunction() | ||
| 130 | + | ||
| 131 | +gym_analysis_python3_environ("${CMAKE_BINARY_DIR}/python3_environ.cmake") | ||
| 132 | +include("${CMAKE_BINARY_DIR}/python3_environ.cmake") | ||
| 133 | + | ||
| 134 | +# Torch 依赖(仅测试桥按需启用): | ||
| 135 | +# 1. 正式 Torch 绑定为运行期 JIT 编译(决策 28),构建态不依赖 torch/torch_npu—— | ||
| 136 | +# 这是 CANN 包集成(构建环境无 torch)的硬要求. | ||
| 137 | +# 2. 未启用 ENABLE_TESTS 时,run/kernel/whl 构建不依赖 torch. | ||
| 138 | +# 3. 必须在本文件(根作用域 include)中查找: imported target 为目录作用域, 根作用域创建后 | ||
| 139 | +# 才能被后续 add_subdirectory 引入的算子 tests 子目录链接. | ||
| 140 | +if (ENABLE_TESTS) | ||
| 141 | + if (PY3_MOD_TORCH_CMAKE_DIR) | ||
| 142 | + list(APPEND CMAKE_PREFIX_PATH ${PY3_MOD_TORCH_CMAKE_DIR}) | ||
| 111 | endif() | 143 | endif() |
| 112 | find_package(Torch REQUIRED) | 144 | find_package(Torch REQUIRED) |
| 113 | find_library(TORCH_PYTHON_LIB torch_python PATHS ${TORCH_INSTALL_PREFIX}/lib NO_DEFAULT_PATH) | 145 | find_library(TORCH_PYTHON_LIB torch_python PATHS ${TORCH_INSTALL_PREFIX}/lib NO_DEFAULT_PATH) |
| @@ -18,7 +18,12 @@ list(REMOVE_DUPLICATES _aclnn_default_ops) | |||
| 18 | list(REMOVE_DUPLICATES _aclnn_inner_ops) | 18 | list(REMOVE_DUPLICATES _aclnn_inner_ops) |
| 19 | list(REMOVE_DUPLICATES _aclnn_exclude_ops) | 19 | list(REMOVE_DUPLICATES _aclnn_exclude_ops) |
| 20 | 20 | ||
| 21 | -# inner/exc 无算子时用 stub, 保证 op_build 三份 ops-info.ini 齐套 | 21 | +# inner/exc/default 无算子时用 stub, 保证 op_build 三份 ops-info.ini 齐套 |
| 22 | +if(NOT _aclnn_default_ops) | ||
| 23 | + set(_default_stub ${CMAKE_BINARY_DIR}/op_host_aclnn_stub.cpp) | ||
| 24 | + file(WRITE ${_default_stub} "// stub for empty aclnn op set\n") | ||
| 25 | + target_sources(op_host_aclnn PRIVATE ${_default_stub}) | ||
| 26 | +endif() | ||
| 22 | if(NOT _aclnn_inner_ops) | 27 | if(NOT _aclnn_inner_ops) |
| 23 | set(_inner_stub ${CMAKE_BINARY_DIR}/op_host_aclnn_inner_stub.cpp) | 28 | set(_inner_stub ${CMAKE_BINARY_DIR}/op_host_aclnn_inner_stub.cpp) |
| 24 | file(WRITE ${_inner_stub} "// stub for empty aclnnInner op set\n") | 29 | file(WRITE ${_inner_stub} "// stub for empty aclnnInner op set\n") |
| @@ -148,7 +153,7 @@ endif () | |||
| 148 | # pass-2(PREPARE_BUILD) 跳过: autogen 源尚不存在, 且 host 产物不属于 prepare 阶段 | 153 | # pass-2(PREPARE_BUILD) 跳过: autogen 源尚不存在, 且 host 产物不属于 prepare 阶段 |
| 149 | if (ENABLE_OPS_HOST AND NOT PREPARE_BUILD) | 154 | if (ENABLE_OPS_HOST AND NOT PREPARE_BUILD) |
| 150 | 155 | ||
| 151 | - set(_vendor_dir packages/vendors/${VENDOR_NAME}) | 156 | + set(_vendor_dir ${GYM_VENDOR_DEST}) |
| 152 | set(_arch_lib_dir ${_vendor_dir}/op_proto/lib/linux/${CMAKE_SYSTEM_PROCESSOR}) | 157 | set(_arch_lib_dir ${_vendor_dir}/op_proto/lib/linux/${CMAKE_SYSTEM_PROCESSOR}) |
| 153 | 158 | ||
| 154 | get_property(_infer_srcs GLOBAL PROPERTY GYM_INFER_SRCS) | 159 | get_property(_infer_srcs GLOBAL PROPERTY GYM_INFER_SRCS) |
| @@ -204,6 +209,11 @@ if (ENABLE_OPS_HOST AND NOT PREPARE_BUILD) | |||
| 204 | if (_infer_srcs) | 209 | if (_infer_srcs) |
| 205 | target_sources(ophost_gym_infer_obj PRIVATE ${_infer_srcs}) | 210 | target_sources(ophost_gym_infer_obj PRIVATE ${_infer_srcs}) |
| 206 | endif() | 211 | endif() |
| 212 | + if (NOT _autogen_proto_srcs AND NOT _infer_srcs) | ||
| 213 | + set(_infer_stub ${CMAKE_BINARY_DIR}/ophost_gym_infer_stub.cpp) | ||
| 214 | + file(WRITE ${_infer_stub} "// stub for a build without proto/infershape sources\n") | ||
| 215 | + target_sources(ophost_gym_infer_obj PRIVATE ${_infer_stub}) | ||
| 216 | + endif() | ||
| 207 | target_link_libraries(ophost_gym_infer_obj PRIVATE intf_pub) | 217 | target_link_libraries(ophost_gym_infer_obj PRIVATE intf_pub) |
| 208 | add_dependencies(ophost_gym_infer_obj opbuild_gen_default) | 218 | add_dependencies(ophost_gym_infer_obj opbuild_gen_default) |
| 209 | 219 | ||
| @@ -255,6 +265,11 @@ if (ENABLE_OPS_HOST AND NOT PREPARE_BUILD) | |||
| 255 | endforeach() | 265 | endforeach() |
| 256 | target_sources(ophost_gym_tiling_obj PRIVATE ${_tiling_srcs}) | 266 | target_sources(ophost_gym_tiling_obj PRIVATE ${_tiling_srcs}) |
| 257 | target_link_libraries(ophost_gym_tiling_obj PRIVATE intf_pub) | 267 | target_link_libraries(ophost_gym_tiling_obj PRIVATE intf_pub) |
| 268 | + else() | ||
| 269 | + set(_tiling_stub ${CMAKE_BINARY_DIR}/ophost_gym_tiling_stub.cpp) | ||
| 270 | + file(WRITE ${_tiling_stub} "// stub for a build without tiling sources\n") | ||
| 271 | + target_sources(ophost_gym_tiling_obj PRIVATE ${_tiling_stub}) | ||
| 272 | + target_link_libraries(ophost_gym_tiling_obj PRIVATE intf_pub) | ||
| 258 | endif() | 273 | endif() |
| 259 | 274 | ||
| 260 | # tiling 布局核对程序(tiling_layout_check.py 生成, 运行时布局 vs 编译期真值 | 275 | # tiling 布局核对程序(tiling_layout_check.py 生成, 运行时布局 vs 编译期真值 |
| @@ -310,13 +325,15 @@ if (ENABLE_OPS_HOST AND NOT PREPARE_BUILD) | |||
| 310 | target_link_libraries(ops_aclnn PRIVATE intf_pub) | 325 | target_link_libraries(ops_aclnn PRIVATE intf_pub) |
| 311 | target_include_directories(ops_aclnn PRIVATE ${GYM_HOST_INCLUDES}) | 326 | target_include_directories(ops_aclnn PRIVATE ${GYM_HOST_INCLUDES}) |
| 312 | add_dependencies(ops_aclnn opbuild_gen_default) | 327 | add_dependencies(ops_aclnn opbuild_gen_default) |
| 313 | - # 手写 aclnn 通道: 手写源 whole-archive 一并链入 | 328 | + endif() |
| 314 | - if (_opapi_srcs) | 329 | + |
| 315 | - add_library(gym_opapi_manual STATIC EXCLUDE_FROM_ALL ${_opapi_srcs}) | 330 | + # 手写 aclnn 通道: 手写源单独成静态库, 与自动生成源一起 whole-archive 进 cust_opapi. |
| 316 | - set_target_properties(gym_opapi_manual PROPERTIES POSITION_INDEPENDENT_CODE ON) | 331 | + # 不依赖 op_build 产物, 便于纯手写入口(如 AICPU kernel 的 aclnn 包装)独立接入. |
| 317 | - target_link_libraries(gym_opapi_manual PRIVATE intf_pub) | 332 | + if (_opapi_srcs) |
| 318 | - target_include_directories(gym_opapi_manual PRIVATE ${GYM_HOST_INCLUDES}) | 333 | + add_library(gym_opapi_manual STATIC EXCLUDE_FROM_ALL ${_opapi_srcs}) |
| 319 | - endif() | 334 | + set_target_properties(gym_opapi_manual PROPERTIES POSITION_INDEPENDENT_CODE ON) |
| 335 | + target_link_libraries(gym_opapi_manual PRIVATE intf_pub) | ||
| 336 | + target_include_directories(gym_opapi_manual PRIVATE ${GYM_HOST_INCLUDES}) | ||
| 320 | endif() | 337 | endif() |
| 321 | 338 | ||
| 322 | set(_cust_opapi_stub ${CMAKE_BINARY_DIR}/cust_opapi_stub.cpp) | 339 | set(_cust_opapi_stub ${CMAKE_BINARY_DIR}/cust_opapi_stub.cpp) |
| @@ -324,17 +341,20 @@ if (ENABLE_OPS_HOST AND NOT PREPARE_BUILD) | |||
| 324 | add_library(cust_opapi SHARED EXCLUDE_FROM_ALL ${_cust_opapi_stub}) | 341 | add_library(cust_opapi SHARED EXCLUDE_FROM_ALL ${_cust_opapi_stub}) |
| 325 | target_include_directories(cust_opapi PRIVATE ${GYM_HOST_INCLUDES}) | 342 | target_include_directories(cust_opapi PRIVATE ${GYM_HOST_INCLUDES}) |
| 326 | target_link_directories(cust_opapi PRIVATE ${GYM_HOST_LINK_DIRS}) | 343 | target_link_directories(cust_opapi PRIVATE ${GYM_HOST_LINK_DIRS}) |
| 344 | + set(_cust_opapi_archives "") | ||
| 345 | + if (TARGET ops_aclnn) | ||
| 346 | + list(APPEND _cust_opapi_archives $<TARGET_FILE:ops_aclnn>) | ||
| 347 | + endif () | ||
| 327 | if (TARGET gym_opapi_manual) | 348 | if (TARGET gym_opapi_manual) |
| 349 | + list(APPEND _cust_opapi_archives $<TARGET_FILE:gym_opapi_manual>) | ||
| 350 | + endif () | ||
| 351 | + if (_cust_opapi_archives) | ||
| 328 | target_link_libraries(cust_opapi PRIVATE | 352 | target_link_libraries(cust_opapi PRIVATE |
| 329 | - -Wl,--whole-archive | 353 | + -Wl,--whole-archive ${_cust_opapi_archives} -Wl,--no-whole-archive) |
| 330 | - $<TARGET_FILE:ops_aclnn> | 354 | + endif () |
| 331 | - $<TARGET_FILE:gym_opapi_manual> | 355 | + # 目标级依赖: EXCLUDE_FROM_ALL 静态库只靠文件级依赖不足以被 make 调度 |
| 332 | - -Wl,--no-whole-archive) | 356 | + if (TARGET gym_opapi_manual) |
| 333 | - else () | 357 | + add_dependencies(cust_opapi gym_opapi_manual) |
| 334 | - target_link_libraries(cust_opapi PRIVATE | ||
| 335 | - -Wl,--whole-archive | ||
| 336 | - $<TARGET_FILE:ops_aclnn> | ||
| 337 | - -Wl,--no-whole-archive) | ||
| 338 | endif () | 358 | endif () |
| 339 | target_link_libraries(cust_opapi PRIVATE | 359 | target_link_libraries(cust_opapi PRIVATE |
| 340 | ${GYM_CANN_LIBS_DIR}/libnnopbase.so | 360 | ${GYM_CANN_LIBS_DIR}/libnnopbase.so |
| @@ -343,7 +363,9 @@ if (ENABLE_OPS_HOST AND NOT PREPARE_BUILD) | |||
| 343 | ${GYM_CANN_LIBS_DIR}/libascend_dump.so | 363 | ${GYM_CANN_LIBS_DIR}/libascend_dump.so |
| 344 | ascendalog dl) | 364 | ascendalog dl) |
| 345 | target_link_libraries(cust_opapi PRIVATE intf_pub) | 365 | target_link_libraries(cust_opapi PRIVATE intf_pub) |
| 346 | - add_dependencies(cust_opapi ops_aclnn) | 366 | + if (TARGET ops_aclnn) |
| 367 | + add_dependencies(cust_opapi ops_aclnn) | ||
| 368 | + endif() | ||
| 347 | add_custom_target(ops_gym_host ALL) | 369 | add_custom_target(ops_gym_host ALL) |
| 348 | add_dependencies(ops_gym_host cust_opapi cust_proto cust_opmaster gym_optiling_compat) | 370 | add_dependencies(ops_gym_host cust_opapi cust_proto cust_opmaster gym_optiling_compat) |
| 349 | 371 | ||
| @@ -438,6 +460,15 @@ if (ENABLE_OPS_HOST AND NOT PREPARE_BUILD) | |||
| 438 | install(FILES ${_gym_aclnn_master} DESTINATION ${_vendor_dir}/op_api/include/aclnnop | 460 | install(FILES ${_gym_aclnn_master} DESTINATION ${_vendor_dir}/op_api/include/aclnnop |
| 439 | COMPONENT ${VENDOR_NAME}) | 461 | COMPONENT ${VENDOR_NAME}) |
| 440 | endif() | 462 | endif() |
| 463 | + # 手写 aclnn 头 install: op_host/op_api/*.h(与自动生成头同目录发布) | ||
| 464 | + foreach (_op_dir ${OP_DIR_LIST}) | ||
| 465 | + file(GLOB _manual_aclnn_headers ${_op_dir}/op_host/op_api/*.h) | ||
| 466 | + if (_manual_aclnn_headers) | ||
| 467 | + install(FILES ${_manual_aclnn_headers} | ||
| 468 | + DESTINATION ${_vendor_dir}/op_api/include/aclnnop | ||
| 469 | + COMPONENT ${VENDOR_NAME}) | ||
| 470 | + endif() | ||
| 471 | + endforeach() | ||
| 441 | # proto 头 install: autogen 下全部 *_proto.h | 472 | # proto 头 install: autogen 下全部 *_proto.h |
| 442 | file(GLOB _autogen_proto_headers ${ASCEND_AUTOGEN_DIR}/*_proto.h) | 473 | file(GLOB _autogen_proto_headers ${ASCEND_AUTOGEN_DIR}/*_proto.h) |
| 443 | if (_autogen_proto_headers) | 474 | if (_autogen_proto_headers) |
| @@ -269,6 +269,12 @@ function(add_bin_compile_target) | |||
| 269 | continue() | 269 | continue() |
| 270 | endif () | 270 | endif () |
| 271 | 271 | ||
| 272 | + # 纯 AICPU 算子不参与 AICore kernel 编译链, 由 aicpu.cmake 独立出包 | ||
| 273 | + get_property(_aicpu_only_ops GLOBAL PROPERTY GYM_AICPU_ONLY_OPS) | ||
| 274 | + if (op_file IN_LIST _aicpu_only_ops) | ||
| 275 | + continue() | ||
| 276 | + endif () | ||
| 277 | + | ||
| 272 | set(OP_TARGET_NAME ${op_file}_${BINARY_COMPUTE_UNIT}) | 278 | set(OP_TARGET_NAME ${op_file}_${BINARY_COMPUTE_UNIT}) |
| 273 | if (TARGET ${OP_TARGET_NAME}) | 279 | if (TARGET ${OP_TARGET_NAME}) |
| 274 | # 同算子多 dtype 脚本共享一组 staging 目标 | 280 | # 同算子多 dtype 脚本共享一组 staging 目标 |
| @@ -288,7 +294,7 @@ function(add_bin_compile_target) | |||
| 288 | file(MAKE_DIRECTORY ${OP_SRC_OUT_DIR}) | 294 | file(MAKE_DIRECTORY ${OP_SRC_OUT_DIR}) |
| 289 | 295 | ||
| 290 | # vendors staging: kernel 二进制与配置(COMPONENT 供 CPack 收集) | 296 | # vendors staging: kernel 二进制与配置(COMPONENT 供 CPack 收集) |
| 291 | - set(_kernel_install_dir packages/vendors/${VENDOR_NAME}/op_impl/ai_core/tbe/kernel) | 297 | + set(_kernel_install_dir ${GYM_VENDOR_DEST}/op_impl/ai_core/tbe/kernel) |
| 292 | install(DIRECTORY ${OP_BIN_OUT_DIR} | 298 | install(DIRECTORY ${OP_BIN_OUT_DIR} |
| 293 | DESTINATION ${_kernel_install_dir}/${BINARY_COMPUTE_UNIT} OPTIONAL | 299 | DESTINATION ${_kernel_install_dir}/${BINARY_COMPUTE_UNIT} OPTIONAL |
| 294 | COMPONENT ${VENDOR_NAME}) | 300 | COMPONENT ${VENDOR_NAME}) |
| @@ -372,7 +378,7 @@ function(add_bin_compile_target) | |||
| 372 | foreach(_op_target ${_ops_target_list}) | 378 | foreach(_op_target ${_ops_target_list}) |
| 373 | add_dependencies(${OPS_CONFIG_TARGET} ${_op_target}) | 379 | add_dependencies(${OPS_CONFIG_TARGET} ${_op_target}) |
| 374 | endforeach() | 380 | endforeach() |
| 375 | - set(_kernel_cfg_dir packages/vendors/${VENDOR_NAME}/op_impl/ai_core/tbe/kernel/config/${BINARY_COMPUTE_UNIT}) | 381 | + set(_kernel_cfg_dir ${GYM_VENDOR_DEST}/op_impl/ai_core/tbe/kernel/config/${BINARY_COMPUTE_UNIT}) |
| 376 | install(FILES ${BINARY_INFO_CONFIG_FILE} DESTINATION ${_kernel_cfg_dir} OPTIONAL | 382 | install(FILES ${BINARY_INFO_CONFIG_FILE} DESTINATION ${_kernel_cfg_dir} OPTIONAL |
| 377 | COMPONENT ${VENDOR_NAME}) | 383 | COMPONENT ${VENDOR_NAME}) |
| 378 | install(FILES ${BIN_OUT_DIR}/relocatable_kernel_info_config.json | 384 | install(FILES ${BIN_OUT_DIR}/relocatable_kernel_info_config.json |
| @@ -24,11 +24,15 @@ if (NOT PROJECT_SOURCE_DIR) | |||
| 24 | include("${CANN_3RD_LIB_PATH}/cann-cmake/function/prepare.cmake") | 24 | include("${CANN_3RD_LIB_PATH}/cann-cmake/function/prepare.cmake") |
| 25 | else() | 25 | else() |
| 26 | include(FetchContent) | 26 | include(FetchContent) |
| 27 | + # SOURCE_DIR 把源码落点从默认 ${CMAKE_BINARY_DIR}/_deps 改到三方缓存目录, | ||
| 28 | + # 与上面分支的预置约定同名归一: 主/prepare 两次 configure 共用一份, 跨 -c 持久。 | ||
| 29 | + # 注意: 该缓存不校验版本, 升级 CANN_CMAKE_TAG 时需手动清理 cann-cmake 目录。 | ||
| 27 | if(CANN_3RD_LIB_PATH AND EXISTS "${CANN_3RD_LIB_PATH}/cmake-${CANN_CMAKE_TAG}.tar.gz") | 30 | if(CANN_3RD_LIB_PATH AND EXISTS "${CANN_3RD_LIB_PATH}/cmake-${CANN_CMAKE_TAG}.tar.gz") |
| 28 | FetchContent_Declare( | 31 | FetchContent_Declare( |
| 29 | cann-cmake | 32 | cann-cmake |
| 30 | URL "${CANN_3RD_LIB_PATH}/cmake-${CANN_CMAKE_TAG}.tar.gz" | 33 | URL "${CANN_3RD_LIB_PATH}/cmake-${CANN_CMAKE_TAG}.tar.gz" |
| 31 | URL_HASH SHA256=43fb1a2cb376192bb307bd4003c0c4bd82ab66a7eb62d3ddfa9f70f988b7ff18 | 34 | URL_HASH SHA256=43fb1a2cb376192bb307bd4003c0c4bd82ab66a7eb62d3ddfa9f70f988b7ff18 |
| 35 | + SOURCE_DIR "${CANN_3RD_LIB_PATH}/cann-cmake" | ||
| 32 | ) | 36 | ) |
| 33 | else() | 37 | else() |
| 34 | FetchContent_Declare( | 38 | FetchContent_Declare( |
| @@ -36,6 +40,7 @@ if (NOT PROJECT_SOURCE_DIR) | |||
| 36 | GIT_REPOSITORY https://gitcode.com/cann/cmake.git | 40 | GIT_REPOSITORY https://gitcode.com/cann/cmake.git |
| 37 | GIT_TAG ${CANN_CMAKE_TAG} | 41 | GIT_TAG ${CANN_CMAKE_TAG} |
| 38 | GIT_SHALLOW TRUE | 42 | GIT_SHALLOW TRUE |
| 43 | + SOURCE_DIR "${CANN_3RD_LIB_PATH}/cann-cmake" | ||
| 39 | ) | 44 | ) |
| 40 | endif() | 45 | endif() |
| 41 | FetchContent_GetProperties(cann-cmake) | 46 | FetchContent_GetProperties(cann-cmake) |
| @@ -0,0 +1,131 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +"""Python3 environment analysis (single probe point for the CMake configure stage). | ||
| 12 | + | ||
| 13 | +Probes the build interpreter for torch / torch_npu facts and writes a generated | ||
| 14 | +.cmake file consumed by cmake/config.cmake: | ||
| 15 | + | ||
| 16 | + PYTHON3_VERSION_ID interpreter major.minor | ||
| 17 | + PY3_MOD_TORCH_VERSION torch.__version__ (raw, local part kept) | ||
| 18 | + PY3_MOD_TORCH_ROOT_PATH torch package root | ||
| 19 | + PY3_MOD_TORCH_CMAKE_DIR torch.utils.cmake_prefix_path | ||
| 20 | + PY3_MOD_TORCH_C_GLIBCXX_USE_CXX11_ABI torch._C._GLIBCXX_USE_CXX11_ABI (0/1) | ||
| 21 | + PY3_MOD_TORCH_NPU_VERSION torch_npu.__version__ | ||
| 22 | + PY3_MOD_TORCH_NPU_ROOT_PATH torch_npu package root | ||
| 23 | + | ||
| 24 | +Missing modules yield empty values (probe/policy separation): whether torch or | ||
| 25 | +torch_npu is REQUIRED is decided by the CMake side according to | ||
| 26 | +ENABLE_TESTS / ENABLE_TORCH_BINDINGS. Modeled after pypto's | ||
| 27 | +cmake/scripts/analysis_python3_environ.py. | ||
| 28 | +""" | ||
| 29 | + | ||
| 30 | +import argparse | ||
| 31 | +import logging | ||
| 32 | +import os | ||
| 33 | +from pathlib import Path | ||
| 34 | +import sys | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +class Analysis: | ||
| 38 | + def __init__(self, args): | ||
| 39 | + self.output: Path = Path(args.output).resolve() | ||
| 40 | + self.interpreter_version: str = f"{sys.version_info.major}.{sys.version_info.minor}" | ||
| 41 | + self.py_mod_torch_version: str = "" | ||
| 42 | + self.py_mod_torch_root_dir: str = "" | ||
| 43 | + self.py_mod_torch_cmake_dir: str = "" | ||
| 44 | + self.py_mod_torch_c_use_cxx11_abi: int = 1 | ||
| 45 | + self.py_mod_torch_npu_version: str = "" | ||
| 46 | + self.py_mod_torch_npu_root_dir: str = "" | ||
| 47 | + self._init_torch_param() | ||
| 48 | + self._init_torch_npu_param() | ||
| 49 | + | ||
| 50 | + def __str__(self) -> str: | ||
| 51 | + desc = "\nEnviron" | ||
| 52 | + desc += f"\n Output : {self.output}" | ||
| 53 | + desc += f"\n Python3 : {sys.executable} ({self.interpreter_version})" | ||
| 54 | + desc += "\n torch" | ||
| 55 | + desc += f"\n Version : {self.py_mod_torch_version}" | ||
| 56 | + desc += f"\n CMake_Dir : {self.py_mod_torch_cmake_dir}" | ||
| 57 | + desc += f"\n Root_Dir : {self.py_mod_torch_root_dir}" | ||
| 58 | + desc += f"\n _C._GLIBCXX_USE_CXX11_ABI : {self.py_mod_torch_c_use_cxx11_abi}" | ||
| 59 | + desc += "\n torch_npu" | ||
| 60 | + desc += f"\n Version : {self.py_mod_torch_npu_version}" | ||
| 61 | + desc += f"\n Root_Dir : {self.py_mod_torch_npu_root_dir}" | ||
| 62 | + return desc | ||
| 63 | + | ||
| 64 | + @staticmethod | ||
| 65 | + def main(): | ||
| 66 | + """Main processing flow""" | ||
| 67 | + parser = argparse.ArgumentParser(description="Python3-Environ Analysis.", epilog="Best Regards!") | ||
| 68 | + parser.add_argument( | ||
| 69 | + "-o", "--output", type=Path, required=True, help="Specify output .cmake file path.") | ||
| 70 | + ctrl = Analysis(args=parser.parse_args()) | ||
| 71 | + logging.info("%s", ctrl) | ||
| 72 | + ctrl.analysis() | ||
| 73 | + | ||
| 74 | + def analysis(self): | ||
| 75 | + """Write the generated .cmake consumed by cmake/config.cmake.""" | ||
| 76 | + lines = [ | ||
| 77 | + '\n# Python3 Version', | ||
| 78 | + f'\nset(PYTHON3_VERSION_ID "{self.interpreter_version}")', | ||
| 79 | + '\nmessage(STATUS "PYTHON3_VERSION_ID=${PYTHON3_VERSION_ID}")', | ||
| 80 | + '\n', | ||
| 81 | + '\n# Python3 module torch', | ||
| 82 | + f'\nset(PY3_MOD_TORCH_VERSION "{self.py_mod_torch_version}")', | ||
| 83 | + f'\nget_filename_component(PY3_MOD_TORCH_ROOT_PATH "{self.py_mod_torch_root_dir}" REALPATH)', | ||
| 84 | + f'\nget_filename_component(PY3_MOD_TORCH_CMAKE_DIR "{self.py_mod_torch_cmake_dir}" REALPATH)', | ||
| 85 | + f'\nset(PY3_MOD_TORCH_C_GLIBCXX_USE_CXX11_ABI {self.py_mod_torch_c_use_cxx11_abi})', | ||
| 86 | + '\nmessage(STATUS "PY3_MOD_TORCH_VERSION=${PY3_MOD_TORCH_VERSION}")', | ||
| 87 | + '\nmessage(STATUS "PY3_MOD_TORCH_CMAKE_DIR=${PY3_MOD_TORCH_CMAKE_DIR}")', | ||
| 88 | + '\n', | ||
| 89 | + '\n# Python3 module torch_npu', | ||
| 90 | + f'\nset(PY3_MOD_TORCH_NPU_VERSION "{self.py_mod_torch_npu_version}")', | ||
| 91 | + f'\nget_filename_component(PY3_MOD_TORCH_NPU_ROOT_PATH "{self.py_mod_torch_npu_root_dir}" REALPATH)', | ||
| 92 | + '\nmessage(STATUS "PY3_MOD_TORCH_NPU_VERSION=${PY3_MOD_TORCH_NPU_VERSION}")', | ||
| 93 | + '\nmessage(STATUS "PY3_MOD_TORCH_NPU_ROOT_PATH=${PY3_MOD_TORCH_NPU_ROOT_PATH}")', | ||
| 94 | + '\n', | ||
| 95 | + ] | ||
| 96 | + self.output.parent.mkdir(parents=True, exist_ok=True) | ||
| 97 | + with open(str(self.output), "w", encoding="utf-8") as f: | ||
| 98 | + f.writelines(lines) | ||
| 99 | + | ||
| 100 | + def _init_torch_param(self): | ||
| 101 | + os_env = os.environ.copy() | ||
| 102 | + try: | ||
| 103 | + # Keep `import torch` side-effect free: do not autoload device backends. | ||
| 104 | + os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0" | ||
| 105 | + import torch | ||
| 106 | + | ||
| 107 | + self.py_mod_torch_version = str(torch.__version__) | ||
| 108 | + self.py_mod_torch_root_dir = str(Path(torch.__file__).parent) | ||
| 109 | + self.py_mod_torch_cmake_dir = str(Path(torch.utils.cmake_prefix_path).resolve()) | ||
| 110 | + self.py_mod_torch_c_use_cxx11_abi = int(torch._C._GLIBCXX_USE_CXX11_ABI) | ||
| 111 | + except ImportError: | ||
| 112 | + pass | ||
| 113 | + finally: | ||
| 114 | + os.environ.clear() | ||
| 115 | + os.environ.update(os_env) | ||
| 116 | + | ||
| 117 | + def _init_torch_npu_param(self): | ||
| 118 | + if not self.py_mod_torch_version: | ||
| 119 | + return | ||
| 120 | + try: | ||
| 121 | + import torch_npu | ||
| 122 | + | ||
| 123 | + self.py_mod_torch_npu_version = str(getattr(torch_npu, "__version__", "")) | ||
| 124 | + self.py_mod_torch_npu_root_dir = str(Path(torch_npu.__file__).parent) | ||
| 125 | + except ImportError: | ||
| 126 | + pass | ||
| 127 | + | ||
| 128 | + | ||
| 129 | +if __name__ == "__main__": | ||
| 130 | + logging.basicConfig(format='%(asctime)s - %(filename)s:%(lineno)d - %(levelname)s: %(message)s', level=logging.INFO) | ||
| 131 | + Analysis.main() | ||
| @@ -0,0 +1,40 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +"""Merge per-kernel AICPU opInfo json files into the vendor cust_aicpu_kernel.json. | ||
| 12 | + | ||
| 13 | +Every PyPTO AICPU codegen artifact carries the shared kernel library name, so the | ||
| 14 | +merge rewrites ``kernelSo`` to the vendor library built by this repository. | ||
| 15 | +""" | ||
| 16 | +import argparse | ||
| 17 | +import json | ||
| 18 | +from pathlib import Path | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +def main(): | ||
| 22 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 23 | + parser.add_argument("--output", required=True, type=Path) | ||
| 24 | + parser.add_argument("--kernel-so", required=True) | ||
| 25 | + parser.add_argument("inputs", nargs="+", type=Path) | ||
| 26 | + args = parser.parse_args() | ||
| 27 | + | ||
| 28 | + merged = {} | ||
| 29 | + for path in args.inputs: | ||
| 30 | + data = json.loads(path.read_text()) | ||
| 31 | + for op_type, info in data.items(): | ||
| 32 | + if op_type in merged: | ||
| 33 | + raise SystemExit(f"duplicate AICPU op type {op_type} in {path}") | ||
| 34 | + info["opInfo"]["kernelSo"] = args.kernel_so | ||
| 35 | + merged[op_type] = info | ||
| 36 | + args.output.write_text(json.dumps(merged, indent=4) + "\n") | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +if __name__ == "__main__": | ||
| 40 | + main() | ||
| @@ -11,13 +11,14 @@ | |||
| 11 | """ | 11 | """ |
| 12 | PyPTO kernel codegen driver. | 12 | PyPTO kernel codegen driver. |
| 13 | 13 | ||
| 14 | -This script is invoked from CMake configure stage for operators marked with enable_pypto_kernel(<op_file>). | 14 | +Generate AI Core binary headers or a native AICPU fast-launch library for CMake. |
| 15 | -It runs host-side binary artifact preparation and copies all generated artifacts into --out-dir. | 15 | +Generated artifacts go into --out-dir. |
| 16 | """ | 16 | """ |
| 17 | 17 | ||
| 18 | import argparse | 18 | import argparse |
| 19 | import importlib.util | 19 | import importlib.util |
| 20 | import logging | 20 | import logging |
| 21 | +import re | ||
| 21 | import shutil | 22 | import shutil |
| 22 | import sys | 23 | import sys |
| 23 | from pathlib import Path | 24 | from pathlib import Path |
| @@ -75,6 +76,41 @@ def _prepare_binary_headers(py_file: Path, arch: str) -> Path: | |||
| 75 | ).resolve() | 76 | ).resolve() |
| 76 | 77 | ||
| 77 | 78 | ||
| 79 | +def _build_native_aicpu(py_file: Path, out_dir: Path, op_file: str, arch: str): | ||
| 80 | + """Compile the beta AICPU launcher and emit its C ABI declaration.""" | ||
| 81 | + from pypto_pro import ir | ||
| 82 | + from pypto_pro.runtime.aicpu_codegen import generate_aicpu_bare_body, generate_aicpu_sources | ||
| 83 | + from pypto_pro.runtime.aicpu_compile import build_aicpu_jit_so | ||
| 84 | + from pypto_pro.runtime.opc import pypto_aicpu_codegen as offline | ||
| 85 | + | ||
| 86 | + spec = importlib.util.spec_from_file_location(py_file.stem, py_file) | ||
| 87 | + module = importlib.util.module_from_spec(spec) | ||
| 88 | + sys.modules[spec.name] = module | ||
| 89 | + spec.loader.exec_module(module) | ||
| 90 | + kernel = getattr(module, op_file) | ||
| 91 | + arch = offline._setup_arch_env(offline.normalize_arch(arch)) | ||
| 92 | + definition = kernel.to_kernel_def(None, None) | ||
| 93 | + program, _ = definition.parse_target_program(ir.SectionKind.Vector, bound_signature=None) | ||
| 94 | + params = offline._extract_param_specs(program, definition.last_param_directions) | ||
| 95 | + body = generate_aicpu_bare_body(program, arch, kernel.__name__) | ||
| 96 | + sources = generate_aicpu_sources(body, params, kernel.__name__) | ||
| 97 | + | ||
| 98 | + args_header = out_dir / f"{op_file}_aicpu_args.h" | ||
| 99 | + kernel_source = out_dir / f"{op_file}_aicpu.cpp" | ||
| 100 | + host_source = out_dir / f"{op_file}_aicpu_host.cpp" | ||
| 101 | + args_header.write_text(sources["args_header"], encoding="utf-8") | ||
| 102 | + kernel_source.write_text(sources["kernel_source"], encoding="utf-8") | ||
| 103 | + host_source.write_text(sources["host_source"], encoding="utf-8") | ||
| 104 | + declaration = re.search(r'extern "C" uint32_t \w+Run\([^{}]+\)', sources["host_source"]) | ||
| 105 | + if declaration is None: | ||
| 106 | + raise RuntimeError("native AICPU codegen did not emit its Run ABI") | ||
| 107 | + (out_dir / f"{op_file}_native.h").write_text( | ||
| 108 | + "// Generated from PyPTO beta's native host ABI.\n#pragma once\n#include <stdint.h>\n" | ||
| 109 | + + declaration.group() + ";\n", encoding="utf-8") | ||
| 110 | + build_aicpu_jit_so(str(out_dir), op_file, kernel_source, host_source, | ||
| 111 | + out_dir / f"lib{op_file}.so", arch, 600) | ||
| 112 | + | ||
| 113 | + | ||
| 78 | def main(): | 114 | def main(): |
| 79 | parser = argparse.ArgumentParser(description="PyPTO kernel codegen driver") | 115 | parser = argparse.ArgumentParser(description="PyPTO kernel codegen driver") |
| 80 | parser.add_argument("--py-file", required=True, help="kernel python source file") | 116 | parser.add_argument("--py-file", required=True, help="kernel python source file") |
| @@ -87,6 +123,7 @@ def main(): | |||
| 87 | parser.add_argument( | 123 | parser.add_argument( |
| 88 | "--soc", required=True, help="soc version (e.g. ascend950), mapped to pypto arch" | 124 | "--soc", required=True, help="soc version (e.g. ascend950), mapped to pypto arch" |
| 89 | ) | 125 | ) |
| 126 | + parser.add_argument("--aicpu-native", action="store_true", help="build a native AICPU library") | ||
| 90 | args = parser.parse_args() | 127 | args = parser.parse_args() |
| 91 | 128 | ||
| 92 | arch = _ARCH_MAP.get(args.soc) | 129 | arch = _ARCH_MAP.get(args.soc) |
| @@ -100,6 +137,10 @@ def main(): | |||
| 100 | out_dir = Path(args.out_dir) | 137 | out_dir = Path(args.out_dir) |
| 101 | out_dir.mkdir(parents=True, exist_ok=True) | 138 | out_dir.mkdir(parents=True, exist_ok=True) |
| 102 | 139 | ||
| 140 | + if args.aicpu_native: | ||
| 141 | + _build_native_aicpu(py_file, out_dir.resolve(), args.op_file, arch) | ||
| 142 | + return | ||
| 143 | + | ||
| 103 | _install_build_only_torch_stub() | 144 | _install_build_only_torch_stub() |
| 104 | binary_dir = _prepare_binary_headers(py_file, arch) | 145 | binary_dir = _prepare_binary_headers(py_file, arch) |
| 105 | shutil.copytree(binary_dir, out_dir, dirs_exist_ok=True) | 146 | shutil.copytree(binary_dir, out_dir, dirs_exist_ok=True) |
| @@ -10,21 +10,23 @@ PyPTO-Gym 是 PyPTO 实验算子仓,应该提供从算子源码到可安装产 | |||
| 10 | 10 | ||
| 11 | | 产物 | 命令 | 安装方式 | 适用场景 | | 11 | | 产物 | 命令 | 安装方式 | 适用场景 | |
| 12 | | ------------------------------- | -------------------------------------- | --------------- | --------------------------------- | | 12 | | ------------------------------- | -------------------------------------- | --------------- | --------------------------------- | |
| 13 | -| **whl**(JIT 直调) | `python3 build_ci.py --pkg-type whl` | `pip install` | 开发调试、快速验证、PIP源生态发布 | | 13 | +| **whl**(AOT 全量) | `python3 build_ci.py --pkg-type whl` | `pip install` | 开发调试、快速验证、PIP源生态发布 | |
| 14 | | **.run**(custom run 包) | `python3 build_ci.py --pkg-type run` | `bash *.run` | 生产部署、批量交付 | | 14 | | **.run**(custom run 包) | `python3 build_ci.py --pkg-type run` | `bash *.run` | 生产部署、批量交付 | |
| 15 | 15 | ||
| 16 | ### 1.2. 两种产物模式的区别 | 16 | ### 1.2. 两种产物模式的区别 |
| 17 | 17 | ||
| 18 | -#### 1.2.1. whl 模式(JIT 直调) | 18 | +#### 1.2.1. whl 模式(AOT 全量) |
| 19 | 19 | ||
| 20 | ```bash | 20 | ```bash |
| 21 | +python3 build_ci.py --pkg-type whl [--plat_name manylinux2014] | ||
| 21 | pip install build_out/whl/ascend950/pypto_gym-*.whl | 22 | pip install build_out/whl/ascend950/pypto_gym-*.whl |
| 22 | - → import pypto_gym.ops.pro.experimental.flex_attention | 23 | + → py3-none-manylinux<ver>_<arch> 产物(默认 manylinux2014,glibc 基线由标准构建环境保证) |
| 23 | - → 首次调用时 JIT 编译 kernel | 24 | + → 预编译 kernel(_opp vendor 树)+ 绑定 JIT 材料(_bindings,首调对运行时 torch 编译) |
| 24 | ``` | 25 | ``` |
| 25 | 26 | ||
| 26 | -- 算子以 Python 包形态分发,`op_kernel/*.py` 内的 `@pl.jit` kernel 在运行时按需编译 | 27 | +- 版本静态声明于 `pyproject.toml`(发版必 bump,PyPI 同版本不可重传);产物含预编译 kernel 二进制, |
| 27 | -- 适合开发迭代:改完 kernel 直接跑,无需重新打包 | 28 | + 无需运行时编译 kernel;Torch 绑定首调 JIT 编译并缓存 |
| 29 | +- `--plat_name` 可选 `manylinux2014 / manylinux_2_24 / manylinux_2_28`,自动拼接系统架构后缀 | ||
| 28 | 30 | ||
| 29 | ### 1.2.2. run 模式(custom run 包) | 31 | ### 1.2.2. run 模式(custom run 包) |
| 30 | 32 | ||
| @@ -38,13 +40,15 @@ bash cann-950-pypto_gym_9.2.0_linux-aarch64.run | |||
| 38 | - 内含预编译产物:kernel `.o`(按 dtype 组合)+ host 侧三个 `.so` + aclnn 头文件 + ops-info.json | 40 | - 内含预编译产物:kernel `.o`(按 dtype 组合)+ host 侧三个 `.so` + aclnn 头文件 + ops-info.json |
| 39 | - 安装后零 JIT 开销,aclnn 接口直接查找已编译二进制 | 41 | - 安装后零 JIT 开销,aclnn 接口直接查找已编译二进制 |
| 40 | 42 | ||
| 41 | -正式 Torch 绑定默认一并预编译、装入 `.run`,当前支持 | 43 | +正式 Torch 绑定默认随构建产出,当前支持 |
| 42 | -`mega_mhc`。已加载 CANN 基础环境时,安装到其 `opp` 后即可使用 | 44 | +`mega_mhc`、`atten_epilogue`、`quant_sparse_lightning_indexer`。已加载 CANN 基础环境时,安装到其 `opp` 后即可使用 |
| 43 | `pypto_gym.mega_mhc(...)`;直接调用 `torch.ops.pypto_gym.mega_mhc(...)` 前需先 | 45 | `pypto_gym.mega_mhc(...)`;直接调用 `torch.ops.pypto_gym.mega_mhc(...)` 前需先 |
| 44 | `import pypto_gym` 并调用 `pypto_gym.load()`(或先访问任一 `pypto_gym.<op>`)。 | 46 | `import pypto_gym` 并调用 `pypto_gym.load()`(或先访问任一 `pypto_gym.<op>`)。 |
| 45 | -`import pypto_gym` 本身不导入 torch、不加载绑定库,无需运行时编译。 | 47 | +`import pypto_gym` 惰性:不导入 torch、不加载绑定;绑定 `.cpp` 首调对运行时 torch |
| 46 | -构建环境需有 torch/torch_npu;部署环境需与其 ABI 兼容。标准 CANN 安装自动登记 | 48 | +JIT 编译并按构建身份缓存(`prewarm()` 可部署期预编译,镜像期消除首调耗时)。 |
| 47 | -Python 入口并使用绑定库的相对运行时路径,无需额外 source vendor 脚本。 | 49 | +构建链零 torch 依赖;torch 模式 stest 与运行期 JIT 编译需环境内可用的 torch/torch_npu, |
| 50 | +版本由 JIT 现场适配,无 ABI 锁定。标准 CANN 布局由安装器将壳 wheel | ||
| 51 | +pip 登记到 `<cann_root>/python/site-packages`(source CANN 环境后即可 import)。 | ||
| 48 | 自定义位置安装仍可使用 vendor 的 `set_env.bash`。 | 52 | 自定义位置安装仍可使用 vendor 的 `set_env.bash`。 |
| 49 | 53 | ||
| 50 | ```bash | 54 | ```bash |
| @@ -54,10 +58,10 @@ python3 build_ci.py --pkg-type run --ops mega_mhc --stest | |||
| 54 | 默认情况下,`--stest` 对已提供绑定的算子使用 `--mode torch`;未提供绑定的算子使用 `--mode aclnn`。 | 58 | 默认情况下,`--stest` 对已提供绑定的算子使用 `--mode torch`;未提供绑定的算子使用 `--mode aclnn`。 |
| 55 | `run` 默认尝试启用绑定,但若所选算子**都没有**接入绑定,会自动降级为 ACLNN-only 包(打印 | 59 | `run` 默认尝试启用绑定,但若所选算子**都没有**接入绑定,会自动降级为 ACLNN-only 包(打印 |
| 56 | WARNING),仍按原有的 ACLNN 方式调用和测试。仅需 ACLNN 接口时可显式传 | 60 | WARNING),仍按原有的 ACLNN 方式调用和测试。仅需 ACLNN 接口时可显式传 |
| 57 | -`--no-torch-bindings`(手工 CMake 对应 `-DENABLE_TORCH_BINDINGS=OFF`);显式传 | 61 | +`--no-torch-bindings`(手工 CMake 对应 `-DENABLE_TORCH_BINDINGS=OFF`)。 |
| 58 | -`--torch-bindings` 则要求所选算子中至少有一个提供绑定,否则 configure 阶段报错。 | 62 | +`whl`(AOT native wheel)同样默认启用绑定,但所选算子都没有绑定时**直接报错**—— |
| 59 | -`whl` 构建保持 JIT 模式,不启用此绑定。 | 63 | +wheel 的主路径就是 torch.ops;确需 ACLNN-only wheel 时显式传 `--no-torch-bindings`。 |
| 60 | -详细接口和新算子接入方式见 [Torch 绑定说明](../torch_extension/README.md)。 | 64 | +外部调用者获取算子接口的方式(`get_ops` / `prewarm` 契约)见 `pypto_gym` 包内文档(`help(pypto_gym)`);vendor 三级发现与注入机制见 `pypto_gym/__init__.py` 的 `_resolve_vendor_path` docstring。 |
| 61 | 65 | ||
| 62 | ### 1.3. 快速开始 | 66 | ### 1.3. 快速开始 |
| 63 | 67 | ||
| @@ -86,11 +90,13 @@ python3 build_ci.py --pkg-type whl | |||
| 86 | 90 | ||
| 87 | > 添加 `--stest` 会自动设置 `ENABLE_TESTS=ON`,构建测试目标并执行测试;不添加时默认不构建测试桥。手工构建测试桥见 §2.3。 | 91 | > 添加 `--stest` 会自动设置 `ENABLE_TESTS=ON`,构建测试目标并执行测试;不添加时默认不构建测试桥。手工构建测试桥见 §2.3。 |
| 88 | 92 | ||
| 89 | -`.run` 构建的 `--ops ALL`(含省略 `--ops`)使用 | 93 | +`.run` / `whl` 构建的 `--ops ALL`(含省略 `--ops`)使用 |
| 90 | [ops/pro/build_ops.yaml](../ops/pro/build_ops.yaml) 控制发布范围,使用 YAML 路径列表: | 94 | [ops/pro/build_ops.yaml](../ops/pro/build_ops.yaml) 控制发布范围,使用 YAML 路径列表: |
| 91 | 95 | ||
| 92 | ```yaml | 96 | ```yaml |
| 93 | - deepseek_v4_1/mega_mhc | 97 | - deepseek_v4_1/mega_mhc |
| 98 | +- deepseek_v4_1/atten_epilogue | ||
| 99 | +- deepseek_v4_1/quant_sparse_lightning_indexer | ||
| 94 | ``` | 100 | ``` |
| 95 | 101 | ||
| 96 | 路径相对于 `ops/pro`。列出的目录参与构建,未列出的目录不参与;不想构建某项时, | 102 | 路径相对于 `ops/pro`。列出的目录参与构建,未列出的目录不参与;不想构建某项时, |
| @@ -98,7 +104,7 @@ python3 build_ci.py --pkg-type whl | |||
| 98 | 文件缺失、路径错误或全部被注释时构建报错。 | 104 | 文件缺失、路径错误或全部被注释时构建报错。 |
| 99 | `--stest` 使用相同名单,CMake 自动跟踪文件变化。 | 105 | `--stest` 使用相同名单,CMake 自动跟踪文件变化。 |
| 100 | 显式 `--ops mega_mhc` 绕过清单,仍按算子目录名选择;多个名称用逗号分隔。 | 106 | 显式 `--ops mega_mhc` 绕过清单,仍按算子目录名选择;多个名称用逗号分隔。 |
| 101 | -`whl` 的 `ALL` 不受此文件影响。 | 107 | +`whl` 与 `run` 的 `ALL` 均按此清单确定构建与测试范围。 |
| 102 | 108 | ||
| 103 | #### 1.3.3. 安装 .run 包 | 109 | #### 1.3.3. 安装 .run 包 |
| 104 | 110 | ||
| @@ -253,7 +259,7 @@ pytest ops/pro/experimental/flex_attention/tests --mode jit -q | |||
| 253 | 259 | ||
| 254 | ### 2.3. 构建 aclnn 测试桥 | 260 | ### 2.3. 构建 aclnn 测试桥 |
| 255 | 261 | ||
| 256 | -测试桥只在 `ENABLE_TESTS=ON` 时构建。使用 `build_ci.py --pkg-type run --ops flex_attention --no-torch-bindings --stest` 会自动开启该选项并完成构建、安装和测试;也可以手工配置后只构建测试桥: | 262 | +测试桥只在 `ENABLE_TESTS=ON` 时构建。build_ci.py 仅在 **`--pkg-type run` 且 stest 模式为 auto/aclnn** 时自动开启该选项(桥的唯一消费方是 run 的 aclnn 模式,覆盖未绑定算子);whl 流程(stest 仅 torch 模式)与 jit 源码模式永不开启,保持 configure 零 torch 依赖。例如 `build_ci.py --pkg-type run --ops flex_attention --no-torch-bindings --stest` 会自动开启并完成构建、安装和测试;也可以手工配置后只构建测试桥: |
| 257 | 263 | ||
| 258 | ```bash | 264 | ```bash |
| 259 | cmake -S . -B build/ascend950 \ | 265 | cmake -S . -B build/ascend950 \ |
| @@ -2756,7 +2756,7 @@ def workspace_bytes(t): | |||
| 2756 | 2756 | ||
| 2757 | 2757 | ||
| 2758 | @pl.jit( | 2758 | @pl.jit( |
| 2759 | - arch="a5", | 2759 | + arch="3510", |
| 2760 | auto_mutex=True, | 2760 | auto_mutex=True, |
| 2761 | tiling_key=EpilogueKey, | 2761 | tiling_key=EpilogueKey, |
| 2762 | compile_timeout=300, | 2762 | compile_timeout=300, |
| @@ -1,6 +1,6 @@ | |||
| 1 | # QuantSparseLightningIndexer 设计说明(PyPTO-Pro) | 1 | # QuantSparseLightningIndexer 设计说明(PyPTO-Pro) |
| 2 | 2 | ||
| 3 | -对应实现:[quant_sparse_lightning_indexer.py](op_kernel/quant_sparse_lightning_indexer.py)。模块只有一个公开 host 函数和一个 `@pl.jit(arch="a5", auto_mutex=True, tiling_key=QsliKey)` 入口 `quant_sparse_lightning_indexer_kernel`。host 侧校验输入与属性、申报工作区、选择容量档位并启动一次 kernel;设备侧完成候选 K 搬运、QK 点积、head 加权归约、TopK 和分片结果归并。kernel 在构建期由 `asc_opc` 预编译成二进制随 custom run 包交付,运行期经生成的 `aclnnQuantSparseLightningIndexer` 接口调用。接口见 [README.md](README.md),测试及性能记录见 [RESULTS.md](RESULTS.md)。 | 3 | +对应实现:[quant_sparse_lightning_indexer.py](op_kernel/quant_sparse_lightning_indexer.py)。模块只有一个公开 host 函数和一个 `@pl.jit(arch="3510", auto_mutex=True, tiling_key=QsliKey)` 入口 `quant_sparse_lightning_indexer_kernel`。host 侧校验输入与属性、申报工作区、选择容量档位并启动一次 kernel;设备侧完成候选 K 搬运、QK 点积、head 加权归约、TopK 和分片结果归并。kernel 在构建期由 `asc_opc` 预编译成二进制随 custom run 包交付,运行期经生成的 `aclnnQuantSparseLightningIndexer` 接口调用。接口见 [README.md](README.md),测试及性能记录见 [RESULTS.md](RESULTS.md)。 |
| 4 | 4 | ||
| 5 | 5 | ||
| 6 | 本文中,worker 指一个 AIC 及其配合工作的两个 AIV;tile 指一次处理的 512 个候选 token,对应候选数组中连续的 64 个块位置,不要求这些块在逻辑序列或物理内存中连续。GM 是设备全局内存,UB 是 AIV 的本地缓冲区;L1、L0A、L0B 和 L0C 用于 Cube 数据及累加结果。MTE2 负责从 GM 读取数据,MTE3 负责向 GM 等目标搬运数据,FIXPIPE 将 Cube 累加结果交给 AIV。 | 6 | 本文中,worker 指一个 AIC 及其配合工作的两个 AIV;tile 指一次处理的 512 个候选 token,对应候选数组中连续的 64 个块位置,不要求这些块在逻辑序列或物理内存中连续。GM 是设备全局内存,UB 是 AIV 的本地缓冲区;L1、L0A、L0B 和 L0C 用于 Cube 数据及累加结果。MTE2 负责从 GM 读取数据,MTE3 负责向 GM 等目标搬运数据,FIXPIPE 将 Cube 累加结果交给 AIV。 |
Mops/pro/deepseek_v4_1/quant_sparse_lightning_indexer/op_kernel/quant_sparse_lightning_indexer.py+1-1
| @@ -1755,7 +1755,7 @@ def _prepare_addresses64_pow2_vf( | |||
| 1755 | vf.mem_bar() | 1755 | vf.mem_bar() |
| 1756 | 1756 | ||
| 1757 | 1757 | ||
| 1758 | -@pl.jit(arch="a5", auto_mutex=True, tiling_key=QsliKey) | 1758 | +@pl.jit(arch="3510", auto_mutex=True, tiling_key=QsliKey) |
| 1759 | def quant_sparse_lightning_indexer_kernel( | 1759 | def quant_sparse_lightning_indexer_kernel( |
| 1760 | q_ptr: pl.Ptr[pl.DT_UINT8], | 1760 | q_ptr: pl.Ptr[pl.DT_UINT8], |
| 1761 | k_ptr: pl.Ptr[pl.DT_UINT8], | 1761 | k_ptr: pl.Ptr[pl.DT_UINT8], |
| @@ -1573,7 +1573,7 @@ def compute_p_dn(ctx_p, sub_id, qk_vec_db, tile_nz_db, tile_nz_db_1, tmp_max, tm | |||
| 1573 | # ================================================================ | 1573 | # ================================================================ |
| 1574 | # Kernel with NBuffer + auto_mutex | 1574 | # Kernel with NBuffer + auto_mutex |
| 1575 | # ================================================================ | 1575 | # ================================================================ |
| 1576 | -@pl.jit(arch="a5", auto_mutex=True, compile_timeout=200, | 1576 | +@pl.jit(arch="3510", auto_mutex=True, compile_timeout=200, |
| 1577 | tiling_key=FlexAttnTilingKey, | 1577 | tiling_key=FlexAttnTilingKey, |
| 1578 | datatype={ | 1578 | datatype={ |
| 1579 | "query": "io_dtype", | 1579 | "query": "io_dtype", |
| @@ -842,7 +842,7 @@ def scalar_bound(spans_gm, b_idx, span_num, q_abs): | |||
| 842 | # ================================================================ | 842 | # ================================================================ |
| 843 | # Kernel with NBuffer + auto_mutex | 843 | # Kernel with NBuffer + auto_mutex |
| 844 | # ================================================================ | 844 | # ================================================================ |
| 845 | -@pl.jit(arch="a5", auto_mutex=True, compile_timeout=200) | 845 | +@pl.jit(arch="3510", auto_mutex=True, compile_timeout=200) |
| 846 | def flex_attention_bf16( | 846 | def flex_attention_bf16( |
| 847 | q: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC, pl.DYNAMIC], pl.DT_BF16], | 847 | q: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC, pl.DYNAMIC], pl.DT_BF16], |
| 848 | # PagedAttention NHD, exactly as the operator declares them: | 848 | # PagedAttention NHD, exactly as the operator declares them: |
| @@ -15,7 +15,7 @@ build-backend = "setuptools.build_meta" | |||
| 15 | 15 | ||
| 16 | [project] | 16 | [project] |
| 17 | name = "pypto-gym" | 17 | name = "pypto-gym" |
| 18 | -version = "0.1.0" | 18 | +version = "0.1.1" |
| 19 | authors = [ | 19 | authors = [ |
| 20 | { name = "PyPTO Team", email = "pto@cann.osinfra.cn" } | 20 | { name = "PyPTO Team", email = "pto@cann.osinfra.cn" } |
| 21 | ] | 21 | ] |
| @@ -27,7 +27,8 @@ dynamic = ["license"] | |||
| 27 | 27 | ||
| 28 | requires-python = ">=3.9" | 28 | requires-python = ">=3.9" |
| 29 | dependencies = [ | 29 | dependencies = [ |
| 30 | - "pypto>=0.2.1", | 30 | + "pypto>=0.3.0", |
| 31 | + "ninja>=1.11", | ||
| 31 | ] | 32 | ] |
| 32 | keywords = ["python", "pto", "tile", "tile-centric", "ascend", "kernel", "operator"] | 33 | keywords = ["python", "pto", "tile", "tile-centric", "ascend", "kernel", "operator"] |
| 33 | 34 | ||
| @@ -0,0 +1,94 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +#[[ | ||
| 11 | +Runtime-JIT delivery (decision 28): no binding compilation here and no | ||
| 12 | +torch/torch_npu build dependency. The payload ships the binding C++ sources | ||
| 13 | +(_csrc/) plus the Python entry package; pypto_gym._jit compiles the binding | ||
| 14 | +on first call against the user's actual torch/torch_npu (no rpath/RUNPATH | ||
| 15 | +involved, decision 29). | ||
| 16 | + | ||
| 17 | +Install destinations come from the root-scope layout variables (config.cmake): | ||
| 18 | + run layout: GYM_PY_ENTRY_DEST = packages/vendors/<v>/python/pypto_gym | ||
| 19 | + whl layout: GYM_PY_ENTRY_DEST = pypto_gym (wheel root) | ||
| 20 | +The gym_shell component additionally installs the entry tree rooted at | ||
| 21 | +pypto_gym/ in ANY layout, so `cmake --install --component gym_shell` alone | ||
| 22 | +materializes the shell-wheel source tree (cmake stays the single source of | ||
| 23 | +layout truth; build_ci does no source assembly). | ||
| 24 | +]] | ||
| 25 | + | ||
| 26 | +option(GYM_PACKAGE_SHELL_WHL "Embed the Python shell wheel into the run payload" OFF) | ||
| 27 | + | ||
| 28 | +# The repo tree under pypto_gym/ mirrors the installed package layout 1:1 | ||
| 29 | +# (_loader/, _bindings/csrc/gym_aclnn.h, ...), so the directory install carries | ||
| 30 | +# everything except the per-op materials aggregated below and the configure-time | ||
| 31 | +# operators.json. | ||
| 32 | +install(DIRECTORY pypto_gym/ | ||
| 33 | + DESTINATION ${GYM_PY_ENTRY_DEST} | ||
| 34 | + COMPONENT ${VENDOR_NAME} PATTERN "__pycache__" EXCLUDE) | ||
| 35 | + | ||
| 36 | +# Shell-tree component (py3-none-any shell wheel source, layout independent). | ||
| 37 | +install(DIRECTORY pypto_gym/ | ||
| 38 | + DESTINATION pypto_gym | ||
| 39 | + COMPONENT gym_shell PATTERN "__pycache__" EXCLUDE) | ||
| 40 | + | ||
| 41 | +# Called from ops/<paradigm>/<network>/<op>/torch_extension/CMakeLists.txt. | ||
| 42 | +# Per-op materials aggregate into _bindings/{csrc,frontends}/ at install time | ||
| 43 | +# (decentralized ownership, centralized layout); the JIT compile resolves | ||
| 44 | +# `#include "gym_aclnn.h"` from _bindings/csrc/ (same directory as the sources). | ||
| 45 | +function(gym_add_torch_binding op_name) | ||
| 46 | + install(FILES "${op_name}.cpp" | ||
| 47 | + DESTINATION ${GYM_PY_ENTRY_DEST}/_bindings/csrc | ||
| 48 | + COMPONENT ${VENDOR_NAME}) | ||
| 49 | + install(FILES "${op_name}.py" | ||
| 50 | + DESTINATION ${GYM_PY_ENTRY_DEST}/_bindings/frontends | ||
| 51 | + COMPONENT ${VENDOR_NAME}) | ||
| 52 | + install(FILES "${op_name}.cpp" | ||
| 53 | + DESTINATION pypto_gym/_bindings/csrc | ||
| 54 | + COMPONENT gym_shell) | ||
| 55 | + install(FILES "${op_name}.py" | ||
| 56 | + DESTINATION pypto_gym/_bindings/frontends | ||
| 57 | + COMPONENT gym_shell) | ||
| 58 | + set_property(GLOBAL APPEND PROPERTY GYM_TORCH_OPS ${op_name}) | ||
| 59 | +endfunction() | ||
| 60 | + | ||
| 61 | +function(gym_finalize_torch_bindings) | ||
| 62 | + get_property(_ops GLOBAL PROPERTY GYM_TORCH_OPS) | ||
| 63 | + if(NOT _ops) | ||
| 64 | + message(FATAL_ERROR "None of the selected operators provide a Torch binding") | ||
| 65 | + endif() | ||
| 66 | + list(REMOVE_DUPLICATES _ops) | ||
| 67 | + list(JOIN _ops "\", \"" _ops_json) | ||
| 68 | + file(WRITE "${CMAKE_BINARY_DIR}/torch_extension/operators.json" "[\"${_ops_json}\"]\n") | ||
| 69 | + install(FILES "${CMAKE_BINARY_DIR}/torch_extension/operators.json" | ||
| 70 | + DESTINATION ${GYM_PY_ENTRY_DEST}/_bindings | ||
| 71 | + COMPONENT ${VENDOR_NAME}) | ||
| 72 | + install(FILES "${CMAKE_BINARY_DIR}/torch_extension/operators.json" | ||
| 73 | + DESTINATION pypto_gym/_bindings | ||
| 74 | + COMPONENT gym_shell) | ||
| 75 | + message(STATUS "Torch binding sources (runtime JIT): ${_ops}") | ||
| 76 | + | ||
| 77 | + if(GYM_PACKAGE_SHELL_WHL) | ||
| 78 | + # Embed the shell wheel built by build_ci.py between `cmake --build` and | ||
| 79 | + # `package`; the run installer pip-installs it into the CANN | ||
| 80 | + # site-packages (decision 29). Globbed at install time and absence is | ||
| 81 | + # tolerated so manual cmake flows keep working. | ||
| 82 | + install(CODE " | ||
| 83 | + file(GLOB _gym_shell_whls \"${CMAKE_BINARY_DIR}/shell_whl/*.whl\") | ||
| 84 | + if(_gym_shell_whls) | ||
| 85 | + file(INSTALL \${_gym_shell_whls} | ||
| 86 | + DESTINATION \"\${CMAKE_INSTALL_PREFIX}/packages/vendors/${VENDOR_NAME}/python\") | ||
| 87 | + message(STATUS \"Embedded shell wheel(s): \${_gym_shell_whls}\") | ||
| 88 | + else() | ||
| 89 | + message(WARNING \"No shell wheel under ${CMAKE_BINARY_DIR}/shell_whl; \" | ||
| 90 | + \"the run package ships without the Python layer\") | ||
| 91 | + endif()" | ||
| 92 | + COMPONENT ${VENDOR_NAME}) | ||
| 93 | + endif() | ||
| 94 | +endfunction() | ||
| @@ -0,0 +1,213 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | +"""Torch interfaces backed by the installed PyPTO-Gym ACLNN binaries. | ||
| 10 | + | ||
| 11 | +Importing this package is cheap and does not require torch. Bindings are JIT | ||
| 12 | +compiled on first use (pypto_gym._loader) and loaded lazily on first attribute | ||
| 13 | +access, or explicitly through :func:`load` / :func:`prewarm`. This keeps the | ||
| 14 | +namespace importable from tooling that does not have torch/torch_npu installed. | ||
| 15 | +""" | ||
| 16 | +import os | ||
| 17 | +import pkgutil | ||
| 18 | +from pathlib import Path | ||
| 19 | + | ||
| 20 | +from ._loader import binding_names as _binding_names | ||
| 21 | + | ||
| 22 | +_VENDOR_NAME = 'pypto_gym' | ||
| 23 | +_VENDOR_REL = Path('_opp') / 'vendors' / _VENDOR_NAME | ||
| 24 | +_VENDOR_LIB_REL = Path('op_api') / 'lib' / 'libcust_opapi.so' | ||
| 25 | + | ||
| 26 | +_resolved_vendor = None | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def _package_base_dir(): | ||
| 30 | + """pypto-style dual location: cur_dir wins, dist locate validates. | ||
| 31 | + | ||
| 32 | + ``locate_file`` catches packaging anomalies; a mismatch (editable/source | ||
| 33 | + tree) falls back to the directory of this file, which is always truthful. | ||
| 34 | + """ | ||
| 35 | + cur_dir = Path(__file__).resolve().parent | ||
| 36 | + try: | ||
| 37 | + from importlib import metadata | ||
| 38 | + pkg_dir = Path(str(metadata.distribution('pypto-gym').locate_file('pypto_gym'))).resolve() | ||
| 39 | + except Exception: | ||
| 40 | + return cur_dir | ||
| 41 | + return pkg_dir if pkg_dir == cur_dir else cur_dir | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +def _is_vendor(path): | ||
| 45 | + return path is not None and (path / _VENDOR_LIB_REL).is_file() | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +def _discover_vendor(): | ||
| 49 | + """Three-tier vendor discovery (decision 30). Returns Path or None. | ||
| 50 | + | ||
| 51 | + 1. bundled ``_opp`` sibling — community full wheel (form marker) | ||
| 52 | + 2. ``ASCEND_CUSTOM_OPP_PATH`` entries — run installed to a custom location | ||
| 53 | + (set_env.bash), or user-managed | ||
| 54 | + 3. ``$ASCEND_OPP_PATH/vendors`` — run installed into the standard | ||
| 55 | + CANN opp, nothing sourced | ||
| 56 | + (ops-transformer _custom_opp_paths | ||
| 57 | + style scan; ASCEND_HOME_PATH/opp | ||
| 58 | + as equivalent fallback) | ||
| 59 | + Every tier is validated by op_api/lib/libcust_opapi.so; invalid hits | ||
| 60 | + degrade to the next tier. No rpath/RUNPATH is involved anywhere | ||
| 61 | + (decision 29): the C++ side consumes ASCEND_CUSTOM_OPP_PATH via | ||
| 62 | + gym_aclnn.h's dlopen scan. | ||
| 63 | + """ | ||
| 64 | + bundled = _package_base_dir() / _VENDOR_REL | ||
| 65 | + if _is_vendor(bundled): | ||
| 66 | + return bundled | ||
| 67 | + for entry in os.environ.get('ASCEND_CUSTOM_OPP_PATH', '').split(':'): | ||
| 68 | + entry = entry.strip() | ||
| 69 | + if not entry: | ||
| 70 | + continue | ||
| 71 | + for cand in (Path(entry), Path(entry) / _VENDOR_NAME): | ||
| 72 | + if _is_vendor(cand): | ||
| 73 | + return cand | ||
| 74 | + opp = os.environ.get('ASCEND_OPP_PATH', '') | ||
| 75 | + if not opp: | ||
| 76 | + home = os.environ.get('ASCEND_HOME_PATH', '') | ||
| 77 | + opp = str(Path(home) / 'opp') if home else '' | ||
| 78 | + if opp: | ||
| 79 | + cand = Path(opp) / 'vendors' / _VENDOR_NAME | ||
| 80 | + if _is_vendor(cand): | ||
| 81 | + return cand | ||
| 82 | + return None | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +def _ensure_vendor_env(): | ||
| 86 | + """Resolve the vendor and prepend it to ASCEND_CUSTOM_OPP_PATH. | ||
| 87 | + | ||
| 88 | + Runs at import time, before any binding load: gym_aclnn.h caches its | ||
| 89 | + dlopen handles once (Libraries() static singleton). Prepending makes the | ||
| 90 | + resolved vendor win over stale entries (bundled-first, decision 4/30). | ||
| 91 | + """ | ||
| 92 | + global _resolved_vendor | ||
| 93 | + vendor = _discover_vendor() | ||
| 94 | + _resolved_vendor = vendor | ||
| 95 | + if vendor is None: | ||
| 96 | + return | ||
| 97 | + path = str(vendor) | ||
| 98 | + entries = [p for p in os.environ.get('ASCEND_CUSTOM_OPP_PATH', '').split(':') if p] | ||
| 99 | + if entries and entries[0] == path: | ||
| 100 | + return | ||
| 101 | + if path in entries: | ||
| 102 | + entries.remove(path) | ||
| 103 | + entries.insert(0, path) | ||
| 104 | + os.environ['ASCEND_CUSTOM_OPP_PATH'] = ':'.join(entries) | ||
| 105 | + | ||
| 106 | + | ||
| 107 | +_ensure_vendor_env() | ||
| 108 | + | ||
| 109 | +# Allow the optional kernel wheel's pypto_gym.ops namespace to coexist. The | ||
| 110 | +# attribute is updated through globals() because assigning to a dunder name | ||
| 111 | +# directly is discouraged by the code checker; the effect is identical. | ||
| 112 | +globals()['__path__'] = pkgutil.extend_path(globals()['__path__'], __name__) | ||
| 113 | + | ||
| 114 | +try: | ||
| 115 | + __all__ = list(_binding_names()) | ||
| 116 | +except ImportError: | ||
| 117 | + # Bindings are not installed (for example an ACLNN-only artifact). | ||
| 118 | + __all__ = [] | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def vendor_path(): | ||
| 122 | + """Absolute path of the resolved custom-op vendor directory, or None. | ||
| 123 | + | ||
| 124 | + Pure C++ aclnn consumers can export ``ASCEND_CUSTOM_OPP_PATH`` to this | ||
| 125 | + path; importing this package already sets it for the current process. | ||
| 126 | + """ | ||
| 127 | + return str(_resolved_vendor) if _resolved_vendor is not None else None | ||
| 128 | + | ||
| 129 | + | ||
| 130 | +def load(op=None): | ||
| 131 | + """Load bindings (JIT compiling on first use) and return the op names. | ||
| 132 | + | ||
| 133 | + Accessing ``pypto_gym.<op>`` loads lazily; call this before using | ||
| 134 | + ``torch.ops.pypto_gym.<op>`` directly. | ||
| 135 | + """ | ||
| 136 | + from ._loader import binding_names, load_binding | ||
| 137 | + | ||
| 138 | + if op is None: | ||
| 139 | + names = list(binding_names()) | ||
| 140 | + for name in names: | ||
| 141 | + load_binding(name) | ||
| 142 | + return names | ||
| 143 | + if not isinstance(op, str): | ||
| 144 | + raise TypeError('operator name must be a string') | ||
| 145 | + load_binding(op) | ||
| 146 | + return [op] | ||
| 147 | + | ||
| 148 | + | ||
| 149 | +def prewarm(ops=None): | ||
| 150 | + """JIT compile bindings into the versioned cache without executing ops. | ||
| 151 | + | ||
| 152 | + For image builds / post-install warm-up so the production runtime stays | ||
| 153 | + compile-free. Imports torch. Returns the compiled op names. | ||
| 154 | + """ | ||
| 155 | + from ._loader import prewarm as _prewarm | ||
| 156 | + return _prewarm(ops) | ||
| 157 | + | ||
| 158 | + | ||
| 159 | +def _resolve_op(name): | ||
| 160 | + """Shared operator resolver behind get_ops() and attribute access. | ||
| 161 | + | ||
| 162 | + Currently resolves the torch-binding tier (operators.json manifest). | ||
| 163 | + Reserved for multi-tier resolution (torch.ops -> JIT source -> None); | ||
| 164 | + the public contract of get_ops() stays stable across that extension. | ||
| 165 | + Returns the callable entry, or None when unresolvable. | ||
| 166 | + """ | ||
| 167 | + from ._loader import binding_names, load_binding | ||
| 168 | + | ||
| 169 | + try: | ||
| 170 | + names = binding_names() | ||
| 171 | + except ImportError: | ||
| 172 | + return None | ||
| 173 | + if name not in names: | ||
| 174 | + return None | ||
| 175 | + return load_binding(name) | ||
| 176 | + | ||
| 177 | + | ||
| 178 | +def get_ops(op=None): | ||
| 179 | + """Resolve operator entries by name (tier-agnostic soft probe). | ||
| 180 | + | ||
| 181 | + ``op=None`` -> sorted list of currently resolvable operator names. | ||
| 182 | + ``op=<str>`` -> callable entry, or None when unresolvable (no exception; | ||
| 183 | + cross-check with ``get_ops()`` for typos). | ||
| 184 | + """ | ||
| 185 | + if op is None: | ||
| 186 | + from ._loader import binding_names | ||
| 187 | + | ||
| 188 | + try: | ||
| 189 | + return sorted(binding_names()) | ||
| 190 | + except ImportError: | ||
| 191 | + return [] | ||
| 192 | + if not isinstance(op, str): | ||
| 193 | + raise TypeError('operator name must be a string') | ||
| 194 | + return _resolve_op(op) | ||
| 195 | + | ||
| 196 | + | ||
| 197 | +def __getattr__(name): | ||
| 198 | + if name.startswith('_'): | ||
| 199 | + raise AttributeError(name) | ||
| 200 | + from ._loader import binding_names | ||
| 201 | + | ||
| 202 | + try: | ||
| 203 | + binding_names() | ||
| 204 | + except ImportError as error: | ||
| 205 | + raise AttributeError(str(error)) from error | ||
| 206 | + entry = _resolve_op(name) | ||
| 207 | + if entry is None: | ||
| 208 | + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") | ||
| 209 | + return entry | ||
| 210 | + | ||
| 211 | + | ||
| 212 | +def __dir__(): | ||
| 213 | + return sorted(set(globals()) | set(__all__)) | ||
| @@ -105,13 +105,10 @@ inline aclDataType DataType(at::ScalarType type) { | |||
| 105 | return ACL_INT64; | 105 | return ACL_INT64; |
| 106 | case at::kByte: | 106 | case at::kByte: |
| 107 | return ACL_UINT8; | 107 | return ACL_UINT8; |
| 108 | - case at::kFloat8_e4m3fn: | 108 | + case at::ScalarType::Float8_e4m3fn: |
| 109 | - // ACL_FLOAT8_E4M3FN (acl/acl_base_rt.h); the enum name is not exported by | 109 | + return ACL_FLOAT8_E4M3FN; |
| 110 | - // every CANN header set, so use the ABI value, matching the test bridges. | 110 | + case at::ScalarType::Float8_e8m0fnu: |
| 111 | - return static_cast<aclDataType>(36); | 111 | + return ACL_FLOAT8_E8M0; |
| 112 | - case at::kFloat8_e8m0fnu: | ||
| 113 | - // ACL_FLOAT8_E8M0, same reasoning as above. | ||
| 114 | - return static_cast<aclDataType>(37); | ||
| 115 | default: | 112 | default: |
| 116 | TORCH_CHECK(false, "Unsupported ACL tensor dtype: ", type); | 113 | TORCH_CHECK(false, "Unsupported ACL tensor dtype: ", type); |
| 117 | } | 114 | } |
| @@ -137,12 +134,26 @@ struct TensorInfo { | |||
| 137 | int64_t storage_elements; | 134 | int64_t storage_elements; |
| 138 | void *data; | 135 | void *data; |
| 139 | aclDataType type; | 136 | aclDataType type; |
| 137 | + aclFormat format; | ||
| 138 | + std::vector<int64_t> storage_sizes; | ||
| 140 | explicit TensorInfo(const at::Tensor &tensor) | 139 | explicit TensorInfo(const at::Tensor &tensor) |
| 141 | : sizes(tensor.sizes().vec()), strides(tensor.strides().vec()), | 140 | : sizes(tensor.sizes().vec()), strides(tensor.strides().vec()), |
| 142 | offset(tensor.storage_offset()), | 141 | offset(tensor.storage_offset()), |
| 143 | storage_elements(tensor.storage().nbytes() / tensor.element_size()), | 142 | storage_elements(tensor.storage().nbytes() / tensor.element_size()), |
| 144 | data(const_cast<void *>(tensor.storage().data())), | 143 | data(const_cast<void *>(tensor.storage().data())), |
| 145 | - type(DataType(tensor.scalar_type())) {} | 144 | + type(DataType(tensor.scalar_type())), |
| 145 | + format(static_cast<aclFormat>(at_npu::native::get_npu_format(tensor))) { | ||
| 146 | + // Preserve the historical ND descriptor exactly; internal formats such as | ||
| 147 | + // FRACTAL_NZ need torch_npu's physical storage shape to describe the | ||
| 148 | + // reordered elements. | ||
| 149 | + if (format == ACL_FORMAT_ND) { | ||
| 150 | + storage_sizes.push_back(storage_elements); | ||
| 151 | + } else { | ||
| 152 | + storage_sizes = at_npu::native::get_npu_storage_sizes(tensor); | ||
| 153 | + if (storage_sizes.empty()) | ||
| 154 | + storage_sizes.push_back(storage_elements); | ||
| 155 | + } | ||
| 156 | + } | ||
| 146 | }; | 157 | }; |
| 147 | 158 | ||
| 148 | inline TensorHandle Tensor(const TensorInfo &tensor) { | 159 | inline TensorHandle Tensor(const TensorInfo &tensor) { |
| @@ -153,8 +164,9 @@ inline TensorHandle Tensor(const TensorInfo &tensor) { | |||
| 153 | static const auto destroy = | 164 | static const auto destroy = |
| 154 | Symbol<DestroyTensor::Function>("aclDestroyTensor"); | 165 | Symbol<DestroyTensor::Function>("aclDestroyTensor"); |
| 155 | auto *result = create(tensor.sizes.data(), tensor.sizes.size(), tensor.type, | 166 | auto *result = create(tensor.sizes.data(), tensor.sizes.size(), tensor.type, |
| 156 | - tensor.strides.data(), tensor.offset, ACL_FORMAT_ND, | 167 | + tensor.strides.data(), tensor.offset, tensor.format, |
| 157 | - &tensor.storage_elements, 1, tensor.data); | 168 | + tensor.storage_sizes.data(), tensor.storage_sizes.size(), |
| 169 | + tensor.data); | ||
| 158 | TORCH_CHECK(result, "aclCreateTensor failed"); | 170 | TORCH_CHECK(result, "aclCreateTensor failed"); |
| 159 | return TensorHandle(result, DestroyTensor{destroy}); | 171 | return TensorHandle(result, DestroyTensor{destroy}); |
| 160 | } | 172 | } |
| @@ -6,11 +6,19 @@ | |||
| 6 | # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | 6 | # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. |
| 7 | # See LICENSE in the root of the software repository for the full text of the License. | 7 | # See LICENSE in the root of the software repository for the full text of the License. |
| 8 | # ----------------------------------------------------------------------------------------------------------- | 8 | # ----------------------------------------------------------------------------------------------------------- |
| 9 | -"""Load shipped libraries on demand; no runtime compilation or kernel-source imports.""" | 9 | +"""Load operator bindings on demand: JIT compile on first use, then dlopen. |
| 10 | + | ||
| 11 | +The binding sources ship in ``_bindings/csrc/``; ``.jit.ensure_compiled`` | ||
| 12 | +compiles them into a versioned cache (no rpath/RUNPATH involved) and the | ||
| 13 | +artifact is loaded through ``torch.ops.load_library``. No kernel-source | ||
| 14 | +imports, no device work. | ||
| 15 | +""" | ||
| 10 | import importlib | 16 | import importlib |
| 11 | import json | 17 | import json |
| 12 | from pathlib import Path | 18 | from pathlib import Path |
| 13 | 19 | ||
| 20 | +from .jit import cache_dir, ensure_compiled, prewarm # noqa: F401 (re-exported) | ||
| 21 | + | ||
| 14 | _loaded = {} | 22 | _loaded = {} |
| 15 | _names = None | 23 | _names = None |
| 16 | 24 | ||
| @@ -19,11 +27,11 @@ def binding_names(): | |||
| 19 | """Return the installed operator names without importing torch.""" | 27 | """Return the installed operator names without importing torch.""" |
| 20 | global _names | 28 | global _names |
| 21 | if _names is None: | 29 | if _names is None: |
| 22 | - package = Path(__file__).resolve().parent | 30 | + package = Path(__file__).resolve().parent.parent |
| 23 | - manifest = package / 'operators.json' | 31 | + manifest = package / '_bindings' / 'operators.json' |
| 24 | if not manifest.is_file(): | 32 | if not manifest.is_file(): |
| 25 | - raise ImportError('Torch bindings are not installed; build the .run with --torch-bindings ' | 33 | + raise ImportError('Torch bindings are not installed; build the artifact without ' |
| 26 | - 'and install it into the active CANN environment') | 34 | + '--no-torch-bindings and install it into the active CANN environment') |
| 27 | try: | 35 | try: |
| 28 | names = json.loads(manifest.read_text(encoding='utf-8')) | 36 | names = json.loads(manifest.read_text(encoding='utf-8')) |
| 29 | except (OSError, ValueError) as error: | 37 | except (OSError, ValueError) as error: |
| @@ -38,7 +46,7 @@ def binding_names(): | |||
| 38 | 46 | ||
| 39 | 47 | ||
| 40 | def load_binding(name): | 48 | def load_binding(name): |
| 41 | - """Import torch/torch_npu and load one operator extension on first use.""" | 49 | + """Import torch/torch_npu, JIT compile on first use, load one operator.""" |
| 42 | if name in _loaded: | 50 | if name in _loaded: |
| 43 | return _loaded[name] | 51 | return _loaded[name] |
| 44 | if name not in binding_names(): | 52 | if name not in binding_names(): |
| @@ -46,14 +54,12 @@ def load_binding(name): | |||
| 46 | import torch | 54 | import torch |
| 47 | import torch_npu # Register PrivateUse1 and load libtorch_npu before extensions. | 55 | import torch_npu # Register PrivateUse1 and load libtorch_npu before extensions. |
| 48 | 56 | ||
| 49 | - package = Path(__file__).resolve().parent | 57 | + library = ensure_compiled(name) |
| 50 | - library = package / '_native' / f'libpypto_gym_{name}.so' | ||
| 51 | try: | 58 | try: |
| 52 | torch.ops.load_library(str(library)) | 59 | torch.ops.load_library(str(library)) |
| 53 | except OSError as error: | 60 | except OSError as error: |
| 54 | - raise ImportError(f'Cannot load {library}; use the torch/torch_npu ABI ' | 61 | + raise ImportError(f'Cannot load {library}: {error}') from error |
| 55 | - f'used to build this .run: {error}') from error | 62 | + module = importlib.import_module(f'.._bindings.frontends.{name}', __package__) |
| 56 | - module = importlib.import_module(f'._frontends.{name}', __package__) | ||
| 57 | entry = getattr(module, name) | 63 | entry = getattr(module, name) |
| 58 | _loaded[name] = entry | 64 | _loaded[name] = entry |
| 59 | return entry | 65 | return entry |
| @@ -0,0 +1,290 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | +"""JIT compiler implementation: versioned cache + flock + cpp_extension.load. | ||
| 10 | + | ||
| 11 | +Cache key dimensions (structural correctness, pypto _compute_cache_dir style): | ||
| 12 | + gym_ver distribution version; source trees without dist-info fall back | ||
| 13 | + to a sha1 of the _bindings/csrc payload so edits invalidate the cache | ||
| 14 | + build_ts X-Build-Timestamp from the wheel METADATA (build identity): | ||
| 15 | + same-version rebuilds get a fresh key, so a stale cache can | ||
| 16 | + never shadow changed binding sources; omitted for source trees | ||
| 17 | + (their dev-<sha1> gym_ver is content-addressed already) | ||
| 18 | + torch_ver torch.__version__ (local part kept: +cpu vs +npu differ) | ||
| 19 | + tonpu_ver torch_npu.__version__ | ||
| 20 | + ascend_hash md5 of the CANN install path, ascend_<hash> (acl/aclnn headers | ||
| 21 | + affect the compile; same name/resolution as pypto); omitted | ||
| 22 | + when unknown | ||
| 23 | + arch platform.machine() | ||
| 24 | +No Python dimension: form-B artifacts carry zero Python symbols (verified), | ||
| 25 | +one .so serves every supported interpreter version. | ||
| 26 | +""" | ||
| 27 | + | ||
| 28 | +import fcntl | ||
| 29 | +import hashlib | ||
| 30 | +import logging | ||
| 31 | +import os | ||
| 32 | +from pathlib import Path | ||
| 33 | +import platform | ||
| 34 | +import re | ||
| 35 | +import shutil | ||
| 36 | +import sys | ||
| 37 | +import sysconfig | ||
| 38 | +import time | ||
| 39 | + | ||
| 40 | +_log = logging.getLogger(__name__) | ||
| 41 | + | ||
| 42 | +_LOCK_TIMEOUT = 1800.0 # seconds to wait for a concurrent compiler | ||
| 43 | +_POLL_INTERVAL = 1.0 | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def _sanitize(text: str) -> str: | ||
| 47 | + return re.sub(r"[^A-Za-z0-9._-]", "_", str(text)) | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def _csrc_dir() -> Path: | ||
| 51 | + return Path(__file__).resolve().parent.parent / "_bindings" / "csrc" | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +def _gym_version() -> str: | ||
| 55 | + from importlib import metadata | ||
| 56 | + try: | ||
| 57 | + return metadata.version("pypto-gym") | ||
| 58 | + except Exception: | ||
| 59 | + # Source/editable tree without dist-info: fingerprint the JIT inputs so | ||
| 60 | + # source edits invalidate the cache (replaces the missing version key). | ||
| 61 | + digest = hashlib.sha1() | ||
| 62 | + csrc = _csrc_dir() | ||
| 63 | + if csrc.is_dir(): | ||
| 64 | + for path in sorted(csrc.rglob("*")): | ||
| 65 | + if path.is_file(): | ||
| 66 | + digest.update(str(path.relative_to(csrc)).encode()) | ||
| 67 | + digest.update(path.read_bytes()) | ||
| 68 | + return "dev-" + digest.hexdigest()[:12] | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def _build_timestamp() -> str: | ||
| 72 | + """Build-identity segment from the wheel METADATA (X-Build-Timestamp). | ||
| 73 | + | ||
| 74 | + Written by setup.py's CustomEggInfo at build time (pypto-style); build_ci | ||
| 75 | + injects one timestamp per build round shared by the full and shell wheels. | ||
| 76 | + Empty for source trees (no dist-info); 'nots' with a warning when an | ||
| 77 | + installed artifact predates the field. | ||
| 78 | + """ | ||
| 79 | + from importlib import metadata | ||
| 80 | + try: | ||
| 81 | + meta = metadata.metadata("pypto-gym") | ||
| 82 | + except Exception: | ||
| 83 | + return "" | ||
| 84 | + ts = (meta["X-Build-Timestamp"] or "").strip() if meta is not None else "" | ||
| 85 | + if not ts: | ||
| 86 | + _log.warning("pypto-gym METADATA has no X-Build-Timestamp; using the 'nots' cache segment") | ||
| 87 | + return "nots" | ||
| 88 | + return ts | ||
| 89 | + | ||
| 90 | + | ||
| 91 | +def _resolve_cann_path() -> str: | ||
| 92 | + """CANN install path resolution, pypto _get_ascend_path parity: | ||
| 93 | + CANN_PATH > ASCEND_HOME_PATH > dirname(ASCEND_OPP_PATH).""" | ||
| 94 | + for env_key in ("CANN_PATH", "ASCEND_HOME_PATH"): | ||
| 95 | + val = os.environ.get(env_key, "") | ||
| 96 | + if val: | ||
| 97 | + return val | ||
| 98 | + opp = os.environ.get("ASCEND_OPP_PATH", "") | ||
| 99 | + return str(Path(opp).parent) if opp else "" | ||
| 100 | + | ||
| 101 | + | ||
| 102 | +def _cann_hash() -> str: | ||
| 103 | + """CANN install identity segment (same name and resolution order as pypto's | ||
| 104 | + ascend_<hash>). The CANN headers/libs are compile inputs; switching or | ||
| 105 | + upgrading CANN must not reuse bindings compiled against another install. | ||
| 106 | + """ | ||
| 107 | + cann = _resolve_cann_path() | ||
| 108 | + if not cann: | ||
| 109 | + return "" | ||
| 110 | + return "ascend_" + hashlib.md5(cann.encode()).hexdigest()[:8] | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +def cache_dir() -> Path: | ||
| 114 | + """Versioned cache directory (created on demand by ensure_compiled).""" | ||
| 115 | + import torch | ||
| 116 | + import torch_npu | ||
| 117 | + xdg = os.environ.get("XDG_CACHE_HOME", "") | ||
| 118 | + root = Path(xdg) if xdg and Path(xdg).is_absolute() else Path.home() / ".cache" | ||
| 119 | + path = root / "cann" / "pypto_gym" | ||
| 120 | + for segment in ( | ||
| 121 | + _sanitize(_gym_version()), | ||
| 122 | + _sanitize(_build_timestamp()), | ||
| 123 | + _sanitize(str(torch.__version__)), | ||
| 124 | + _sanitize(str(getattr(torch_npu, "__version__", "0"))), | ||
| 125 | + _cann_hash(), | ||
| 126 | + platform.machine(), | ||
| 127 | + ): | ||
| 128 | + if segment: | ||
| 129 | + path = path / segment | ||
| 130 | + return path | ||
| 131 | + | ||
| 132 | + | ||
| 133 | +def _cann_path() -> Path: | ||
| 134 | + cann = _resolve_cann_path() | ||
| 135 | + if not cann or not (Path(cann) / "lib64" / "libascendcl.so").is_file(): | ||
| 136 | + raise ImportError( | ||
| 137 | + "CANN not found for JIT binding compilation: set ASCEND_HOME_PATH " | ||
| 138 | + "(or CANN_PATH / ASCEND_OPP_PATH) to a CANN installation providing " | ||
| 139 | + "lib64/libascendcl.so") | ||
| 140 | + return Path(cann) | ||
| 141 | + | ||
| 142 | + | ||
| 143 | +def _ensure_ninja_on_path() -> None: | ||
| 144 | + """Make the pip-installed ninja visible when its scripts dir is off PATH.""" | ||
| 145 | + if shutil.which("ninja"): | ||
| 146 | + return | ||
| 147 | + candidates = [str(Path(sys.executable).parent)] | ||
| 148 | + scripts = sysconfig.get_path("scripts") | ||
| 149 | + if scripts: | ||
| 150 | + candidates.append(scripts) | ||
| 151 | + try: | ||
| 152 | + import ninja | ||
| 153 | + bin_dir = getattr(ninja, "BIN_DIR", "") | ||
| 154 | + if bin_dir: | ||
| 155 | + candidates.append(str(bin_dir)) | ||
| 156 | + module_file = getattr(ninja, "__file__", "") | ||
| 157 | + if module_file: | ||
| 158 | + for parent in Path(module_file).resolve().parent.parents: | ||
| 159 | + candidates.append( | ||
| 160 | + str(parent / ("Scripts" if os.name == "nt" else "bin"))) | ||
| 161 | + except ImportError: | ||
| 162 | + pass | ||
| 163 | + for prefix in (sys.prefix, sys.base_prefix): | ||
| 164 | + candidates.append( | ||
| 165 | + str(Path(prefix) / ("Scripts" if os.name == "nt" else "bin"))) | ||
| 166 | + seen = set() | ||
| 167 | + for candidate in candidates: | ||
| 168 | + if not candidate or candidate in seen: | ||
| 169 | + continue | ||
| 170 | + seen.add(candidate) | ||
| 171 | + if shutil.which("ninja", path=candidate): | ||
| 172 | + current = os.environ.get("PATH", "") | ||
| 173 | + os.environ["PATH"] = candidate + (os.pathsep + current if current else "") | ||
| 174 | + return | ||
| 175 | + raise RuntimeError( | ||
| 176 | + "ninja executable not found; install it with 'pip install ninja' " | ||
| 177 | + "or add the Python environment's scripts directory to PATH") | ||
| 178 | + | ||
| 179 | + | ||
| 180 | +def _try_lock(fd) -> bool: | ||
| 181 | + try: | ||
| 182 | + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) | ||
| 183 | + return True | ||
| 184 | + except BlockingIOError: | ||
| 185 | + return False | ||
| 186 | + | ||
| 187 | + | ||
| 188 | +def _poll_lock(fd, timeout: float) -> bool: | ||
| 189 | + deadline = time.monotonic() + timeout | ||
| 190 | + while time.monotonic() < deadline: | ||
| 191 | + if _try_lock(fd): | ||
| 192 | + return True | ||
| 193 | + time.sleep(_POLL_INTERVAL) | ||
| 194 | + return False | ||
| 195 | + | ||
| 196 | + | ||
| 197 | +def ensure_compiled(op_name: str) -> Path: | ||
| 198 | + """Return the compiled binding .so for op_name, compiling on first use.""" | ||
| 199 | + build_dir = cache_dir() | ||
| 200 | + so_path = build_dir / f"pypto_gym_{op_name}.so" | ||
| 201 | + if so_path.is_file(): | ||
| 202 | + return so_path | ||
| 203 | + build_dir.mkdir(parents=True, exist_ok=True) | ||
| 204 | + lock_path = build_dir / f".{op_name}.compile.lock" | ||
| 205 | + lock_fd = open(lock_path, "w") | ||
| 206 | + acquired = False | ||
| 207 | + try: | ||
| 208 | + acquired = _try_lock(lock_fd) or _poll_lock(lock_fd, _LOCK_TIMEOUT) | ||
| 209 | + if not acquired: | ||
| 210 | + _log.warning("timeout waiting for the compilation lock; compiling independently") | ||
| 211 | + if so_path.is_file(): # a peer finished while we waited | ||
| 212 | + return so_path | ||
| 213 | + _compile(op_name, build_dir) | ||
| 214 | + if not so_path.is_file(): | ||
| 215 | + raise RuntimeError( | ||
| 216 | + f"JIT compilation reported success but produced no {so_path}") | ||
| 217 | + return so_path | ||
| 218 | + finally: | ||
| 219 | + if acquired: | ||
| 220 | + # unlink while still holding: after unlock+unlink a peer could lock | ||
| 221 | + # the old inode while a newcomer locks a fresh one (pypto pattern). | ||
| 222 | + try: | ||
| 223 | + lock_path.unlink(missing_ok=True) | ||
| 224 | + except OSError: | ||
| 225 | + pass | ||
| 226 | + try: | ||
| 227 | + fcntl.flock(lock_fd, fcntl.LOCK_UN) | ||
| 228 | + except OSError: | ||
| 229 | + pass | ||
| 230 | + lock_fd.close() | ||
| 231 | + | ||
| 232 | + | ||
| 233 | +def _compile(op_name: str, build_dir: Path) -> None: | ||
| 234 | + _ensure_ninja_on_path() | ||
| 235 | + import torch_npu # noqa: F401 (headers/libs for the binding; torch pulled in by cpp_extension) | ||
| 236 | + from torch.utils import cpp_extension | ||
| 237 | + | ||
| 238 | + csrc = _csrc_dir() | ||
| 239 | + source = csrc / f"{op_name}.cpp" | ||
| 240 | + if not source.is_file(): | ||
| 241 | + raise ImportError( | ||
| 242 | + f"binding source not found: {source}; install a pypto-gym artifact " | ||
| 243 | + f"that ships _bindings/csrc (wheel or run-registered shell)") | ||
| 244 | + cann = _cann_path() | ||
| 245 | + tonpu = Path(torch_npu.__file__).parent | ||
| 246 | + verbose = os.environ.get("GYM_JIT_VERBOSE", "") == "1" | ||
| 247 | + _log.info("JIT compiling pypto_gym_%s into %s", op_name, build_dir) | ||
| 248 | + try: | ||
| 249 | + cpp_extension.load( | ||
| 250 | + name=f"pypto_gym_{op_name}", | ||
| 251 | + sources=[str(source)], | ||
| 252 | + extra_include_paths=[ | ||
| 253 | + str(csrc), | ||
| 254 | + str(tonpu / "include"), | ||
| 255 | + str(cann / "include"), | ||
| 256 | + str(cann / "include" / "aclnnop"), | ||
| 257 | + ], | ||
| 258 | + extra_ldflags=[ | ||
| 259 | + f"-L{cann / 'lib64'}", "-lascendcl", | ||
| 260 | + f"-L{tonpu / 'lib'}", "-ltorch_npu", | ||
| 261 | + ], | ||
| 262 | + build_directory=str(build_dir), | ||
| 263 | + is_python_module=False, | ||
| 264 | + verbose=verbose, | ||
| 265 | + ) | ||
| 266 | + except Exception as error: | ||
| 267 | + raise RuntimeError( | ||
| 268 | + f"JIT compilation of pypto_gym_{op_name} failed: {error}\n" | ||
| 269 | + f"Requirements: g++ (GCC 9.4.0+), ninja on PATH (pip install ninja, or apt install ninja-build), torch/torch_npu " | ||
| 270 | + f"headers (from the installed pip packages), CANN headers/libs " | ||
| 271 | + f"(ASCEND_HOME_PATH). Set GYM_JIT_VERBOSE=1 for the full compile log." | ||
| 272 | + ) from error | ||
| 273 | + | ||
| 274 | + | ||
| 275 | +def prewarm(ops=None): | ||
| 276 | + """Compile bindings into the versioned cache without executing any op. | ||
| 277 | + | ||
| 278 | + Intended for image builds / post-install warm-up so the production runtime | ||
| 279 | + stays compile-free. Imports torch. Returns the compiled op names. | ||
| 280 | + """ | ||
| 281 | + if ops is None: | ||
| 282 | + from . import binding_names | ||
| 283 | + names = list(binding_names()) | ||
| 284 | + elif isinstance(ops, str): | ||
| 285 | + names = [ops] | ||
| 286 | + else: | ||
| 287 | + names = list(ops) | ||
| 288 | + for name in names: | ||
| 289 | + ensure_compiled(name) | ||
| 290 | + return names | ||
| @@ -1,9 +1,13 @@ | |||
| 1 | # Runtime dependencies for pypto-gym | 1 | # Runtime dependencies for pypto-gym |
| 2 | # 注:torch / torch_npu 需要用户按照昇腾环境手册单独安装,不从 PyPI 自动拉取。 | 2 | # 注:torch / torch_npu 需要用户按照昇腾环境手册单独安装,不从 PyPI 自动拉取。 |
| 3 | 3 | ||
| 4 | -pypto>=0.2.0 | 4 | +# [project] dependencies |
| 5 | -numpy | 5 | +pypto>=0.3.0 |
| 6 | +ninja>=1.11 | ||
| 7 | + | ||
| 8 | +# [project.optional-dependencies] tests | ||
| 6 | PyYAML>=6.0 | 9 | PyYAML>=6.0 |
| 7 | pytest>=7 | 10 | pytest>=7 |
| 8 | -pytest-forked==1.6.0 | 11 | +pytest-forked |
| 9 | pytest-xdist | 12 | pytest-xdist |
| 13 | +numpy | ||
| @@ -23,7 +23,7 @@ readonly TMP_PKG_VERSION_FILE="${TMP_PKG_INFO_PATH}/version.info" | |||
| 23 | unset tmp_cfd | 23 | unset tmp_cfd |
| 24 | 24 | ||
| 25 | readonly VENDOR_NAME="pypto_gym" | 25 | readonly VENDOR_NAME="pypto_gym" |
| 26 | -source "${TMP_PKG_SCRIPTS_PATH}/python_registration.sh" | 26 | +source "${TMP_PKG_SCRIPTS_PATH}/python_wheel.sh" |
| 27 | 27 | ||
| 28 | ######################################################################################################################## | 28 | ######################################################################################################################## |
| 29 | # 日志 | 29 | # 日志 |
| @@ -169,28 +169,13 @@ do_install() { | |||
| 169 | [ -d "${TMP_PKG_ROOT_PATH}/packages/vendors/${VENDOR_NAME}" ] \ | 169 | [ -d "${TMP_PKG_ROOT_PATH}/packages/vendors/${VENDOR_NAME}" ] \ |
| 170 | || exit_log 1 "vendor payload missing in package: ${TMP_PKG_ROOT_PATH}/packages/vendors/${VENDOR_NAME}" | 170 | || exit_log 1 "vendor payload missing in package: ${TMP_PKG_ROOT_PATH}/packages/vendors/${VENDOR_NAME}" |
| 171 | 171 | ||
| 172 | - local has_bindings=n register_python=n check_rc=0 | 172 | + local has_bindings=n |
| 173 | - if [ -f "${TMP_PKG_ROOT_PATH}/packages/vendors/${VENDOR_NAME}/python/pypto_gym/operators.json" ]; then | 173 | + if [ -f "${TMP_PKG_ROOT_PATH}/packages/vendors/${VENDOR_NAME}/python/pypto_gym/_bindings/operators.json" ]; then |
| 174 | has_bindings=y | 174 | has_bindings=y |
| 175 | - gym_python_check_links "${targetdir}" | ||
| 176 | - check_rc=$? | ||
| 177 | - case "${check_rc}" in | ||
| 178 | - 0) register_python=y ;; | ||
| 179 | - 2) gym_python_warn_degraded "${targetdir}" "CANN site-packages is not writable" ;; | ||
| 180 | - *) exit_log 1 "cannot register Python bindings" ;; | ||
| 181 | - esac | ||
| 182 | - fi | ||
| 183 | - | ||
| 184 | - # Always drop links left by a previous version; only a writable standard | ||
| 185 | - # CANN layout can recreate them. | ||
| 186 | - if ! gym_python_remove_links "${targetdir}"; then | ||
| 187 | - if [ "${has_bindings}" = y ]; then | ||
| 188 | - gym_python_warn_degraded "${targetdir}" "cannot remove stale Python binding links" | ||
| 189 | - register_python=n | ||
| 190 | - else | ||
| 191 | - exit_log 1 "cannot remove old Python binding registration" | ||
| 192 | - fi | ||
| 193 | fi | 175 | fi |
| 176 | + # Legacy symlink trees (pre-wheel versions) and stale pip registrations are | ||
| 177 | + # handled inside gym_install_shell_wheel / gym_remove_shell_wheel. | ||
| 178 | + gym_remove_shell_wheel "${targetdir}" | ||
| 194 | 179 | ||
| 195 | if [ -d "${targetdir}/${vendordir}" ]; then | 180 | if [ -d "${targetdir}/${vendordir}" ]; then |
| 196 | log "[INFO] ${targetdir}/${vendordir} already exists, old version will be replaced" | 181 | log "[INFO] ${targetdir}/${vendordir} already exists, old version will be replaced" |
| @@ -213,28 +198,24 @@ do_install() { | |||
| 213 | cp -f "${TMP_PKG_VERSION_FILE}" "${targetdir}/${vendordir}/version.info" 2>/dev/null | 198 | cp -f "${TMP_PKG_VERSION_FILE}" "${targetdir}/${vendordir}/version.info" 2>/dev/null |
| 214 | fi | 199 | fi |
| 215 | 200 | ||
| 216 | - # set_env.bash: 导出 ASCEND_CUSTOM_OPP_PATH + LD_LIBRARY_PATH | 201 | + # set_env.bash: 导出 ASCEND_CUSTOM_OPP_PATH + LD_LIBRARY_PATH(纯 C++ aclnn 消费方)。 |
| 202 | + # Python 层由壳 wheel 经 pip 注册(决策 29),不再注入 PYTHONPATH。 | ||
| 217 | mkdir -p "${targetdir}/${vendordir}/bin" | 203 | mkdir -p "${targetdir}/${vendordir}/bin" |
| 218 | cat > "${targetdir}/${vendordir}/bin/set_env.bash" <<EOF | 204 | cat > "${targetdir}/${vendordir}/bin/set_env.bash" <<EOF |
| 219 | #!/bin/bash | 205 | #!/bin/bash |
| 220 | export ASCEND_CUSTOM_OPP_PATH=${targetdir}/${vendordir}:\${ASCEND_CUSTOM_OPP_PATH} | 206 | export ASCEND_CUSTOM_OPP_PATH=${targetdir}/${vendordir}:\${ASCEND_CUSTOM_OPP_PATH} |
| 221 | export LD_LIBRARY_PATH=${targetdir}/${vendordir}/op_api/lib/:\${LD_LIBRARY_PATH} | 207 | export LD_LIBRARY_PATH=${targetdir}/${vendordir}/op_api/lib/:\${LD_LIBRARY_PATH} |
| 222 | -if [ -d "${targetdir}/${vendordir}/python" ]; then | ||
| 223 | - export PYTHONPATH=${targetdir}/${vendordir}/python:\${PYTHONPATH} | ||
| 224 | -fi | ||
| 225 | EOF | 208 | EOF |
| 226 | chmod 550 "${targetdir}/${vendordir}/bin/set_env.bash" | 209 | chmod 550 "${targetdir}/${vendordir}/bin/set_env.bash" |
| 227 | 210 | ||
| 228 | - if [ "${register_python}" = y ]; then | 211 | + local registered_dir="" |
| 229 | - gym_python_install_links "${targetdir}" || { | 212 | + if [ "${has_bindings}" = y ]; then |
| 230 | - gym_python_warn_degraded "${targetdir}" "cannot create Python binding links" | 213 | + registered_dir=$(gym_install_shell_wheel "${targetdir}") |
| 231 | - register_python=n | ||
| 232 | - } | ||
| 233 | fi | 214 | fi |
| 234 | 215 | ||
| 235 | # 独立卸载入口和共享登记逻辑一起交付。 | 216 | # 独立卸载入口和共享登记逻辑一起交付。 |
| 236 | mkdir -p "${targetdir}/${vendordir}/scripts" | 217 | mkdir -p "${targetdir}/${vendordir}/scripts" |
| 237 | - for script_name in uninstall.sh python_registration.sh; do | 218 | + for script_name in uninstall.sh python_wheel.sh; do |
| 238 | cp -f "${TMP_PKG_SCRIPTS_PATH}/${script_name}" "${targetdir}/${vendordir}/scripts/${script_name}" \ | 219 | cp -f "${TMP_PKG_SCRIPTS_PATH}/${script_name}" "${targetdir}/${vendordir}/scripts/${script_name}" \ |
| 239 | || exit_log 1 "cannot install ${script_name}" | 220 | || exit_log 1 "cannot install ${script_name}" |
| 240 | chmod 550 "${targetdir}/${vendordir}/scripts/${script_name}" | 221 | chmod 550 "${targetdir}/${vendordir}/scripts/${script_name}" |
| @@ -250,19 +231,18 @@ EOF | |||
| 250 | 231 | ||
| 251 | log "[INFO] install success. vendor: ${VENDOR_NAME} -> ${targetdir}/${vendordir}" | 232 | log "[INFO] install success. vendor: ${VENDOR_NAME} -> ${targetdir}/${vendordir}" |
| 252 | log "[INFO] verify: grep load_priority ${config_file}" | 233 | log "[INFO] verify: grep load_priority ${config_file}" |
| 253 | - public_python_dir=$(gym_python_public_dir "${targetdir}") | 234 | + if [ -n "${registered_dir}" ] && [ -f "${registered_dir}/_bindings/operators.json" ]; then |
| 254 | - if [ -n "${public_python_dir}" ] && [ -f "${public_python_dir}/operators.json" ]; then | 235 | + log "[INFO] Python bindings registered (pip): ${registered_dir}" |
| 255 | - log "[INFO] Python bindings registered: ${public_python_dir}; no vendor source required with CANN environment loaded" | ||
| 256 | elif [ "${has_bindings}" = y ]; then | 236 | elif [ "${has_bindings}" = y ]; then |
| 257 | - log "[WARN] Python bindings not registered; source ${targetdir}/${vendordir}/bin/set_env.bash to use pypto_gym" | 237 | + log "[WARN] Python bindings not registered; pip install ${targetdir}/${vendordir}/python/pypto_gym-*.whl manually" |
| 258 | else | 238 | else |
| 259 | - log "[INFO] custom-location environment: source ${targetdir}/${vendordir}/bin/set_env.bash" | 239 | + log "[INFO] ACLNN-only package: source ${targetdir}/${vendordir}/bin/set_env.bash for C++ consumers" |
| 260 | fi | 240 | fi |
| 261 | log "[INFO] uninstall: bash ${targetdir}/${vendordir}/scripts/uninstall.sh" | 241 | log "[INFO] uninstall: bash ${targetdir}/${vendordir}/scripts/uninstall.sh" |
| 262 | } | 242 | } |
| 263 | 243 | ||
| 264 | do_uninstall() { | 244 | do_uninstall() { |
| 265 | - gym_python_remove_links "${targetdir}" || exit_log 1 "cannot remove Python binding registration" | 245 | + gym_remove_shell_wheel "${targetdir}" || exit_log 1 "cannot remove Python binding registration" |
| 266 | if [ ! -d "${targetdir}/${vendordir}" ]; then | 246 | if [ ! -d "${targetdir}/${vendordir}" ]; then |
| 267 | log "[INFO] ${targetdir}/${vendordir} not exist, no need to uninstall" | 247 | log "[INFO] ${targetdir}/${vendordir} not exist, no need to uninstall" |
| 268 | remove_load_priority | 248 | remove_load_priority |
| @@ -1,101 +0,0 @@ | |||
| 1 | -#!/bin/bash | ||
| 2 | -# ----------------------------------------------------------------------------------------------------------- | ||
| 3 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | -# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | -# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | -# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | -# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | - | ||
| 12 | -# Keep the payload vendor-local and expose only its binding entries through the | ||
| 13 | -# Python path already set by CANN. Never replace an existing wheel's ops tree. | ||
| 14 | -gym_python_public_dir() { | ||
| 15 | - local opp_root cann_root | ||
| 16 | - opp_root=$(readlink -f "$1") || return 1 | ||
| 17 | - cann_root=$(dirname "${opp_root}") | ||
| 18 | - if [ "${opp_root}" = "${cann_root}/opp" ] && | ||
| 19 | - [ -f "${cann_root}/set_env.sh" ] && | ||
| 20 | - [ -d "${cann_root}/python/site-packages" ]; then | ||
| 21 | - printf '%s\n' "${cann_root}/python/site-packages/pypto_gym" | ||
| 22 | - fi | ||
| 23 | -} | ||
| 24 | - | ||
| 25 | -gym_python_link_owned() { | ||
| 26 | - [ -L "$1" ] && [ "$(readlink -m "$1")" = "$(readlink -m "$2")" ] | ||
| 27 | -} | ||
| 28 | - | ||
| 29 | -# Return codes: | ||
| 30 | -# 0 - registration is possible, or the install is not a standard CANN layout | ||
| 31 | -# 1 - an existing entry belongs to another package (fatal: never overwrite) | ||
| 32 | -# 2 - the CANN site-packages is not writable (degradable: install vendor only) | ||
| 33 | -gym_python_check_links() { | ||
| 34 | - local public_dir vendor_python entry path | ||
| 35 | - public_dir=$(gym_python_public_dir "$1") || return 1 | ||
| 36 | - [ -n "${public_dir}" ] || return 0 | ||
| 37 | - vendor_python="$1/vendors/pypto_gym/python/pypto_gym" | ||
| 38 | - if [ -L "${public_dir}" ] || { [ -e "${public_dir}" ] && [ ! -d "${public_dir}" ]; }; then | ||
| 39 | - printf 'Python binding path is already occupied: %s\n' "${public_dir}" >&2 | ||
| 40 | - return 1 | ||
| 41 | - fi | ||
| 42 | - # Ownership is checked before writability: another package must never be | ||
| 43 | - # overwritten even when the current user could technically write the entry. | ||
| 44 | - for entry in __init__.py _loader.py _native _frontends operators.json; do | ||
| 45 | - path="${public_dir}/${entry}" | ||
| 46 | - if { [ -e "${path}" ] || [ -L "${path}" ]; } && | ||
| 47 | - ! gym_python_link_owned "${path}" "${vendor_python}/${entry}"; then | ||
| 48 | - printf 'Python binding entry is already owned by another package: %s\n' "${path}" >&2 | ||
| 49 | - return 1 | ||
| 50 | - fi | ||
| 51 | - done | ||
| 52 | - if [ ! -w "$(dirname "${public_dir}")" ] || | ||
| 53 | - { [ -d "${public_dir}" ] && [ ! -w "${public_dir}" ]; }; then | ||
| 54 | - printf 'Python binding path is not writable: %s\n' "${public_dir}" >&2 | ||
| 55 | - return 2 | ||
| 56 | - fi | ||
| 57 | - return 0 | ||
| 58 | -} | ||
| 59 | - | ||
| 60 | -# Non-fatal registration failure: keep the vendor install usable through its own | ||
| 61 | -# set_env.bash instead of aborting the whole installation. | ||
| 62 | -gym_python_warn_degraded() { | ||
| 63 | - local targetdir="$1" reason="$2" | ||
| 64 | - printf 'warning: %s; Python bindings were not registered\n' "${reason}" >&2 | ||
| 65 | - printf 'warning: run "source %s/vendors/pypto_gym/bin/set_env.bash" to use pypto_gym in this shell\n' \ | ||
| 66 | - "${targetdir}" >&2 | ||
| 67 | -} | ||
| 68 | - | ||
| 69 | -gym_python_remove_links() { | ||
| 70 | - local public_dir vendor_python entry path removed_any=n | ||
| 71 | - public_dir=$(gym_python_public_dir "$1") || return 1 | ||
| 72 | - [ -n "${public_dir}" ] || return 0 | ||
| 73 | - vendor_python="$1/vendors/pypto_gym/python/pypto_gym" | ||
| 74 | - for entry in __init__.py _loader.py _native _frontends operators.json; do | ||
| 75 | - path="${public_dir}/${entry}" | ||
| 76 | - if gym_python_link_owned "${path}" "${vendor_python}/${entry}"; then | ||
| 77 | - rm -f "${path}" || return 1 | ||
| 78 | - removed_any=y | ||
| 79 | - case "${entry}" in | ||
| 80 | - __init__.py|_loader.py) | ||
| 81 | - rm -f "${public_dir}/__pycache__/${entry%.py}."*.pyc || return 1 | ||
| 82 | - ;; | ||
| 83 | - esac | ||
| 84 | - fi | ||
| 85 | - done | ||
| 86 | - [ "${removed_any}" = y ] || return 0 | ||
| 87 | - rmdir "${public_dir}/__pycache__" "${public_dir}" 2>/dev/null || true | ||
| 88 | -} | ||
| 89 | - | ||
| 90 | -gym_python_install_links() { | ||
| 91 | - local public_dir vendor_python entry link_target | ||
| 92 | - public_dir=$(gym_python_public_dir "$1") || return 1 | ||
| 93 | - [ -n "${public_dir}" ] || return 0 | ||
| 94 | - vendor_python="$1/vendors/pypto_gym/python/pypto_gym" | ||
| 95 | - [ -f "${vendor_python}/operators.json" ] || return 0 | ||
| 96 | - mkdir -p -m 755 "${public_dir}" || return 1 | ||
| 97 | - for entry in __init__.py _loader.py _native _frontends operators.json; do | ||
| 98 | - link_target=$(realpath --relative-to="${public_dir}" "${vendor_python}/${entry}") || return 1 | ||
| 99 | - ln -s "${link_target}" "${public_dir}/${entry}" || return 1 | ||
| 100 | - done | ||
| 101 | -} | ||
| @@ -0,0 +1,125 @@ | |||
| 1 | +#!/bin/bash | ||
| 2 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 11 | +# Python shell-wheel registration (decision 29/30). | ||
| 12 | +# | ||
| 13 | +# The run payload embeds a python shell wheel (pypto_gym-*.whl, py3-none-any: | ||
| 14 | +# entry package + _csrc binding sources, no vendor binaries). For a standard | ||
| 15 | +# CANN layout the installer pip-installs it into <cann_root>/python/site-packages | ||
| 16 | +# (the path CANN's own set_env.sh already puts on PYTHONPATH), mirroring the | ||
| 17 | +# pypto / ops-transformer convention. Failures degrade to a warning: the vendor | ||
| 18 | +# binaries stay usable through pure C++ aclnn, and the wheel remains inside the | ||
| 19 | +# vendor tree for a manual pip install. | ||
| 20 | + | ||
| 21 | +# Derive the public site-packages entry from the opp install root: only the | ||
| 22 | +# standard CANN layout qualifies (<cann_root>/opp + set_env.sh + site-packages). | ||
| 23 | +# gym's --install-path points at the opp dir, hence the dirname hop (decision 30). | ||
| 24 | +gym_python_public_dir() { | ||
| 25 | + local opp_root cann_root | ||
| 26 | + opp_root=$(readlink -f "$1") || return 1 | ||
| 27 | + cann_root=$(dirname "${opp_root}") | ||
| 28 | + if [ "${opp_root}" = "${cann_root}/opp" ] && | ||
| 29 | + [ -f "${cann_root}/set_env.sh" ] && | ||
| 30 | + [ -d "${cann_root}/python/site-packages" ]; then | ||
| 31 | + printf '%s\n' "${cann_root}/python/site-packages/pypto_gym" | ||
| 32 | + fi | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +gym_python_warn_degraded() { | ||
| 36 | + local targetdir="$1" reason="$2" | ||
| 37 | + printf 'warning: %s; the Python layer was not registered\n' "${reason}" >&2 | ||
| 38 | + printf 'warning: pip install the embedded wheel manually to enable pypto_gym:\n' >&2 | ||
| 39 | + printf 'warning: python3 -m pip install %s/vendors/pypto_gym/python/pypto_gym-*.whl\n' \ | ||
| 40 | + "${targetdir}" >&2 | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +# pip-install the embedded shell wheel. Prints the registered package dir on | ||
| 44 | +# success; always returns 0 (non-fatal by design), warnings go to stderr. | ||
| 45 | +# Namespace ownership: pypto_gym is owned solely by this distribution (the | ||
| 46 | +# shared-namespace kernel wheel is retired, decisions 24/25), so pip's | ||
| 47 | +# whole-directory replacement (--upgrade) is the intended upgrade semantics; | ||
| 48 | +# uninstall remains RECORD-precise and preserves foreign files. | ||
| 49 | +gym_install_shell_wheel() { | ||
| 50 | + local targetdir="$1" public_dir site_dir whl | ||
| 51 | + public_dir=$(gym_python_public_dir "${targetdir}") || return 0 | ||
| 52 | + [ -n "${public_dir}" ] || return 0 | ||
| 53 | + site_dir=$(dirname "${public_dir}") | ||
| 54 | + whl=$(find "${targetdir}/vendors/pypto_gym/python" -maxdepth 1 -name "pypto_gym-*.whl" 2>/dev/null | head -1) | ||
| 55 | + if [ -z "${whl}" ]; then | ||
| 56 | + gym_python_warn_degraded "${targetdir}" "no shell wheel in the payload" | ||
| 57 | + return 0 | ||
| 58 | + fi | ||
| 59 | + if ! command -v python3 >/dev/null 2>&1; then | ||
| 60 | + gym_python_warn_degraded "${targetdir}" "python3 is not available" | ||
| 61 | + return 0 | ||
| 62 | + fi | ||
| 63 | + # Migration guard: drop legacy symlink trees left by pre-wheel versions. | ||
| 64 | + if [ -L "${public_dir}" ] || { [ -d "${public_dir}" ] && [ -n "$(find "${public_dir}" -maxdepth 1 -type l 2>/dev/null | head -1)" ]; }; then | ||
| 65 | + chmod -R +w "${public_dir}" 2>/dev/null | ||
| 66 | + rm -rf "${public_dir}" | ||
| 67 | + fi | ||
| 68 | + # Ownership guard: a foreign real __init__.py without our dist-info means | ||
| 69 | + # another package squats the name; never clobber it (pip --force-reinstall | ||
| 70 | + # would). A namespace-style directory (e.g. a kernel wheel's pypto_gym/ops) | ||
| 71 | + # is mergeable and passes. | ||
| 72 | + if [ -f "${public_dir}/__init__.py" ] && [ ! -L "${public_dir}/__init__.py" ] && \ | ||
| 73 | + [ -z "$(find "${site_dir}" -maxdepth 1 -type d -name "pypto_gym-*.dist-info" 2>/dev/null | head -1)" ]; then | ||
| 74 | + gym_python_warn_degraded "${targetdir}" \ | ||
| 75 | + "Python binding path is already occupied by another package: ${public_dir}" | ||
| 76 | + return 0 | ||
| 77 | + fi | ||
| 78 | + if [ ! -w "${site_dir}" ]; then | ||
| 79 | + gym_python_warn_degraded "${targetdir}" "CANN site-packages is not writable" | ||
| 80 | + return 0 | ||
| 81 | + fi | ||
| 82 | + if ! python3 -m pip install --disable-pip-version-check --no-deps --no-compile \ | ||
| 83 | + --force-reinstall --upgrade -t "${site_dir}" "${whl}" >/dev/null 2>&1; then | ||
| 84 | + gym_python_warn_degraded "${targetdir}" "pip install of the shell wheel failed" | ||
| 85 | + return 0 | ||
| 86 | + fi | ||
| 87 | + if [ "${ARG_INSTALL_FOR_ALL:-n}" = "y" ]; then | ||
| 88 | + # Multi-user scenario: pip -t honors umask, so widen readability the | ||
| 89 | + # same way the vendor tree does under --install-for-all. | ||
| 90 | + chmod -R a+rX "${public_dir}" 2>/dev/null | ||
| 91 | + find "${site_dir}" -maxdepth 1 -type d -name "pypto_gym-*.dist-info" \ | ||
| 92 | + -exec chmod -R a+rX {} + 2>/dev/null | ||
| 93 | + fi | ||
| 94 | + printf '%s\n' "${public_dir}" | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +# Remove the pip-registered package via its RECORD (files owned by other | ||
| 98 | +# distributions under pypto_gym/, e.g. a kernel wheel's ops/ tree, survive); | ||
| 99 | +# legacy symlink trees are dropped wholesale. | ||
| 100 | +gym_remove_shell_wheel() { | ||
| 101 | + local targetdir="$1" public_dir site_dir distinfo entry | ||
| 102 | + public_dir=$(gym_python_public_dir "${targetdir}") || return 0 | ||
| 103 | + [ -n "${public_dir}" ] || return 0 | ||
| 104 | + site_dir=$(dirname "${public_dir}") | ||
| 105 | + if [ -d "${public_dir}" ] && [ -n "$(find "${public_dir}" -maxdepth 1 -type l 2>/dev/null | head -1)" ]; then | ||
| 106 | + chmod -R +w "${public_dir}" 2>/dev/null | ||
| 107 | + rm -rf "${public_dir}" || return 1 | ||
| 108 | + fi | ||
| 109 | + distinfo=$(find "${site_dir}" -maxdepth 1 -type d -name "pypto_gym-*.dist-info" 2>/dev/null | head -1) | ||
| 110 | + if [ -n "${distinfo}" ] && [ -f "${distinfo}/RECORD" ]; then | ||
| 111 | + while IFS= read -r entry; do | ||
| 112 | + [ -n "${entry}" ] || continue | ||
| 113 | + rm -f "${site_dir}/${entry%%,*}" 2>/dev/null | ||
| 114 | + done < "${distinfo}/RECORD" | ||
| 115 | + rm -rf "${distinfo}" | ||
| 116 | + # Bytecode caches are not in RECORD but are regenerable and ours | ||
| 117 | + # (nested too: importing _jit/_frontends creates per-subpackage caches). | ||
| 118 | + find "${public_dir}" -type d -name "__pycache__" -prune -exec rm -rf {} + 2>/dev/null | ||
| 119 | + # Drop now-empty package subdirs bottom-up, then the package dir itself | ||
| 120 | + # only when empty: foreign files (shared namespace) survive. | ||
| 121 | + find "${public_dir}" -mindepth 1 -type d -empty -delete 2>/dev/null | ||
| 122 | + rmdir "${public_dir}" 2>/dev/null | ||
| 123 | + fi | ||
| 124 | + return 0 | ||
| 125 | +} | ||
| @@ -18,7 +18,7 @@ vendor_name=pypto_gym | |||
| 18 | # 从本脚本位置反推 vendors 根目录与 config.ini | 18 | # 从本脚本位置反推 vendors 根目录与 config.ini |
| 19 | # 本脚本位于 <opp>/vendors/<vendor>/scripts/uninstall.sh, 向上 2 级 = <opp>/vendors | 19 | # 本脚本位于 <opp>/vendors/<vendor>/scripts/uninstall.sh, 向上 2 级 = <opp>/vendors |
| 20 | curr_path=$(dirname "$(readlink -f "$0")") | 20 | curr_path=$(dirname "$(readlink -f "$0")") |
| 21 | -source "${curr_path}/python_registration.sh" | 21 | +source "${curr_path}/python_wheel.sh" |
| 22 | vendordir=$(realpath "${curr_path}/../../") | 22 | vendordir=$(realpath "${curr_path}/../../") |
| 23 | config_file="${vendordir}/config.ini" | 23 | config_file="${vendordir}/config.ini" |
| 24 | 24 | ||
| @@ -28,7 +28,7 @@ log() { | |||
| 28 | } | 28 | } |
| 29 | 29 | ||
| 30 | # 先清理由本包创建的 Python 入口,保留其他 wheel 的 ops 目录。 | 30 | # 先清理由本包创建的 Python 入口,保留其他 wheel 的 ops 目录。 |
| 31 | -gym_python_remove_links "$(dirname "${vendordir}")" || exit 1 | 31 | +gym_remove_shell_wheel "$(dirname "${vendordir}")" || exit 1 |
| 32 | 32 | ||
| 33 | # 删除 vendor 目录 | 33 | # 删除 vendor 目录 |
| 34 | if [ ! -d "${vendordir}/${vendor_name}" ]; then | 34 | if [ ! -d "${vendordir}/${vendor_name}" ]; then |
| @@ -10,42 +10,144 @@ | |||
| 10 | # ----------------------------------------------------------------------------------------------------------- | 10 | # ----------------------------------------------------------------------------------------------------------- |
| 11 | """PyPTO-GYM setuptools configuration module | 11 | """PyPTO-GYM setuptools configuration module |
| 12 | 12 | ||
| 13 | -Source tree to install tree path mapping is controlled here: | 13 | +Two wheel forms, selected by exactly one environment variable (both produced |
| 14 | +by build_ci.py; bare `python -m build` is rejected with a pointer): | ||
| 14 | 15 | ||
| 15 | - ops -> pypto_gym.ops # operator library: pro/tensor paradigms map level by level | 16 | +- GYM_WHL_STAGE=<dir> community full wheel: Python shell + _bindings materials |
| 17 | + (csrc/frontends/manifest) + _opp vendor tree (precompiled kernels / tiling / | ||
| 18 | + aclnn). Tag py3-none-<plat>: platform binaries aboard, but no Python/torch | ||
| 19 | + ABI lock (bindings are JIT compiled at runtime, decision 28). The plat tag | ||
| 20 | + defaults to linux_<arch>; pass a manylinux plat via build_ci.py --plat_name | ||
| 21 | + (forwarded as `bdist_wheel --plat-name=...`) for PyPI-compatible tags. | ||
| 22 | + Version <base>. | ||
| 23 | +- GYM_WHL_SHELL=<dir> run-embedded shell wheel: Python shell + _bindings only, | ||
| 24 | + no vendor binaries. Tag py3-none-any (fully platform independent, shared by | ||
| 25 | + x86/aarch64 run packages). Version <base>. | ||
| 16 | 26 | ||
| 17 | -Only packages under ops/pro and ops/tensor are discovered; tests/op_host | 27 | +The staged tree layout (materialized by `cmake --install`; the repo source tree |
| 18 | -directories inside operator trees and non-.py files (.md/.txt etc.) are | 28 | +under python/pypto_gym/ mirrors it 1:1) is <dir>/pypto_gym/{__init__.py, |
| 19 | -excluded from the bdist. | 29 | +_loader/,_bindings/{operators.json,csrc/,frontends/}[,_opp/]}. |
| 20 | """ | 30 | """ |
| 21 | 31 | ||
| 22 | import logging | 32 | import logging |
| 33 | +import os | ||
| 23 | from pathlib import Path | 34 | from pathlib import Path |
| 24 | -from typing import Dict, List, Tuple | 35 | +from typing import List |
| 25 | from datetime import datetime, timezone | 36 | from datetime import datetime, timezone |
| 26 | 37 | ||
| 27 | import setuptools | 38 | import setuptools |
| 39 | +from setuptools.dist import Distribution | ||
| 40 | +from setuptools.command.egg_info import egg_info as _egg_info | ||
| 41 | + | ||
| 42 | +try: | ||
| 43 | + from setuptools.command.bdist_wheel import bdist_wheel as _bdist_wheel | ||
| 44 | +except ImportError: # older setuptools: fall back to the wheel package | ||
| 45 | + from wheel.bdist_wheel import bdist_wheel as _bdist_wheel | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +class BinaryDistribution(Distribution): | ||
| 49 | + """Force a platform-specific wheel (Root-Is-Purelib: false). | ||
| 50 | + | ||
| 51 | + The full form ships the vendor tree (kernel .o, host libraries) as package | ||
| 52 | + data; without this, bdist_wheel would tag the wheel py3-none-any and pip | ||
| 53 | + would install it on incompatible platforms. | ||
| 54 | + """ | ||
| 55 | + | ||
| 56 | + def has_ext_modules(self): | ||
| 57 | + return True | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +class Py3NonePlatformWheel(_bdist_wheel): | ||
| 61 | + """Tag the full form py3-none-<plat>. | ||
| 62 | + | ||
| 63 | + The binaries aboard are Python/torch ABI free (device kernels + C-API host | ||
| 64 | + libraries; bindings are JIT compiled against the runtime torch), so the | ||
| 65 | + cpXX-cpXX interpreter lock of the default platform tag would wrongly | ||
| 66 | + reject compatible interpreters (decision 22/28). | ||
| 67 | + """ | ||
| 68 | + | ||
| 69 | + def finalize_options(self): | ||
| 70 | + super().finalize_options() | ||
| 71 | + self.python_tag = "py3" | ||
| 72 | + | ||
| 73 | + def get_tag(self): | ||
| 74 | + _python, _abi, plat = super().get_tag() | ||
| 75 | + return "py3", "none", plat | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +class CustomEggInfo(_egg_info): | ||
| 79 | + """Inject X-Build-Timestamp into PKG-INFO (bdist_wheel copies it to METADATA). | ||
| 80 | + | ||
| 81 | + setuptools has no public API for custom METADATA fields; following pypto's | ||
| 82 | + CustomEggInfo, the field is inserted into the RFC 5322 header region (before | ||
| 83 | + the blank-line separator) so importlib.metadata can parse it. The JIT cache | ||
| 84 | + keys on this build identity: same-version rebuilds must not reuse a stale | ||
| 85 | + binding cache. The timestamp comes from GYM_BUILD_TIMESTAMP (build_ci | ||
| 86 | + injects one per build round, shared by the full and shell wheels); a manual | ||
| 87 | + `python -m build` generates one locally. | ||
| 88 | + """ | ||
| 89 | + | ||
| 90 | + def run(self): | ||
| 91 | + super().run() | ||
| 92 | + self._inject_build_timestamp() | ||
| 93 | + | ||
| 94 | + def _inject_build_timestamp(self): | ||
| 95 | + metadata_file = Path(self.egg_info) / "PKG-INFO" | ||
| 96 | + if not metadata_file.exists(): | ||
| 97 | + # 兼容部分 setuptools 版本使用 METADATA 文件名 | ||
| 98 | + metadata_file = Path(self.egg_info) / "METADATA" | ||
| 99 | + if not metadata_file.exists(): | ||
| 100 | + # -e 模式下没有 METADATA/PKG-INFO 文件 | ||
| 101 | + logging.warning("Can't get METADATA in %s", self.egg_info) | ||
| 102 | + return | ||
| 103 | + timestamp = os.environ.get("GYM_BUILD_TIMESTAMP", "").strip() | ||
| 104 | + if not timestamp: | ||
| 105 | + timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") | ||
| 106 | + field = f"X-Build-Timestamp: {timestamp}\n" | ||
| 107 | + content = metadata_file.read_text(encoding="utf-8") | ||
| 108 | + separator = "\n\n" | ||
| 109 | + idx = content.find(separator) | ||
| 110 | + if idx == -1: | ||
| 111 | + # 无空行分隔符(异常情况), 追加到末尾 | ||
| 112 | + metadata_file.write_text(content + field, encoding="utf-8") | ||
| 113 | + else: | ||
| 114 | + metadata_file.write_text(content[:idx] + "\n" + field + content[idx + 1:], encoding="utf-8") | ||
| 28 | 115 | ||
| 29 | 116 | ||
| 30 | class SetupCtrl: | 117 | class SetupCtrl: |
| 31 | - """Setuptools configuration flow controller | 118 | + """Setuptools configuration flow controller (staged-tree packaging only).""" |
| 32 | - | ||
| 33 | - Discovers source packages and the operator tree, generates the | ||
| 34 | - packages/package_dir mapping, and starts the setuptools build. | ||
| 35 | - """ | ||
| 36 | 119 | ||
| 37 | _LICENSE_EXPR: str = "LicenseRef-CANN-Open-Software-License-Agreement-Version-2.0" | 120 | _LICENSE_EXPR: str = "LicenseRef-CANN-Open-Software-License-Agreement-Version-2.0" |
| 38 | _LICENSE_FILES: List[str] = ["LICENSE"] | 121 | _LICENSE_FILES: List[str] = ["LICENSE"] |
| 39 | - | 122 | + _PACKAGE: str = "pypto_gym" |
| 40 | - # Paradigm dirs under ops/ that participate in packaging | 123 | + _PACKAGE_DATA_COMMON: List[str] = [ |
| 41 | - _PARADIGM_DIRS = ("pro", "tensor") | 124 | + "_bindings/operators.json", |
| 42 | - | 125 | + "_bindings/frontends/*.py", |
| 43 | - # Dir names inside operator trees excluded from packaging | 126 | + "_bindings/csrc/*", |
| 44 | - _EXCLUDED_DIRS = {"tests", "op_host", "__pycache__"} | 127 | + ] |
| 128 | + _PACKAGE_DATA_FULL: List[str] = _PACKAGE_DATA_COMMON + [ | ||
| 129 | + "_opp/vendors/**/*", | ||
| 130 | + ] | ||
| 45 | 131 | ||
| 46 | def __init__(self): | 132 | def __init__(self): |
| 47 | self.src_root: Path = Path(__file__).parent.resolve() | 133 | self.src_root: Path = Path(__file__).parent.resolve() |
| 48 | - self.packages, self.package_dir = self._discover_packages() | 134 | + stage = os.environ.get("GYM_WHL_STAGE", "") |
| 135 | + shell = os.environ.get("GYM_WHL_SHELL", "") | ||
| 136 | + if bool(stage) == bool(shell): | ||
| 137 | + raise RuntimeError( | ||
| 138 | + "exactly one of GYM_WHL_STAGE (community full wheel) or GYM_WHL_SHELL " | ||
| 139 | + "(run-embedded shell wheel) must be set; build wheels via " | ||
| 140 | + "build_ci.py --pkg-type whl|run") | ||
| 141 | + self.shell_mode: bool = bool(shell) | ||
| 142 | + root = Path(shell if self.shell_mode else stage).resolve() | ||
| 143 | + if not (root / self._PACKAGE / "__init__.py").is_file(): | ||
| 144 | + raise RuntimeError(f"staged tree {root} misses {self._PACKAGE}/__init__.py") | ||
| 145 | + self.stage: Path = root | ||
| 146 | + self.packages: List[str] = [self._PACKAGE, f"{self._PACKAGE}._loader"] | ||
| 147 | + # package_dir must be relative to the setup.py directory (setuptools requirement). | ||
| 148 | + self.package_dir = { | ||
| 149 | + self._PACKAGE: os.path.relpath(root / self._PACKAGE, self.src_root) | ||
| 150 | + } | ||
| 49 | 151 | ||
| 50 | @classmethod | 152 | @classmethod |
| 51 | def main(cls): | 153 | def main(cls): |
| @@ -62,68 +164,28 @@ class SetupCtrl: | |||
| 62 | @classmethod | 164 | @classmethod |
| 63 | def _main(cls): | 165 | def _main(cls): |
| 64 | ctrl = SetupCtrl() | 166 | ctrl = SetupCtrl() |
| 65 | - logging.info("packaging %d packages", len(ctrl.packages)) | 167 | + logging.info("packaging %d packages (shell=%s)", len(ctrl.packages), ctrl.shell_mode) |
| 66 | - setuptools.setup( | 168 | + kwargs = dict( |
| 67 | # 1. SPDX expression; newer setuptools maps it to the License-Expression field | 169 | # 1. SPDX expression; newer setuptools maps it to the License-Expression field |
| 68 | # 2. license_files packs LICENSE into dist-info/licenses across setuptools versions | 170 | # 2. license_files packs LICENSE into dist-info/licenses across setuptools versions |
| 69 | license=cls._LICENSE_EXPR, | 171 | license=cls._LICENSE_EXPR, |
| 70 | license_files=cls._LICENSE_FILES, | 172 | license_files=cls._LICENSE_FILES, |
| 71 | packages=ctrl.packages, | 173 | packages=ctrl.packages, |
| 72 | package_dir=ctrl.package_dir, | 174 | package_dir=ctrl.package_dir, |
| 175 | + zip_safe=False, | ||
| 73 | ) | 176 | ) |
| 74 | - | 177 | + if ctrl.shell_mode: |
| 75 | - def _discover_packages(self) -> Tuple[List[str], Dict[str, str]]: | 178 | + kwargs.update( |
| 76 | - """Aggregate the packaging scope (currently the ops tree only).""" | 179 | + package_data={cls._PACKAGE: cls._PACKAGE_DATA_COMMON}, |
| 77 | - packages: List[str] = [] | 180 | + cmdclass={"egg_info": CustomEggInfo}, |
| 78 | - package_dir: Dict[str, str] = {} | 181 | + ) |
| 79 | - ops_packages, ops_package_dir = self._discover_ops_packages() | 182 | + else: |
| 80 | - packages += ops_packages | 183 | + kwargs.update( |
| 81 | - package_dir.update(ops_package_dir) | 184 | + package_data={cls._PACKAGE: cls._PACKAGE_DATA_FULL}, |
| 82 | - return packages, package_dir | 185 | + distclass=BinaryDistribution, |
| 83 | - | 186 | + cmdclass={"bdist_wheel": Py3NonePlatformWheel, "egg_info": CustomEggInfo}, |
| 84 | - def _discover_ops_packages(self) -> Tuple[List[str], Dict[str, str]]: | 187 | + ) |
| 85 | - """Discover the ops tree and generate the packages list and package_dir mapping. | 188 | + setuptools.setup(**kwargs) |
| 86 | - | ||
| 87 | - 1. Only packages under the _PARADIGM_DIRS trees (pro/tensor) are discovered: | ||
| 88 | - ops/<paradigm> maps to pypto_gym.ops.<paradigm>, with network/operator | ||
| 89 | - dirs mapping level by level; | ||
| 90 | - 2. Legacy trees outside pro/tensor (e.g. pypto_pro/pypto_tensor) are not | ||
| 91 | - packaged until they are migrated to the pro/tensor layout; | ||
| 92 | - 3. tests/op_host dirs inside operator trees are skipped, so they never | ||
| 93 | - enter the bdist; | ||
| 94 | - 4. package_dir values must be paths relative to the repo root (the | ||
| 95 | - setup.py directory). | ||
| 96 | - """ | ||
| 97 | - ops_root = self.src_root / "ops" | ||
| 98 | - if not ops_root.is_dir(): | ||
| 99 | - logging.warning("Ops tree not found: %s", ops_root) | ||
| 100 | - return [], {} | ||
| 101 | - all_dirs = [] | ||
| 102 | - for path in ops_root.iterdir(): | ||
| 103 | - if path.is_dir() and not path.name.startswith((".", "__")): | ||
| 104 | - all_dirs.append(path.name) | ||
| 105 | - ignored = sorted(d for d in all_dirs if d not in self._PARADIGM_DIRS) | ||
| 106 | - if ignored: | ||
| 107 | - logging.warning("Skip non-paradigm dirs under ops: %s", ignored) | ||
| 108 | - packages: List[str] = ["pypto_gym.ops"] | ||
| 109 | - for paradigm in self._PARADIGM_DIRS: | ||
| 110 | - paradigm_root = ops_root / paradigm | ||
| 111 | - if not paradigm_root.is_dir(): | ||
| 112 | - logging.warning("Paradigm tree not found: %s", paradigm_root) | ||
| 113 | - continue | ||
| 114 | - pkg_root = f"pypto_gym.ops.{paradigm}" | ||
| 115 | - packages.append(pkg_root) | ||
| 116 | - for path in sorted(paradigm_root.rglob("*")): | ||
| 117 | - if not path.is_dir(): | ||
| 118 | - continue | ||
| 119 | - rel = path.relative_to(paradigm_root) | ||
| 120 | - if any(part in self._EXCLUDED_DIRS for part in rel.parts): | ||
| 121 | - continue | ||
| 122 | - if not path.name.isidentifier(): | ||
| 123 | - logging.warning("skip non-identifier package dir: %s", path) | ||
| 124 | - continue | ||
| 125 | - packages.append(f"{pkg_root}." + ".".join(rel.parts)) | ||
| 126 | - return packages, {"pypto_gym.ops": "ops"} | ||
| 127 | 189 | ||
| 128 | 190 | ||
| 129 | if __name__ == "__main__": | 191 | if __name__ == "__main__": |
| @@ -99,7 +99,7 @@ class RunBuildScopeTest(unittest.TestCase): | |||
| 99 | with self.assertRaisesRegex(ValueError, "ambiguous"): | 99 | with self.assertRaisesRegex(ValueError, "ambiguous"): |
| 100 | scope.select_run_ops(self.root, "mega_mhc") | 100 | scope.select_run_ops(self.root, "mega_mhc") |
| 101 | 101 | ||
| 102 | - def test_stest_uses_run_manifest_and_keeps_whl_scope(self): | 102 | + def test_stest_uses_build_manifest_for_both_pkg_types(self): |
| 103 | ctrl = BuildCtrl.__new__(BuildCtrl) | 103 | ctrl = BuildCtrl.__new__(BuildCtrl) |
| 104 | ctrl.src_root = self.root | 104 | ctrl.src_root = self.root |
| 105 | ctrl.feature = SimpleNamespace(ops="ALL", pkg_type_run=True) | 105 | ctrl.feature = SimpleNamespace(ops="ALL", pkg_type_run=True) |
| @@ -108,14 +108,13 @@ class RunBuildScopeTest(unittest.TestCase): | |||
| 108 | ctrl.feature.ops = "example_op" | 108 | ctrl.feature.ops = "example_op" |
| 109 | self.assertEqual([p.name for p in ctrl.selected_op_dirs()], ["example_op"]) | 109 | self.assertEqual([p.name for p in ctrl.selected_op_dirs()], ["example_op"]) |
| 110 | ctrl.feature = SimpleNamespace(ops="ALL", pkg_type_run=False) | 110 | ctrl.feature = SimpleNamespace(ops="ALL", pkg_type_run=False) |
| 111 | - self.assertEqual([p.name for p in ctrl.selected_op_dirs()], | 111 | + self.assertEqual([p.name for p in ctrl.selected_op_dirs()], ["mega_mhc"]) |
| 112 | - ["example_op", "mega_mhc", "unlisted_op"]) | ||
| 113 | 112 | ||
| 114 | def test_default_bindings_fall_back_to_aclnn_when_unsupported(self): | 113 | def test_default_bindings_fall_back_to_aclnn_when_unsupported(self): |
| 115 | ctrl = BuildCtrl.__new__(BuildCtrl) | 114 | ctrl = BuildCtrl.__new__(BuildCtrl) |
| 116 | ctrl.src_root = self.root | 115 | ctrl.src_root = self.root |
| 117 | ctrl.feature = SimpleNamespace(ops="example_op", pkg_type_run=True, | 116 | ctrl.feature = SimpleNamespace(ops="example_op", pkg_type_run=True, |
| 118 | - torch_bindings=True, torch_bindings_explicit=False) | 117 | + torch_bindings=True) |
| 119 | ctrl.resolve_torch_bindings() | 118 | ctrl.resolve_torch_bindings() |
| 120 | self.assertFalse(ctrl.feature.torch_bindings) | 119 | self.assertFalse(ctrl.feature.torch_bindings) |
| 121 | 120 | ||
| @@ -126,12 +125,27 @@ class RunBuildScopeTest(unittest.TestCase): | |||
| 126 | ctrl.resolve_torch_bindings() | 125 | ctrl.resolve_torch_bindings() |
| 127 | self.assertTrue(ctrl.feature.torch_bindings) | 126 | self.assertTrue(ctrl.feature.torch_bindings) |
| 128 | 127 | ||
| 129 | - # An explicit --torch-bindings request is still validated by CMake. | 128 | + def test_whl_bindings_required_when_unsupported(self): |
| 130 | - ctrl.feature = SimpleNamespace(ops="mega_mhc", pkg_type_run=True, | 129 | + ctrl = BuildCtrl.__new__(BuildCtrl) |
| 131 | - torch_bindings=True, torch_bindings_explicit=True) | 130 | + ctrl.src_root = self.root |
| 131 | + # whl fails instead of degrading: the wheel's main path is torch.ops. | ||
| 132 | + ctrl.feature = SimpleNamespace(ops="example_op", pkg_type_run=False, | ||
| 133 | + torch_bindings=True) | ||
| 134 | + with self.assertRaises(ValueError): | ||
| 135 | + ctrl.resolve_torch_bindings() | ||
| 136 | + | ||
| 137 | + binding = self.root / "ops/pro/experimental/example_op/torch_extension" | ||
| 138 | + binding.mkdir() | ||
| 139 | + (binding / "CMakeLists.txt").write_text("# binding fixture\n") | ||
| 132 | ctrl.resolve_torch_bindings() | 140 | ctrl.resolve_torch_bindings() |
| 133 | self.assertTrue(ctrl.feature.torch_bindings) | 141 | self.assertTrue(ctrl.feature.torch_bindings) |
| 134 | 142 | ||
| 143 | + # An explicit --no-torch-bindings request skips the scope check entirely. | ||
| 144 | + ctrl.feature = SimpleNamespace(ops="unlisted_op", pkg_type_run=False, | ||
| 145 | + torch_bindings=False) | ||
| 146 | + ctrl.resolve_torch_bindings() | ||
| 147 | + self.assertFalse(ctrl.feature.torch_bindings) | ||
| 148 | + | ||
| 135 | def test_cmake_ignores_unselected_orphans(self): | 149 | def test_cmake_ignores_unselected_orphans(self): |
| 136 | cmake = BuildCtrl.which_cmake() | 150 | cmake = BuildCtrl.which_cmake() |
| 137 | if not cmake: | 151 | if not cmake: |
| @@ -6,17 +6,50 @@ | |||
| 6 | # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | 6 | # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. |
| 7 | # See LICENSE in the root of the software repository for the full text of the License. | 7 | # See LICENSE in the root of the software repository for the full text of the License. |
| 8 | # ----------------------------------------------------------------------------------------------------------- | 8 | # ----------------------------------------------------------------------------------------------------------- |
| 9 | -"""Exercise the run installer in temporary CANN and custom directories.""" | 9 | + |
| 10 | -import os | 10 | +"""Exercise the run installer (pip shell-wheel registration) in temporary CANN |
| 11 | +and custom directories. Decision 29/30: the run payload embeds a python shell | ||
| 12 | +wheel; the installer pip-installs it into <cann_root>/python/site-packages for | ||
| 13 | +a standard CANN layout, and degrades with a warning otherwise.""" | ||
| 14 | +import base64 | ||
| 15 | +import hashlib | ||
| 16 | +import json | ||
| 11 | from pathlib import Path | 17 | from pathlib import Path |
| 18 | +import os | ||
| 12 | import shutil | 19 | import shutil |
| 13 | import subprocess | 20 | import subprocess |
| 14 | import sys | 21 | import sys |
| 15 | import tempfile | 22 | import tempfile |
| 16 | import unittest | 23 | import unittest |
| 24 | +import zipfile | ||
| 17 | 25 | ||
| 18 | ROOT = Path(__file__).resolve().parents[2] | 26 | ROOT = Path(__file__).resolve().parents[2] |
| 19 | 27 | ||
| 28 | +_WHEEL_NAME = "pypto_gym-0.0.0-py3-none-any.whl" | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def make_shell_wheel(path: Path, init_body: str = 'VALUE = "installed"\n'): | ||
| 32 | + """Hand-craft a minimal valid wheel (shell package + dist-info with RECORD).""" | ||
| 33 | + dist_info = "pypto_gym-0.0.0.dist-info" | ||
| 34 | + files = { | ||
| 35 | + "pypto_gym/__init__.py": init_body, | ||
| 36 | + "pypto_gym/_bindings/operators.json": '["example_op"]\n', | ||
| 37 | + } | ||
| 38 | + metadata = "Metadata-Version: 2.1\nName: pypto-gym\nVersion: 0.0.0\n" | ||
| 39 | + wheel_meta = ("Wheel-Version: 1.0\nGenerator: gym-test\n" | ||
| 40 | + "Root-Is-Purelib: true\nTag: py3-none-any\n") | ||
| 41 | + records = [] | ||
| 42 | + path.parent.mkdir(parents=True, exist_ok=True) | ||
| 43 | + with zipfile.ZipFile(path, "w") as zf: | ||
| 44 | + for arc, content in list(files.items()) + [ | ||
| 45 | + (f"{dist_info}/METADATA", metadata), (f"{dist_info}/WHEEL", wheel_meta)]: | ||
| 46 | + zf.writestr(arc, content) | ||
| 47 | + data = content.encode() | ||
| 48 | + digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() | ||
| 49 | + records.append(f"{arc},sha256={digest},{len(data)}") | ||
| 50 | + records.append(f"{dist_info}/RECORD,,") | ||
| 51 | + zf.writestr(f"{dist_info}/RECORD", "\n".join(records) + "\n") | ||
| 52 | + | ||
| 20 | 53 | ||
| 21 | class RunInstallTest(unittest.TestCase): | 54 | class RunInstallTest(unittest.TestCase): |
| 22 | def setUp(self): | 55 | def setUp(self): |
| @@ -38,10 +71,13 @@ class RunInstallTest(unittest.TestCase): | |||
| 38 | self.binding = self.payload / "packages/vendors/pypto_gym/python/pypto_gym" | 71 | self.binding = self.payload / "packages/vendors/pypto_gym/python/pypto_gym" |
| 39 | self.binding.mkdir(parents=True) | 72 | self.binding.mkdir(parents=True) |
| 40 | (self.binding / "__init__.py").write_text('VALUE = "installed"\n') | 73 | (self.binding / "__init__.py").write_text('VALUE = "installed"\n') |
| 41 | - (self.binding / "_loader.py").write_text("# loader fixture\n") | 74 | + (self.binding / "_loader").mkdir() |
| 42 | - (self.binding / "operators.json").write_text('["example_op"]\n') | 75 | + (self.binding / "_loader" / "__init__.py").write_text("# loader fixture\n") |
| 43 | - (self.binding / "_native").mkdir() | 76 | + (self.binding / "_bindings").mkdir() |
| 44 | - (self.binding / "_frontends").mkdir() | 77 | + (self.binding / "_bindings" / "operators.json").write_text('["example_op"]\n') |
| 78 | + (self.binding / "_bindings" / "csrc").mkdir() | ||
| 79 | + (self.binding / "_bindings" / "frontends").mkdir() | ||
| 80 | + make_shell_wheel(self.payload / f"packages/vendors/pypto_gym/python/{_WHEEL_NAME}") | ||
| 45 | self.env = dict(os.environ, ASCEND_HOME_PATH=str(self.cann)) | 81 | self.env = dict(os.environ, ASCEND_HOME_PATH=str(self.cann)) |
| 46 | 82 | ||
| 47 | def run_installer(self, *args, success=True): | 83 | def run_installer(self, *args, success=True): |
| @@ -55,13 +91,12 @@ class RunInstallTest(unittest.TestCase): | |||
| 55 | self.assertNotEqual(result.returncode, 0) | 91 | self.assertNotEqual(result.returncode, 0) |
| 56 | return result | 92 | return result |
| 57 | 93 | ||
| 58 | - def test_standard_cann_import_without_vendor_pythonpath(self): | 94 | + def test_standard_cann_pip_registration(self): |
| 59 | self.run_installer() | 95 | self.run_installer() |
| 60 | - for name in ("__init__.py", "_loader.py", "_native", "_frontends", "operators.json"): | 96 | + init = self.public / "__init__.py" |
| 61 | - link = self.public / name | 97 | + self.assertTrue(init.is_file()) |
| 62 | - self.assertTrue(link.is_symlink(), link) | 98 | + self.assertFalse(init.is_symlink()) |
| 63 | - self.assertFalse(Path(os.readlink(link)).is_absolute()) | 99 | + self.assertTrue(list(self.site.glob("pypto_gym-*.dist-info"))) |
| 64 | - self.assertEqual(link.resolve(), (self.vendor / "python/pypto_gym" / name).resolve()) | ||
| 65 | result = subprocess.run( | 100 | result = subprocess.run( |
| 66 | [sys.executable, "-c", "import pypto_gym; print(pypto_gym.VALUE)"], | 101 | [sys.executable, "-c", "import pypto_gym; print(pypto_gym.VALUE)"], |
| 67 | cwd=self.root, env=dict(self.env, PYTHONPATH=str(self.site)), | 102 | cwd=self.root, env=dict(self.env, PYTHONPATH=str(self.site)), |
| @@ -69,23 +104,31 @@ class RunInstallTest(unittest.TestCase): | |||
| 69 | self.assertEqual(result.stdout.strip(), "installed") | 104 | self.assertEqual(result.stdout.strip(), "installed") |
| 70 | self.run_installer("--uninstall") | 105 | self.run_installer("--uninstall") |
| 71 | self.assertFalse(self.public.exists()) | 106 | self.assertFalse(self.public.exists()) |
| 107 | + self.assertFalse(list(self.site.glob("pypto_gym-*.dist-info"))) | ||
| 72 | self.assertFalse(self.vendor.exists()) | 108 | self.assertFalse(self.vendor.exists()) |
| 73 | 109 | ||
| 74 | - def test_custom_install_does_not_publish_into_cann(self): | 110 | + def test_custom_install_keeps_wheel_for_manual_pip(self): |
| 75 | custom = self.root / "custom" | 111 | custom = self.root / "custom" |
| 76 | custom.mkdir() | 112 | custom.mkdir() |
| 77 | self.run_installer(f"--install-path={custom}") | 113 | self.run_installer(f"--install-path={custom}") |
| 78 | self.assertFalse(self.public.exists()) | 114 | self.assertFalse(self.public.exists()) |
| 79 | vendor = custom / "vendors/pypto_gym" | 115 | vendor = custom / "vendors/pypto_gym" |
| 80 | - self.assertTrue((vendor / "python/pypto_gym/operators.json").is_file()) | 116 | + self.assertTrue((vendor / f"python/{_WHEEL_NAME}").is_file()) |
| 81 | - self.assertIn(str(vendor / "python"), (vendor / "bin/set_env.bash").read_text()) | 117 | + self.assertTrue((vendor / "python/pypto_gym/_bindings/operators.json").is_file()) |
| 118 | + set_env = (vendor / "bin/set_env.bash").read_text() | ||
| 119 | + self.assertIn("ASCEND_CUSTOM_OPP_PATH", set_env) | ||
| 120 | + self.assertNotIn("PYTHONPATH", set_env) # decision 29: pip carries the Python layer | ||
| 82 | self.run_installer("--uninstall", f"--install-path={custom}") | 121 | self.run_installer("--uninstall", f"--install-path={custom}") |
| 83 | self.assertFalse(vendor.exists()) | 122 | self.assertFalse(vendor.exists()) |
| 84 | 123 | ||
| 85 | - def test_unwritable_cann_degrades_to_vendor_only(self): | 124 | + def test_missing_whl_degrades_with_warning(self): |
| 86 | - # Simulate a non-root install into a root-owned CANN: the vendor tree is | 125 | + (self.payload / f"packages/vendors/pypto_gym/python/{_WHEEL_NAME}").unlink() |
| 87 | - # writable, but python/site-packages is not. Installation must still | 126 | + result = self.run_installer() |
| 88 | - # succeed and point the user at the vendor set_env.bash. | 127 | + self.assertFalse(self.public.exists()) |
| 128 | + self.assertTrue((self.vendor / "python/pypto_gym/_bindings/operators.json").is_file()) | ||
| 129 | + self.assertIn("not registered", result.stdout + result.stderr) | ||
| 130 | + | ||
| 131 | + def test_unwritable_site_packages_degrades_to_vendor_only(self): | ||
| 89 | setpriv = shutil.which("setpriv") | 132 | setpriv = shutil.which("setpriv") |
| 90 | if os.geteuid() != 0 or not setpriv: | 133 | if os.geteuid() != 0 or not setpriv: |
| 91 | self.skipTest("requires root and setpriv to drop privileges") | 134 | self.skipTest("requires root and setpriv to drop privileges") |
| @@ -100,11 +143,10 @@ class RunInstallTest(unittest.TestCase): | |||
| 100 | "--" + str(self.root)], env=self.env, capture_output=True, text=True) | 143 | "--" + str(self.root)], env=self.env, capture_output=True, text=True) |
| 101 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr) | 144 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr) |
| 102 | self.assertFalse(self.public.exists()) | 145 | self.assertFalse(self.public.exists()) |
| 103 | - self.assertTrue((self.vendor / "python/pypto_gym/operators.json").is_file()) | 146 | + self.assertTrue((self.vendor / "python/pypto_gym/_bindings/operators.json").is_file()) |
| 104 | self.assertIn("not registered", result.stdout + result.stderr) | 147 | self.assertIn("not registered", result.stdout + result.stderr) |
| 105 | - self.assertIn(str(self.vendor / "python"), (self.vendor / "bin/set_env.bash").read_text()) | ||
| 106 | 148 | ||
| 107 | - def test_public_registration_is_readable_with_restrictive_umask(self): | 149 | + def test_install_for_all_readable_with_restrictive_umask(self): |
| 108 | previous_umask = os.umask(0o077) | 150 | previous_umask = os.umask(0o077) |
| 109 | try: | 151 | try: |
| 110 | result = subprocess.run( | 152 | result = subprocess.run( |
| @@ -113,49 +155,72 @@ class RunInstallTest(unittest.TestCase): | |||
| 113 | finally: | 155 | finally: |
| 114 | os.umask(previous_umask) | 156 | os.umask(previous_umask) |
| 115 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr) | 157 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr) |
| 116 | - self.assertEqual(self.public.stat().st_mode & 0o777, 0o755) | 158 | + mode = (self.public / "__init__.py").stat().st_mode |
| 159 | + self.assertTrue(mode & 0o004, f"installed file is not world-readable: {oct(mode)}") | ||
| 117 | self.run_installer("--uninstall") | 160 | self.run_installer("--uninstall") |
| 118 | 161 | ||
| 119 | - def test_existing_kernel_namespace_survives_upgrade_and_standalone_uninstall(self): | 162 | + def test_uninstall_preserves_foreign_files(self): |
| 120 | - ops = self.public / "ops" | 163 | + # RECORD-precise removal: files not owned by our distribution survive |
| 121 | - ops.mkdir(parents=True) | 164 | + # uninstall (namespace replacement at install time is intended, |
| 122 | - marker = ops / "wheel.py" | 165 | + # decisions 24/25; uninstall must still not rm -rf blindly). |
| 123 | - marker.write_text("# existing kernel wheel\n") | ||
| 124 | (self.opp / "vendors").mkdir() | 166 | (self.opp / "vendors").mkdir() |
| 125 | (self.opp / "vendors/config.ini").write_text("load_priority=other_vendor\n") | 167 | (self.opp / "vendors/config.ini").write_text("load_priority=other_vendor\n") |
| 126 | self.run_installer() | 168 | self.run_installer() |
| 127 | - self.run_installer() # Upgrade removes and recreates only owned links. | 169 | + self.assertTrue((self.public / "__init__.py").is_file()) |
| 170 | + foreign = self.public / "foreign.txt" | ||
| 171 | + foreign.write_text("not ours\n") | ||
| 172 | + # Runtime imports leave nested bytecode caches that are not in RECORD. | ||
| 173 | + for sub in ("", "_loader/", "_bindings/frontends/"): | ||
| 174 | + pycache = self.public / sub / "__pycache__" | ||
| 175 | + pycache.mkdir(parents=True, exist_ok=True) | ||
| 176 | + (pycache / "mod.cpython-312.pyc").write_bytes(b"\x00") | ||
| 128 | result = subprocess.run( | 177 | result = subprocess.run( |
| 129 | [str(self.vendor / "scripts/uninstall.sh")], | 178 | [str(self.vendor / "scripts/uninstall.sh")], |
| 130 | env=self.env, capture_output=True, text=True) | 179 | env=self.env, capture_output=True, text=True) |
| 131 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr) | 180 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr) |
| 132 | - self.assertTrue(marker.is_file()) | 181 | + self.assertTrue(foreign.is_file()) # foreign file survives |
| 133 | - self.assertFalse((self.public / "__init__.py").is_symlink()) | 182 | + self.assertFalse((self.public / "__init__.py").exists()) |
| 183 | + self.assertFalse((self.public / "_loader").exists()) | ||
| 184 | + self.assertFalse(list(self.site.glob("pypto_gym-*.dist-info"))) | ||
| 134 | self.assertFalse(self.vendor.exists()) | 185 | self.assertFalse(self.vendor.exists()) |
| 135 | - self.assertEqual((self.opp / "vendors/config.ini").read_text(), "load_priority=other_vendor\n") | 186 | + self.assertEqual((self.opp / "vendors/config.ini").read_text(), |
| 187 | + "load_priority=other_vendor\n") | ||
| 136 | 188 | ||
| 137 | def test_unrelated_python_package_is_not_overwritten(self): | 189 | def test_unrelated_python_package_is_not_overwritten(self): |
| 138 | self.public.mkdir() | 190 | self.public.mkdir() |
| 139 | existing = self.public / "__init__.py" | 191 | existing = self.public / "__init__.py" |
| 140 | existing.write_text("# another package\n") | 192 | existing.write_text("# another package\n") |
| 141 | - self.vendor.mkdir(parents=True) | 193 | + # Registration degrades to a warning (non-fatal); the vendor tree is |
| 142 | - old = self.vendor / "old-version" | 194 | + # ours and is replaced as usual on install/upgrade. |
| 143 | - old.write_text("keep\n") | 195 | + result = self.run_installer() |
| 144 | - result = self.run_installer(success=False) | 196 | + self.assertIn("occupied by another package", result.stdout + result.stderr) |
| 145 | - self.assertIn("already owned by another package", result.stderr) | ||
| 146 | self.assertEqual(existing.read_text(), "# another package\n") | 197 | self.assertEqual(existing.read_text(), "# another package\n") |
| 147 | - self.assertEqual(old.read_text(), "keep\n") | 198 | + self.assertTrue((self.vendor / "python/pypto_gym/_bindings/operators.json").is_file()) |
| 148 | 199 | ||
| 149 | def test_upgrade_without_bindings_removes_old_registration(self): | 200 | def test_upgrade_without_bindings_removes_old_registration(self): |
| 150 | self.run_installer() | 201 | self.run_installer() |
| 151 | - shutil.rmtree(self.binding) | 202 | + self.assertTrue((self.public / "__init__.py").is_file()) |
| 203 | + shutil.rmtree(self.binding.parent) # python/ tree incl. operators.json + whl | ||
| 152 | self.run_installer() | 204 | self.run_installer() |
| 153 | self.assertFalse(self.public.exists()) | 205 | self.assertFalse(self.public.exists()) |
| 154 | self.assertTrue(self.vendor.is_dir()) | 206 | self.assertTrue(self.vendor.is_dir()) |
| 155 | 207 | ||
| 208 | + def test_legacy_symlink_tree_is_replaced_by_pip_install(self): | ||
| 209 | + legacy_target = self.root / "legacy" | ||
| 210 | + legacy_target.mkdir() | ||
| 211 | + (legacy_target / "__init__.py").write_text('VALUE = "legacy"\n') | ||
| 212 | + self.public.mkdir(parents=True) | ||
| 213 | + (self.public / "__init__.py").symlink_to(legacy_target / "__init__.py") | ||
| 214 | + self.run_installer() | ||
| 215 | + init = self.public / "__init__.py" | ||
| 216 | + self.assertFalse(init.is_symlink()) | ||
| 217 | + self.assertEqual(init.read_text(), 'VALUE = "installed"\n') | ||
| 218 | + self.run_installer("--uninstall") | ||
| 219 | + self.assertFalse(self.public.exists()) | ||
| 220 | + | ||
| 156 | def test_no_bindings_preserves_unowned_empty_namespace(self): | 221 | def test_no_bindings_preserves_unowned_empty_namespace(self): |
| 157 | self.public.mkdir() | 222 | self.public.mkdir() |
| 158 | - shutil.rmtree(self.binding) | 223 | + shutil.rmtree(self.binding.parent) |
| 159 | self.run_installer() | 224 | self.run_installer() |
| 160 | self.run_installer("--uninstall") | 225 | self.run_installer("--uninstall") |
| 161 | self.assertTrue(self.public.is_dir()) | 226 | self.assertTrue(self.public.is_dir()) |
| @@ -16,7 +16,7 @@ import tempfile | |||
| 16 | import unittest | 16 | import unittest |
| 17 | 17 | ||
| 18 | ROOT = Path(__file__).resolve().parents[2] | 18 | ROOT = Path(__file__).resolve().parents[2] |
| 19 | -PACKAGE = ROOT / "torch_extension" / "pypto_gym" | 19 | +PACKAGE = ROOT / "python" / "pypto_gym" |
| 20 | 20 | ||
| 21 | 21 | ||
| 22 | class TorchBindingLazyImportTest(unittest.TestCase): | 22 | class TorchBindingLazyImportTest(unittest.TestCase): |
| @@ -26,11 +26,13 @@ class TorchBindingLazyImportTest(unittest.TestCase): | |||
| 26 | self.site = Path(self.temp.name) / "site-packages" | 26 | self.site = Path(self.temp.name) / "site-packages" |
| 27 | self.pkg = self.site / "pypto_gym" | 27 | self.pkg = self.site / "pypto_gym" |
| 28 | self.pkg.mkdir(parents=True) | 28 | self.pkg.mkdir(parents=True) |
| 29 | - for name in ("__init__.py", "_loader.py"): | 29 | + shutil.copy2(PACKAGE / "__init__.py", self.pkg / "__init__.py") |
| 30 | - shutil.copy2(PACKAGE / name, self.pkg / name) | 30 | + shutil.copytree(PACKAGE / "_loader", self.pkg / "_loader", |
| 31 | - (self.pkg / "operators.json").write_text(json.dumps(["example_op"]) + "\n") | 31 | + ignore=shutil.ignore_patterns("__pycache__")) |
| 32 | - frontends = self.pkg / "_frontends" | 32 | + bindings = self.pkg / "_bindings" |
| 33 | - frontends.mkdir() | 33 | + frontends = bindings / "frontends" |
| 34 | + frontends.mkdir(parents=True) | ||
| 35 | + (bindings / "operators.json").write_text(json.dumps(["example_op"]) + "\n") | ||
| 34 | (frontends / "example_op.py").write_text("def example_op(*args, **kwargs):\n" | 36 | (frontends / "example_op.py").write_text("def example_op(*args, **kwargs):\n" |
| 35 | " return 'loaded'\n") | 37 | " return 'loaded'\n") |
| 36 | 38 | ||
| @@ -1,62 +0,0 @@ | |||
| 1 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | -# Licensed under the CANN Open Software License Agreement Version 2.0. | ||
| 3 | - | ||
| 4 | -find_package(Python3 REQUIRED COMPONENTS Interpreter Development) | ||
| 5 | -execute_process( | ||
| 6 | - COMMAND ${Python3_EXECUTABLE} -c "import pathlib, torch_npu; print(pathlib.Path(torch_npu.__file__).parent)" | ||
| 7 | - OUTPUT_VARIABLE GYM_TORCH_NPU_ROOT OUTPUT_STRIP_TRAILING_WHITESPACE | ||
| 8 | - RESULT_VARIABLE _torch_npu_rc ERROR_QUIET) | ||
| 9 | -if(NOT _torch_npu_rc EQUAL 0) | ||
| 10 | - message(FATAL_ERROR "ENABLE_TORCH_BINDINGS requires torch_npu in ${Python3_EXECUTABLE}") | ||
| 11 | -endif() | ||
| 12 | -find_library(GYM_TORCH_NPU_LIB torch_npu PATHS "${GYM_TORCH_NPU_ROOT}/lib" NO_DEFAULT_PATH REQUIRED) | ||
| 13 | -find_library(GYM_ASCENDCL_LIB ascendcl PATHS "${ASCEND_CANN_PACKAGE_PATH}/lib64" NO_DEFAULT_PATH REQUIRED) | ||
| 14 | - | ||
| 15 | -add_library(gym_torch_common INTERFACE) | ||
| 16 | -target_include_directories(gym_torch_common INTERFACE | ||
| 17 | - ${TORCH_INCLUDE_DIRS} | ||
| 18 | - "${CMAKE_CURRENT_SOURCE_DIR}/include" | ||
| 19 | - ${Python3_INCLUDE_DIRS} | ||
| 20 | - "${GYM_TORCH_NPU_ROOT}/include" | ||
| 21 | - "${ASCEND_CANN_PACKAGE_PATH}/include") | ||
| 22 | -target_link_libraries(gym_torch_common INTERFACE | ||
| 23 | - ${TORCH_LIBRARIES} ${TORCH_PYTHON_LIB} ${GYM_TORCH_NPU_LIB} ${GYM_ASCENDCL_LIB} dl) | ||
| 24 | -separate_arguments(_gym_torch_flags NATIVE_COMMAND "${TORCH_CXX_FLAGS}") | ||
| 25 | -target_compile_options(gym_torch_common INTERFACE ${_gym_torch_flags}) | ||
| 26 | -target_compile_features(gym_torch_common INTERFACE cxx_std_17) | ||
| 27 | - | ||
| 28 | -install(DIRECTORY pypto_gym/ | ||
| 29 | - DESTINATION packages/vendors/${VENDOR_NAME}/python/pypto_gym | ||
| 30 | - COMPONENT ${VENDOR_NAME} PATTERN "__pycache__" EXCLUDE) | ||
| 31 | - | ||
| 32 | -# Called from ops/<paradigm>/<network>/<op>/torch_extension/CMakeLists.txt. | ||
| 33 | -function(gym_add_torch_binding op_name) | ||
| 34 | - add_library(torch_binding_${op_name} SHARED "${op_name}.cpp") | ||
| 35 | - target_link_libraries(torch_binding_${op_name} PRIVATE gym_torch_common) | ||
| 36 | - set_target_properties(torch_binding_${op_name} PROPERTIES | ||
| 37 | - OUTPUT_NAME pypto_gym_${op_name} | ||
| 38 | - LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/torch_extension" | ||
| 39 | - INSTALL_RPATH "$ORIGIN/../../../op_api/lib" | ||
| 40 | - INSTALL_RPATH_USE_LINK_PATH FALSE) | ||
| 41 | - install(TARGETS torch_binding_${op_name} | ||
| 42 | - LIBRARY DESTINATION packages/vendors/${VENDOR_NAME}/python/pypto_gym/_native | ||
| 43 | - COMPONENT ${VENDOR_NAME}) | ||
| 44 | - install(FILES "${op_name}.py" | ||
| 45 | - DESTINATION packages/vendors/${VENDOR_NAME}/python/pypto_gym/_frontends | ||
| 46 | - COMPONENT ${VENDOR_NAME}) | ||
| 47 | - set_property(GLOBAL APPEND PROPERTY GYM_TORCH_OPS ${op_name}) | ||
| 48 | -endfunction() | ||
| 49 | - | ||
| 50 | -function(gym_finalize_torch_bindings) | ||
| 51 | - get_property(_ops GLOBAL PROPERTY GYM_TORCH_OPS) | ||
| 52 | - if(NOT _ops) | ||
| 53 | - message(FATAL_ERROR "None of the selected operators provide a Torch binding") | ||
| 54 | - endif() | ||
| 55 | - list(REMOVE_DUPLICATES _ops) | ||
| 56 | - list(JOIN _ops "\", \"" _ops_json) | ||
| 57 | - file(WRITE "${CMAKE_BINARY_DIR}/torch_extension/operators.json" "[\"${_ops_json}\"]\n") | ||
| 58 | - install(FILES "${CMAKE_BINARY_DIR}/torch_extension/operators.json" | ||
| 59 | - DESTINATION packages/vendors/${VENDOR_NAME}/python/pypto_gym | ||
| 60 | - COMPONENT ${VENDOR_NAME}) | ||
| 61 | - message(STATUS "Precompiled Torch bindings: ${_ops}") | ||
| 62 | -endfunction() | ||
| @@ -1,349 +0,0 @@ | |||
| 1 | -# PyPTO-Gym Torch 绑定 | ||
| 2 | - | ||
| 3 | -Torch 绑定使用已安装的 ACLNN 算子库,在当前 NPU stream 上执行预编译 kernel。 | ||
| 4 | -C++ 绑定也在构建期编译并随 `.run` 交付;运行时加载 `.so`,无需编译器或 | ||
| 5 | -PyPTO Python 包。当前已接入 `mega_mhc`、`atten_epilogue` 和 | ||
| 6 | -`quant_sparse_lightning_indexer`。 | ||
| 7 | - | ||
| 8 | -## 构建和安装 | ||
| 9 | - | ||
| 10 | -构建环境需要 CANN、PyPTO-pro、torch、torch_npu 和 PyYAML(读取发布清单)。执行: | ||
| 11 | - | ||
| 12 | -```bash | ||
| 13 | -python3 build_ci.py --pkg-type run --ops mega_mhc --soc ascend950 | ||
| 14 | -bash build_out/run/ascend950/cann-950-pypto_gym_*.run --install-path="$ASCEND_HOME_PATH/opp" | ||
| 15 | -``` | ||
| 16 | - | ||
| 17 | -`.run` 默认附带预编译 Torch 绑定,对应 `-DENABLE_TORCH_BINDINGS=ON`, | ||
| 18 | -无需额外传入 `--torch-bindings`。仅需 ACLNN 接口时,使用 `--no-torch-bindings` | ||
| 19 | -(手工 CMake 使用 `-DENABLE_TORCH_BINDINGS=OFF`)。`whl` 构建不启用此绑定。 | ||
| 20 | -部署环境需要与构建环境兼容的 Python、torch、torch_npu 和 CANN。 | ||
| 21 | -在已加载目标 CANN 基础环境的终端中,安装到其 `opp` 后即可直接导入, | ||
| 22 | -无需额外 source vendor 的 `set_env.bash`。安装器在 CANN 的 `python/site-packages` | ||
| 23 | -中登记指向 vendor 私有文件的相对链接;绑定通过相对运行时库路径加载同一 vendor 的 ACLNN 库。 | ||
| 24 | -升级、卸载只维护本包创建的链接,保留已有 kernel wheel 的 `ops` 目录; | ||
| 25 | -若入口已由其他 Python 包占用,安装会报错而不覆盖。 | ||
| 26 | - | ||
| 27 | -安装到非 CANN 的独立目录时,仍可 source `<opp>/vendors/pypto_gym/bin/set_env.bash` | ||
| 28 | -配置该自定义位置的搜索路径。新终端需要加载 CANN 基础环境。 | ||
| 29 | - | ||
| 30 | -```python | ||
| 31 | -import torch | ||
| 32 | -import pypto_gym | ||
| 33 | - | ||
| 34 | -# 九个输入 tensor 均位于同一 NPU;形状和类型见算子 README。 | ||
| 35 | -outputs = pypto_gym.mega_mhc(*inputs) | ||
| 36 | -# 直接通过 Torch dispatcher 调用前,先显式加载绑定;batch=0 表示自动配置。 | ||
| 37 | -pypto_gym.load() | ||
| 38 | -outputs = torch.ops.pypto_gym.mega_mhc(*inputs, batch=0) | ||
| 39 | -``` | ||
| 40 | - | ||
| 41 | -`import pypto_gym` 是惰性的:不会导入 torch/torch_npu,也不会加载绑定库。访问 | ||
| 42 | -`pypto_gym.mega_mhc` 会在首次调用时加载;直接使用 `torch.ops.pypto_gym.*` 前需先 | ||
| 43 | -调用 `pypto_gym.load()`(或先访问任一 `pypto_gym.<op>`)。因此缺少 torch 或绑定 | ||
| 44 | -ABI 不兼容时,`import pypto_gym` 仍然成功。 | ||
| 45 | - | ||
| 46 | -`pypto_gym.mega_mhc` 支持 `batch=None/16` 和六个运行时标量,五个输出由绑定 | ||
| 47 | -内部申请并以返回值形式返回。功能入口注册了 `PrivateUse1` 和 `Meta`,支持 FakeTensor | ||
| 48 | -和符号 token 维度的输出推导。当前提供 forward 计算,不提供 autograd backward。 | ||
| 49 | - | ||
| 50 | -## 测试 | ||
| 51 | - | ||
| 52 | -```bash | ||
| 53 | -# 构建、隔离安装到 build_out,并通过正式 Torch 入口运行测试。 | ||
| 54 | -python3 build_ci.py --pkg-type run --ops mega_mhc --stest | ||
| 55 | -# 已安装到当前 CANN 时,无需额外 source vendor 脚本: | ||
| 56 | -pytest ops/pro/deepseek_v4_1/mega_mhc/tests -q | ||
| 57 | -``` | ||
| 58 | - | ||
| 59 | -`mega_mhc` 的 24 项完整算子用例中,12 项直接调用 `pypto_gym.mega_mhc`, | ||
| 60 | -12 项直接调用 `torch.ops.pypto_gym.mega_mhc`,每项只执行一次算子,输出由绑定内部申请。 | ||
| 61 | -测试校验五输出数值精度、只读输入和输入内存 guard;入口不受 `--mode` 参数控制。 | ||
| 62 | -用例清单见算子 README。 | ||
| 63 | - | ||
| 64 | -另有一项存储格式边界用例,验证 NZ 输入会在进入异步队列前被拒绝。 | ||
| 65 | -绑定读取真实存储格式元数据,不做隐式格式转换或 NPU 同步。 | ||
| 66 | - | ||
| 67 | -## 多算子构建到同一个包 | ||
| 68 | - | ||
| 69 | -`.run` 的 `ALL`(包括省略 `--ops`)由 | ||
| 70 | -[ops/pro/build_ops.yaml](../ops/pro/build_ops.yaml) 控制,使用 YAML 列表,路径相对于 `ops/pro`: | ||
| 71 | - | ||
| 72 | -```yaml | ||
| 73 | -- deepseek_v4_1/mega_mhc | ||
| 74 | -``` | ||
| 75 | - | ||
| 76 | -当前清单仅列出 `mega_mhc`。文件中列出的路径参与构建,未列出的路径不参与。 | ||
| 77 | -空行、以 `#` 开头的注释及行尾 `#` 注释会被忽略。 | ||
| 78 | -新增算子需要把完整相对路径加入清单;不想构建某个算子时,注释掉对应行即可。 | ||
| 79 | -例如,接入新算子 `example_op` 后可加入第二行,再按需注释: | ||
| 80 | - | ||
| 81 | -```yaml | ||
| 82 | -- deepseek_v4_1/mega_mhc | ||
| 83 | -# - experimental/example_op | ||
| 84 | -``` | ||
| 85 | - | ||
| 86 | -上述清单的 `ALL` 只构建 `deepseek_v4_1/mega_mhc`;取消第二行的注释后包含 | ||
| 87 | -两个算子。`example_op` 是占位名称,启用前需完成实际算子的二进制接入。 | ||
| 88 | - | ||
| 89 | -列出的目录需满足二进制构建约定:位于规定的目录深度内,并同时具备算子级 | ||
| 90 | -`CMakeLists.txt` 和 `op_host/`。路径按完整目录匹配,实际算子名取目录末级名称, | ||
| 91 | -同一个包中的算子名必须唯一。清单需至少列出一个有效目录;文件缺失、路径错误或 | ||
| 92 | -全部被注释时构建报错。 | ||
| 93 | - | ||
| 94 | -显式 `--ops mega_mhc,example_op` 仍按算子目录名选择,绕过此清单, | ||
| 95 | -也可显式选择未列入清单的算子。显式选择的候选范围包括 `ops/pro/` 和 | ||
| 96 | -`ops/tensor/` 下已接入二进制构建的算子;清单的相对路径基准固定为 `ops/pro/`。 | ||
| 97 | -`whl` 的 `ALL` 保持原有发现范围,不使用这份 `.run` 发布清单。 | ||
| 98 | - | ||
| 99 | -CMake 构建和 `--stest` 共用同一份解析逻辑;CMake 会跟踪清单变化并重新配置。 | ||
| 100 | -`operators.json` 是构建生成的 Torch 绑定名单,不作为发布范围的配置入口。 | ||
| 101 | - | ||
| 102 | -`--ops` 支持逗号分隔的算子目录名。同一 SoC、同一次构建选择的所有算子会进入 | ||
| 103 | -同一个 `.run` 包。例如,完成 `example_op` 接入后,与 `mega_mhc` 一起交付: | ||
| 104 | - | ||
| 105 | -```bash | ||
| 106 | -python3 build_ci.py --pkg-type run --soc ascend950 \ | ||
| 107 | - --ops mega_mhc,example_op | ||
| 108 | -``` | ||
| 109 | - | ||
| 110 | -命令中的逗号两侧不要加空格,整个名单作为一个参数传入。名单填写算子目录名, | ||
| 111 | -例如 `mega_mhc`,而不是 C++ 类型名 `MegaMhc` 或 ACLNN 函数名。 | ||
| 112 | - | ||
| 113 | -| 选择方式 | 构建范围 | | ||
| 114 | -| --------------------------------- | ------------------------------------------------------- | | ||
| 115 | -| `--ops mega_mhc` | 单个算子 | | ||
| 116 | -| `--ops mega_mhc,example_op` | 指定的多个算子,共用一个包 | | ||
| 117 | -| `--ops ALL`,或省略 `--ops` | `.run` 仅构建 `ops/pro/build_ops.yaml` 中列出的目录 | | ||
| 118 | - | ||
| 119 | -`.run` 默认附带预编译 Torch 绑定,`--no-torch-bindings` 可显式关闭。 | ||
| 120 | -算子是否进入包和是否提供 Torch 入口是两件事: | ||
| 121 | - | ||
| 122 | -- 所选算子的 host、ACLNN 和 kernel 产物一起打包。 | ||
| 123 | -- 其中已接入 `torch_extension/` 的算子,额外打包各自的绑定 `.so` 和 Python 前端。 | ||
| 124 | -- 当前 `mega_mhc`、`atten_epilogue`、`quant_sparse_lightning_indexer` 已接入绑定, | ||
| 125 | - 各自提供 `pypto_gym.<op>` 和对应的 `torch.ops` 入口。 | ||
| 126 | - 新增算子仍需完成绑定接入,构建不会从 kernel 源码自动生成 Torch 参数接口。 | ||
| 127 | -- `run` 默认尝试启用绑定;若所选算子都没有接入绑定,会自动降级为 ACLNN-only 包并打印 | ||
| 128 | - WARNING,原有 ACLNN 调用/测试方式不受影响。显式传 `--torch-bindings` 时,所选算子中 | ||
| 129 | - 至少要有一个提供绑定,否则 CMake 会报错。也可用 `--no-torch-bindings` 强制 ACLNN-only。 | ||
| 130 | - | ||
| 131 | -输出目录为 `build_out/run/ascend950/`。包名按 SoC、vendor、版本和架构生成, | ||
| 132 | -不包含算子名单。例如,x86_64 环境下生成 | ||
| 133 | -`cann-950-pypto_gym_9.2.0_linux-x86_64.run`,它可以同时包含多个算子。 | ||
| 134 | -要交付一个包含多个算子的包,应在一次命令中指定完整名单;分次构建单算子不会自动 | ||
| 135 | -把前后两次产物合并,且可能使用相同的包名。 | ||
| 136 | - | ||
| 137 | -按发布清单构建并验证当前列出的算子: | ||
| 138 | - | ||
| 139 | -```bash | ||
| 140 | -python3 build_ci.py --pkg-type run --soc ascend950 \ | ||
| 141 | - --ops ALL --stest --jobs 8 | ||
| 142 | -``` | ||
| 143 | - | ||
| 144 | -`--stest` 可用于构建后验证:构建脚本按 `operators.json` 将已有绑定的算子交给 | ||
| 145 | -Torch 测试,将其余算子交给 ACLNN 测试桥;后者需要相应的测试桥和用例。 | ||
| 146 | -`mega_mhc` 的用例已直接固定使用两个正式接口,不再依赖测试入口分发函数。 | ||
| 147 | - | ||
| 148 | -## 新算子接入 | ||
| 149 | - | ||
| 150 | -本章使用 `outputs = torch.ops.pypto_gym.example_op(*inputs)` 的普通函数接口, | ||
| 151 | -输出由 C++ 绑定内部分配。 | ||
| 152 | - | ||
| 153 | -以下以 `example_op` 为占位名称;实际接入时替换为真实算子目录名。 | ||
| 154 | -可对照完整实现 [mega_mhc/torch_extension](../ops/pro/deepseek_v4_1/mega_mhc/torch_extension/)。 | ||
| 155 | -公共构建逻辑位于 [CMakeLists.txt](CMakeLists.txt),ACLNN 调用辅助代码位于 | ||
| 156 | -[include/gym_aclnn.h](include/gym_aclnn.h)。 | ||
| 157 | - | ||
| 158 | -### 1. 先具备算子的二进制构建能力 | ||
| 159 | - | ||
| 160 | -Torch 绑定建立在可独立交付的 ACLNN 算子之上。算子需要先接入仓库的 host、kernel | ||
| 161 | -构建流程,能通过 `--pkg-type run --ops example_op --no-torch-bindings` 生成 | ||
| 162 | -ACLNN 二进制产物;完成下面的 Torch 接入后,构建时使用默认开启的绑定。 | ||
| 163 | -算子目录至少应有算子级 `CMakeLists.txt` 和 `op_host/`,以便构建系统发现。 | ||
| 164 | -host、kernel 的基础接入流程见 [构建指南](../docs/build-guide.md)。 | ||
| 165 | - | ||
| 166 | -接入前明确以下接口约定,并在算子 README 中写清楚: | ||
| 167 | - | ||
| 168 | -- 输入和输出的顺序、shape、dtype、layout、设备及连续性要求。 | ||
| 169 | -- 标量参数的类型、默认值、取值范围,以及空输入的行为。 | ||
| 170 | -- ACLNN 函数名、完整函数签名、输出分配规则和是否支持预分配输出。 | ||
| 171 | -- 是否提供反向计算;只有 forward 的算子应明确限制需要梯度的调用。 | ||
| 172 | - | ||
| 173 | -Torch schema、C++ 函数、Python 前端与 ACLNN 的参数映射必须保持一致。 | ||
| 174 | -ACLNN 签名以该算子构建生成的头文件为准,不要只替换其他算子的函数名。 | ||
| 175 | - | ||
| 176 | -### 2. 增加目录和 CMake 登记 | ||
| 177 | - | ||
| 178 | -在算子目录增加以下三个文件: | ||
| 179 | - | ||
| 180 | -```text | ||
| 181 | -ops/pro/experimental/example_op/ | ||
| 182 | -├── CMakeLists.txt | ||
| 183 | -├── op_host/ | ||
| 184 | -├── op_kernel/ | ||
| 185 | -├── tests/ | ||
| 186 | -└── torch_extension/ | ||
| 187 | - ├── CMakeLists.txt | ||
| 188 | - ├── example_op.cpp | ||
| 189 | - └── example_op.py | ||
| 190 | -``` | ||
| 191 | - | ||
| 192 | -`torch_extension/CMakeLists.txt` 内容为: | ||
| 193 | - | ||
| 194 | -```cmake | ||
| 195 | -if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) | ||
| 196 | - gym_add_torch_binding(example_op) | ||
| 197 | -endif() | ||
| 198 | -``` | ||
| 199 | - | ||
| 200 | -算子级 `CMakeLists.txt` 必须派发到这个子目录。若像 `mega_mhc` 一样已自动遍历 | ||
| 201 | -带 `CMakeLists.txt` 的子目录,无需额外添加;若采用显式派发,则在算子级增加: | ||
| 202 | - | ||
| 203 | -```cmake | ||
| 204 | -if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) | ||
| 205 | - add_subdirectory(torch_extension) | ||
| 206 | -endif() | ||
| 207 | -``` | ||
| 208 | - | ||
| 209 | -两种派发方式选一种,避免重复添加子目录。绑定登记放在 | ||
| 210 | -`torch_extension/CMakeLists.txt` 中,文件名须与 `gym_add_torch_binding()` 的参数一致。 | ||
| 211 | - | ||
| 212 | -公共构建函数会自动完成以下工作: | ||
| 213 | - | ||
| 214 | -1. 创建 `torch_binding_example_op` 共享库目标,并链接公共 Torch、torch_npu、CANN 依赖。 | ||
| 215 | -2. 生成 `libpypto_gym_example_op.so`,安装到包内的 `_native/`。 | ||
| 216 | -3. 将 `example_op.py` 安装到 `_frontends/`。 | ||
| 217 | -4. 把 `example_op` 加入本次构建的全局绑定名单。 | ||
| 218 | - | ||
| 219 | -根构建流程在所有所选算子登记完成后,统一生成 `operators.json`。 | ||
| 220 | -新增算子无需修改公共加载器或手动维护这个 JSON。 | ||
| 221 | - | ||
| 222 | -### 3. 实现 C++ Torch 注册和 ACLNN 调用 | ||
| 223 | - | ||
| 224 | -`example_op.cpp` 负责将 Torch Tensor 转接到该算子的 ACLNN 接口。 | ||
| 225 | -可参考 [mega_mhc.cpp](../ops/pro/deepseek_v4_1/mega_mhc/torch_extension/mega_mhc.cpp)。 | ||
| 226 | - | ||
| 227 | -下面仅展示一个单输入、单输出算子的注册部分;`ExampleOpNpu` 和 `ExampleOpMeta` | ||
| 228 | -须在同一文件中按真实计算和输出规则实现: | ||
| 229 | - | ||
| 230 | -```cpp | ||
| 231 | -#include "gym_aclnn.h" | ||
| 232 | -#include <ATen/ATen.h> | ||
| 233 | -#include <torch/library.h> | ||
| 234 | - | ||
| 235 | -// 具体实现略:NPU 函数执行 ACLNN,Meta 函数只推导输出。 | ||
| 236 | -at::Tensor ExampleOpNpu(const at::Tensor &x); | ||
| 237 | -at::Tensor ExampleOpMeta(const at::Tensor &x); | ||
| 238 | - | ||
| 239 | -TORCH_LIBRARY_FRAGMENT(pypto_gym, m) { | ||
| 240 | - m.def("example_op(Tensor x) -> Tensor"); | ||
| 241 | -} | ||
| 242 | -TORCH_LIBRARY_IMPL(pypto_gym, PrivateUse1, m) { | ||
| 243 | - m.impl("example_op", TORCH_FN(ExampleOpNpu)); | ||
| 244 | -} | ||
| 245 | -TORCH_LIBRARY_IMPL(pypto_gym, Meta, m) { | ||
| 246 | - m.impl("example_op", TORCH_FN(ExampleOpMeta)); | ||
| 247 | -} | ||
| 248 | -``` | ||
| 249 | - | ||
| 250 | -同一个包中的所有算子共用 `pypto_gym` 命名空间,因此使用 | ||
| 251 | -`TORCH_LIBRARY_FRAGMENT` 分别声明各自 schema,避免重复定义命名空间。 | ||
| 252 | -schema 中的 Tensor、标量、默认值和返回值必须与 C++ 函数签名匹配。 | ||
| 253 | - | ||
| 254 | -NPU 实现按以下顺序处理: | ||
| 255 | - | ||
| 256 | -1. 校验输入设备、shape、dtype、连续性、真实存储格式和标量范围,设置正确的 device guard。 | ||
| 257 | - ND 算子调用 `gym_torch::CheckNDStorage(tensor, name)`;逻辑连续性不足以判断物理格式。 | ||
| 258 | -2. 在调用线程分配输出;若支持预分配输出,校验输出规格、真实存储格式和输入输出之间的重叠。 | ||
| 259 | - 支持空输入时按算子约定返回正确形状的空输出。 | ||
| 260 | -3. 用 `gym_torch::Symbol<函数指针类型>()` 解析该算子的 | ||
| 261 | - `aclnnExampleOpGetWorkspaceSize` 和 `aclnnExampleOp`;函数指针类型与生成头文件一致。 | ||
| 262 | -4. 将参与计算的输入、输出 Tensor 列表交给 `gym_torch::Enqueue()`。 | ||
| 263 | - 回调接收 Tensor 元数据,通过 `gym_torch::Tensor()` 构造 ACL Tensor 描述符。 | ||
| 264 | -5. 在回调中调用 `GetWorkspaceSize` 获取 workspace 大小和 executor,检查返回码后, | ||
| 265 | - 调用 `gym_torch::ExecuteOp()` 在当前 NPU stream 执行算子。 | ||
| 266 | - | ||
| 267 | -复用公共辅助函数的 stream 记录和 workspace 管理。队列回调只捕获标量等 host 数据, | ||
| 268 | -不要捕获 `at::Tensor`,也不要在回调中用 `at::empty` 创建 workspace Tensor; | ||
| 269 | -这些操作可能在资源释放时重新进入任务队列。算子正常调用保持异步,数值测试需要时 | ||
| 270 | -再执行 `torch.npu.synchronize()`。 | ||
| 271 | - | ||
| 272 | -`Meta` 实现只根据输入元数据和属性创建输出,不分配 NPU workspace、不执行 ACLNN。 | ||
| 273 | -若需要动态 shape,应使用符号维度推导接口。 | ||
| 274 | - | ||
| 275 | -### 4. 导出 Python 便捷入口 | ||
| 276 | - | ||
| 277 | -`example_op.py` 中必须提供与算子同名的可调用函数。对于上面的单输入示例: | ||
| 278 | - | ||
| 279 | -```python | ||
| 280 | -import torch | ||
| 281 | - | ||
| 282 | - | ||
| 283 | -def example_op(x): | ||
| 284 | - return torch.ops.pypto_gym.example_op(x) | ||
| 285 | -``` | ||
| 286 | - | ||
| 287 | -这里可以补充 Python 参数校验、默认值转换和 `out` 参数展开;C++ 入口仍需保留 | ||
| 288 | -必要校验,因为用户也可以直接调用 `torch.ops`。Python 前端负责参数处理和转发, | ||
| 289 | -计算交给预编译绑定;无需导入 `op_kernel` 或使用运行时扩展编译。 | ||
| 290 | - | ||
| 291 | -`import pypto_gym` 只读取绑定清单,不加载绑定库;`pypto_gym.example_op` 在首次 | ||
| 292 | -访问时按需加载对应 `.so` 并完成 Torch 算子注册。两种入口都可使用: | ||
| 293 | - | ||
| 294 | -```python | ||
| 295 | -import torch | ||
| 296 | -import pypto_gym | ||
| 297 | - | ||
| 298 | -result = pypto_gym.example_op(x) # 首次访问时加载 example_op 绑定。 | ||
| 299 | -# 直接调用 Torch 算子前,先显式加载(或先访问 pypto_gym.example_op): | ||
| 300 | -pypto_gym.load() | ||
| 301 | -result = torch.ops.pypto_gym.example_op(x) | ||
| 302 | -``` | ||
| 303 | - | ||
| 304 | -### 5. 与已有算子一起构建、安装和验收 | ||
| 305 | - | ||
| 306 | -完成上述接入后,在一次构建中选择两个算子: | ||
| 307 | - | ||
| 308 | -```bash | ||
| 309 | -# example_op 为占位名称,须先完成实现再执行。 | ||
| 310 | -python3 build_ci.py --pkg-type run --soc ascend950 \ | ||
| 311 | - --ops mega_mhc,example_op --stest | ||
| 312 | -``` | ||
| 313 | - | ||
| 314 | -`--stest` 要求新算子具备可运行的测试。测试可直接使用上述任一正式接口,每个 | ||
| 315 | -shape 或边界用例选择一个入口,比较完整输出与 golden。需要看护两种入口时, | ||
| 316 | -将不同用例分配给两个入口,避免为了切换入口重复执行相同的算子场景。 | ||
| 317 | - | ||
| 318 | -在与构建环境 ABI 兼容、已加载 CANN 基础环境的终端中,将本次生成的 `.run` | ||
| 319 | -安装到 `$ASCEND_HOME_PATH/opp`,即可直接导入。vendor 内的文件结构如下 | ||
| 320 | -(省略其他 host、kernel 产物): | ||
| 321 | - | ||
| 322 | -```text | ||
| 323 | -<install-path>/vendors/pypto_gym/ | ||
| 324 | -├── op_api/lib/libcust_opapi.so | ||
| 325 | -└── python/pypto_gym/ | ||
| 326 | - ├── __init__.py | ||
| 327 | - ├── _loader.py | ||
| 328 | - ├── operators.json # 包含 mega_mhc 和 example_op | ||
| 329 | - ├── _native/ | ||
| 330 | - │ ├── libpypto_gym_mega_mhc.so | ||
| 331 | - │ └── libpypto_gym_example_op.so | ||
| 332 | - └── _frontends/ | ||
| 333 | - ├── mega_mhc.py | ||
| 334 | - └── example_op.py | ||
| 335 | -``` | ||
| 336 | - | ||
| 337 | -标准 CANN 安装还会在 `$ASCEND_HOME_PATH/python/site-packages/pypto_gym/` 中 | ||
| 338 | -创建 `__init__.py`、`_loader.py`、`_native`、`_frontends`、`operators.json` | ||
| 339 | -这五个相对链接,目标均指向上述 vendor 私有目录。 | ||
| 340 | - | ||
| 341 | -构建期应看到 `Precompiled Torch bindings:` 列出两个算子;安装后可确认: | ||
| 342 | - | ||
| 343 | -```bash | ||
| 344 | -cat "$ASCEND_HOME_PATH/opp/vendors/pypto_gym/python/pypto_gym/operators.json" | ||
| 345 | -``` | ||
| 346 | - | ||
| 347 | -随后在新 Python 进程中 `import pypto_gym`,使用对应输入调用两个算子的正式接口。 | ||
| 348 | -仅出现在 `--ops` 中还不足以提供 Torch 入口;还必须完成绑定的 CMake 登记、 | ||
| 349 | -C++ 注册和同名 Python 前端导出。 | ||
| @@ -1,65 +0,0 @@ | |||
| 1 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | -# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | -# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | -# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | -# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | -"""Torch interfaces backed by the installed PyPTO-Gym ACLNN binaries. | ||
| 10 | - | ||
| 11 | -Importing this package is cheap and does not require torch. Bindings are loaded | ||
| 12 | -on first attribute access, or explicitly through :func:`load`. This keeps the | ||
| 13 | -namespace importable from tooling that does not have torch/torch_npu installed. | ||
| 14 | -""" | ||
| 15 | -import pkgutil | ||
| 16 | - | ||
| 17 | -from ._loader import binding_names as _binding_names | ||
| 18 | - | ||
| 19 | -# Allow the optional kernel wheel's pypto_gym.ops namespace to coexist. The | ||
| 20 | -# attribute is updated through globals() because assigning to a dunder name | ||
| 21 | -# directly is discouraged by the code checker; the effect is identical. | ||
| 22 | -globals()['__path__'] = pkgutil.extend_path(globals()['__path__'], __name__) | ||
| 23 | - | ||
| 24 | -try: | ||
| 25 | - __all__ = list(_binding_names()) | ||
| 26 | -except ImportError: | ||
| 27 | - # Bindings are not installed (for example an ACLNN-only .run). | ||
| 28 | - __all__ = [] | ||
| 29 | - | ||
| 30 | - | ||
| 31 | -def load(op=None): | ||
| 32 | - """Load installed bindings and return the loaded operator names. | ||
| 33 | - | ||
| 34 | - Accessing ``pypto_gym.<op>`` loads lazily; call this before using | ||
| 35 | - ``torch.ops.pypto_gym.<op>`` directly. | ||
| 36 | - """ | ||
| 37 | - from ._loader import binding_names, load_binding | ||
| 38 | - | ||
| 39 | - if op is None: | ||
| 40 | - names = list(binding_names()) | ||
| 41 | - for name in names: | ||
| 42 | - load_binding(name) | ||
| 43 | - return names | ||
| 44 | - if not isinstance(op, str): | ||
| 45 | - raise TypeError('operator name must be a string') | ||
| 46 | - load_binding(op) | ||
| 47 | - return [op] | ||
| 48 | - | ||
| 49 | - | ||
| 50 | -def __getattr__(name): | ||
| 51 | - if name.startswith('_'): | ||
| 52 | - raise AttributeError(name) | ||
| 53 | - from ._loader import binding_names, load_binding | ||
| 54 | - | ||
| 55 | - try: | ||
| 56 | - names = binding_names() | ||
| 57 | - except ImportError as error: | ||
| 58 | - raise AttributeError(str(error)) from error | ||
| 59 | - if name not in names: | ||
| 60 | - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") | ||
| 61 | - return load_binding(name) | ||
| 62 | - | ||
| 63 | - | ||
| 64 | -def __dir__(): | ||
| 65 | - return sorted(set(globals()) | set(__all__)) | ||