Merged
feat(build): Support build in whl/run pkg. #884
杨旭Add on Oct 26
feat(build): Support build in whl/run pkg. #884
Merged
Merged fromDCGDDD/pypto-gymmasterintocann/pypto-gymmaster
Total: 47 files changed+13776-41
| @@ -43,6 +43,8 @@ htmlcov/ | |||
| 43 | *_inputs.txt | 43 | *_inputs.txt |
| 44 | 44 | ||
| 45 | # Build outputs | 45 | # Build outputs |
| 46 | +build/ | ||
| 47 | +build_out/ | ||
| 46 | output/ | 48 | output/ |
| 47 | output_fwd/ | 49 | output_fwd/ |
| 48 | output_bwd/ | 50 | output_bwd/ |
| @@ -50,6 +52,9 @@ PROF_*/ | |||
| 50 | *.o | 52 | *.o |
| 51 | *.bin | 53 | *.bin |
| 52 | *.s | 54 | *.s |
| 55 | + | ||
| 56 | +# makeself runtime dependencies downloaded during packaging (cann-cmake makeself-fetch) | ||
| 57 | +third_party/ | ||
| 53 | *.a | 58 | *.a |
| 54 | kernel_aicore | 59 | kernel_aicore |
| 55 | kernel_aicpu | 60 | kernel_aicpu |
| @@ -0,0 +1,121 @@ | |||
| 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 | +cmake_minimum_required(VERSION 3.18.4) | ||
| 12 | + | ||
| 13 | +# 必须在 project() 命令之前执行 | ||
| 14 | +include(cmake/prepare_3rd.cmake) | ||
| 15 | + | ||
| 16 | +project(pypto_gym | ||
| 17 | + LANGUAGES C CXX | ||
| 18 | + VERSION 1.0.0 | ||
| 19 | +) | ||
| 20 | +init_cann_project() | ||
| 21 | +add_cann_target_options() | ||
| 22 | + | ||
| 23 | +######################################################################################################################## | ||
| 24 | +# 基础配置 | ||
| 25 | +######################################################################################################################## | ||
| 26 | + | ||
| 27 | +# 常量 | ||
| 28 | +set(VENDOR_NAME "pypto_gym" CACHE STRING "vendor name, installed under opp/vendors/<name>") | ||
| 29 | + | ||
| 30 | +# 路径配置 | ||
| 31 | +get_filename_component(PYPTO_GYM_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}" REALPATH) | ||
| 32 | + | ||
| 33 | +# 公开编译开关(build) | ||
| 34 | +set(ASCEND_COMPUTE_UNIT "ascend950" CACHE STRING "soc that need to be compiled") | ||
| 35 | +set(ASCEND_OP_NAME "ALL" CACHE STRING "operators that need to be compiled") | ||
| 36 | +set(PACKAGE_TYPE "run" CACHE STRING "package type: run") | ||
| 37 | +option(ENABLE_OPS_HOST "Build ops host." ON) | ||
| 38 | +option(ENABLE_OPS_KERNEL "Build ops kernel." ON) | ||
| 39 | +option(ENABLE_ASAN "Enable AddressSanitizer (host side)." OFF) | ||
| 40 | +option(ENABLE_UBSAN "Enable UndefinedBehaviorSanitizer (host side)." OFF) | ||
| 41 | + | ||
| 42 | +# 公开编译开关(tests) | ||
| 43 | +# 算子级 dispatcher 据此派发 tests/ 目录; 亦为 config.cmake 预留 XSAN 块的激活条件 | ||
| 44 | +option(ENABLE_TESTS_EXECUTE "Enable auto execute tests executable" OFF) | ||
| 45 | + | ||
| 46 | +# 流程控制开关(内部机制, 由 prepare.sh 以 -DPREPARE_BUILD=ON 驱动; 手工/CLion 入口保持 OFF) | ||
| 47 | +option(PREPARE_BUILD "Prepare build (second pass)." OFF) | ||
| 48 | + | ||
| 49 | +# 缺省编译配置, 编译函数, 反射载体 stub | ||
| 50 | +include(cmake/config.cmake) | ||
| 51 | +include(cmake/func.cmake) | ||
| 52 | +include(cmake/obj_func.cmake) | ||
| 53 | + | ||
| 54 | +######################################################################################################################## | ||
| 55 | +# 编译流程 | ||
| 56 | +######################################################################################################################## | ||
| 57 | + | ||
| 58 | +# 算子接入: 发现 ops/{pro,tensor} 树, add 算子级目录(dispatcher 派发 op_host/tests). | ||
| 59 | +# 算子侧只做"申报"(宏登记源到全局属性), 目标创建在接入后的 custom_build.cmake 读回完成. | ||
| 60 | +gym_op_discovery(OP_LIST OP_DIR_LIST) | ||
| 61 | +foreach(_op_dir ${OP_DIR_LIST}) | ||
| 62 | + add_subdirectory(${_op_dir}) | ||
| 63 | +endforeach() | ||
| 64 | + | ||
| 65 | +# 读回算子登记, 创建 host 侧目标(三 .so/核对程序)与 kernel 编译链 | ||
| 66 | +include(cmake/custom_build.cmake) # TODO 看看能不能去掉 | ||
| 67 | + | ||
| 68 | +######################################################################################################################## | ||
| 69 | +# 打包(cann-cmake + makeself) | ||
| 70 | +# 组件/版本定义 -> version.<pkg>.info 生成 -> 脚本骨架安装 -> CPack External 配置(package 目标产出 .run) | ||
| 71 | +# COMPUTE_UNIT 传入后 .run 名带 chip(如 cann-950-pypto_gym_9.2.0_linux-aarch64.run), | ||
| 72 | +# 多 soc 轮次(build_ci.py 按 soc 循环、build/<soc> 隔离)产物互不冲突 | ||
| 73 | +######################################################################################################################## | ||
| 74 | +include(version.cmake) | ||
| 75 | +add_cann_version_info_targets() | ||
| 76 | + | ||
| 77 | +# run 包脚本骨架安装: install.sh 入口 + help/cleanup + version.info. | ||
| 78 | +# 组件名与 install COMPONENT 一致(set_cann_cpack_config 按组件收集 staging). | ||
| 79 | +set(_GymScriptPrefix "${PYPTO_GYM_SRC_DIR}/scripts/package/${VENDOR_NAME}/scripts") | ||
| 80 | +install(DIRECTORY "${_GymScriptPrefix}/" | ||
| 81 | + DESTINATION share/info/${VENDOR_NAME}/script | ||
| 82 | + FILE_PERMISSIONS | ||
| 83 | + OWNER_READ OWNER_WRITE OWNER_EXECUTE # 文件权限 | ||
| 84 | + GROUP_READ GROUP_EXECUTE | ||
| 85 | + WORLD_READ WORLD_EXECUTE | ||
| 86 | + DIRECTORY_PERMISSIONS | ||
| 87 | + OWNER_READ OWNER_WRITE OWNER_EXECUTE # 目录权限 | ||
| 88 | + GROUP_READ GROUP_EXECUTE | ||
| 89 | + WORLD_READ WORLD_EXECUTE | ||
| 90 | + COMPONENT ${VENDOR_NAME} | ||
| 91 | +) | ||
| 92 | + | ||
| 93 | +# cann-cmake 公共脚本 | ||
| 94 | +set(SCRIPTS_FILES | ||
| 95 | + ${CANN_CMAKE_DIR}/scripts/install/check_version_required.awk | ||
| 96 | + ${CANN_CMAKE_DIR}/scripts/install/common_func_v2.inc | ||
| 97 | + ${CANN_CMAKE_DIR}/scripts/install/common_func.inc | ||
| 98 | + ${CANN_CMAKE_DIR}/scripts/install/common_installer.inc | ||
| 99 | + ${CANN_CMAKE_DIR}/scripts/install/common_interface.csh | ||
| 100 | + ${CANN_CMAKE_DIR}/scripts/install/common_interface.fish | ||
| 101 | + ${CANN_CMAKE_DIR}/scripts/install/common_interface.sh | ||
| 102 | + ${CANN_CMAKE_DIR}/scripts/install/install_common_parser.sh | ||
| 103 | + ${CANN_CMAKE_DIR}/scripts/install/multi_version.inc | ||
| 104 | + ${CANN_CMAKE_DIR}/scripts/install/script_operator.inc | ||
| 105 | + ${CANN_CMAKE_DIR}/scripts/install/version_cfg.inc | ||
| 106 | + ${CANN_CMAKE_DIR}/scripts/install/version_compatiable.inc | ||
| 107 | +) | ||
| 108 | +install(FILES ${SCRIPTS_FILES} | ||
| 109 | + DESTINATION share/info/${VENDOR_NAME}/script | ||
| 110 | + COMPONENT ${VENDOR_NAME} | ||
| 111 | +) | ||
| 112 | + | ||
| 113 | +# version 配置 | ||
| 114 | +# 由 add_cann_version_info_targets 命令产出 | ||
| 115 | +install(FILES ${CMAKE_BINARY_DIR}/version.${VENDOR_NAME}.info | ||
| 116 | + DESTINATION share/info/${VENDOR_NAME} | ||
| 117 | + RENAME version.info | ||
| 118 | + COMPONENT ${VENDOR_NAME} | ||
| 119 | +) | ||
| 120 | + | ||
| 121 | +set_cann_cpack_config(${VENDOR_NAME} COMPUTE_UNIT ${ASCEND_COMPUTE_UNIT} PACKAGE_TYPE "${PACKAGE_TYPE}") | ||
| @@ -1,6 +1,8 @@ | |||
| 1 | # PyPTO-Gym | 1 | # PyPTO-Gym |
| 2 | 2 | ||
| 3 | ## 🔥最新动态 | 3 | ## 🔥最新动态 |
| 4 | + | ||
| 5 | +- 2026/10:PyPTO-Gym 仓的路径结构近期将做一定范围内的重构,重构后的目标旨在将 PyPTO-Gym 构建成 “PyPTO 算子的 Agent 语料基地及算子最佳实践查找基地”,当前任务仍在进行中,更多信息参见 [重构内容](/docs/build-guide.md)。 | ||
| 4 | - 2026/06:PyPTO-Gym 项目首次上线,本仓原为 [PyPTO](https://gitcode.com/cann/pypto) 仓的 `models` 目录,现已拆分为独立仓,与主仓解耦演进。 | 6 | - 2026/06:PyPTO-Gym 项目首次上线,本仓原为 [PyPTO](https://gitcode.com/cann/pypto) 仓的 `models` 目录,现已拆分为独立仓,与主仓解耦演进。 |
| 5 | 7 | ||
| 6 | ## 🚀概述 | 8 | ## 🚀概述 |
| @@ -1,6 +1,6 @@ | |||
| 1 | #!/usr/bin/env python3 | 1 | #!/usr/bin/env python3 |
| 2 | # coding: utf-8 | 2 | # coding: utf-8 |
| 3 | -# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | 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 | 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"). | 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. | 6 | # Please refer to the License for details. You may not use this file except in compliance with the License. |
| @@ -0,0 +1,331 @@ | |||
| 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 | +构建公共配置, 按四阶段组织: | ||
| 12 | + 1 环境检查 | ||
| 13 | + fail-fast 检查外部依赖(工具链/CANN 包/仓自身), 含就近的路径派生; | ||
| 14 | + 2 CMake 选项缺省 构建系统自身配置的缺省补全(CMAKE_* 系); | ||
| 15 | + 3 入参校验与规范化 gym 业务入参(-D 值)的合法性与规范化; | ||
| 16 | + 4 预处理 构建前置动作(输出目录/ini 初始化/prepare.sh 二次构建). | ||
| 17 | + | ||
| 18 | +用户可感知的 option 一律声明在根 CMakeLists.txt, 本文件只做内部变量与检查. | ||
| 19 | +]] | ||
| 20 | + | ||
| 21 | +######################################################################################################################## | ||
| 22 | +# 环境检查 | ||
| 23 | +######################################################################################################################## | ||
| 24 | + | ||
| 25 | +# 系统名称前缀(内部变量, 供 CANN 包内路径拼接) | ||
| 26 | +if (UNIX) | ||
| 27 | + set(SYSTEM_PREFIX ${CMAKE_SYSTEM_PROCESSOR}-linux) | ||
| 28 | +endif() | ||
| 29 | + | ||
| 30 | +# Python3 解析 | ||
| 31 | +# 1. Python3_EXECUTABLE 用以标识 Python3 可执行文件路径, -D 指定的优先级高于环境变量; | ||
| 32 | +# 2. 刷新 CMake 内部变量 Python3_ROOT_DIR 值, 以便后续 find python 相关 package 使用(主要是 Development 组件); | ||
| 33 | +if (DEFINED Python3_EXECUTABLE) | ||
| 34 | + set(Python3_EXECUTABLE "${Python3_EXECUTABLE}") # 不可直接获取绝对路径, 避免不同 executable 权限差异导致的 pip 包查找问题 | ||
| 35 | +elseif (DEFINED ENV{Python3_EXECUTABLE}) | ||
| 36 | + set(Python3_EXECUTABLE "$ENV{Python3_EXECUTABLE}") # 不可直接获取绝对路径, 避免不同 executable 权限差异导致的 pip 包查找问题 | ||
| 37 | +else () | ||
| 38 | + # 当外部未指定 Python3 时, 一般是从 CMake 为入口触发的编译, 此时直接 find. | ||
| 39 | + find_package(Python3 COMPONENTS Interpreter) | ||
| 40 | + if ("${Python3_EXECUTABLE}x" STREQUAL "x") | ||
| 41 | + message(FATAL_ERROR "Can't find python3 Interpreter.") | ||
| 42 | + endif () | ||
| 43 | +endif () | ||
| 44 | +message(STATUS "Python3_EXECUTABLE=${Python3_EXECUTABLE}") | ||
| 45 | +if (NOT (DEFINED Python3_ROOT_DIR OR DEFINED ENV{Python3_ROOT_DIR})) | ||
| 46 | + get_filename_component(_Python3__EXECUTABLE "${Python3_EXECUTABLE}" REALPATH) | ||
| 47 | + get_filename_component(_Python3_ROOT_DIR "${_Python3__EXECUTABLE}" DIRECTORY) | ||
| 48 | + get_filename_component(_Python3_ROOT_DIR "${_Python3_ROOT_DIR}/../" REALPATH) | ||
| 49 | + set(Python3_ROOT_DIR "${_Python3_ROOT_DIR}" CACHE INTERNAL "Python3 root path" FORCE) | ||
| 50 | + message(STATUS "Python3_ROOT_DIR=${Python3_ROOT_DIR}") | ||
| 51 | +endif () | ||
| 52 | + | ||
| 53 | +# CANN 包路径解析 (优先级 -D 覆盖 > 环境变量 > 默认路径) | ||
| 54 | +set(ASCEND_CANN_PACKAGE_PATH) | ||
| 55 | +if (CUSTOM_ASCEND_CANN_PACKAGE_PATH) | ||
| 56 | + get_filename_component(ASCEND_CANN_PACKAGE_PATH "${CUSTOM_ASCEND_CANN_PACKAGE_PATH}" REALPATH) | ||
| 57 | +elseif (DEFINED ENV{ASCEND_HOME_PATH}) | ||
| 58 | + get_filename_component(ASCEND_CANN_PACKAGE_PATH "$ENV{ASCEND_HOME_PATH}" REALPATH) | ||
| 59 | +else () | ||
| 60 | + get_filename_component(ASCEND_CANN_PACKAGE_PATH "/usr/local/Ascend/cann/" REALPATH) | ||
| 61 | +endif () | ||
| 62 | +message(STATUS "ASCEND_CANN_PACKAGE_PATH=${ASCEND_CANN_PACKAGE_PATH}") | ||
| 63 | + | ||
| 64 | +# CANN 包完整性: op_build 工具存在性 | ||
| 65 | +set(OP_BUILD_TOOL ${ASCEND_CANN_PACKAGE_PATH}/tools/opbuild/op_build CACHE STRING "op_build tool") | ||
| 66 | +if (NOT EXISTS ${OP_BUILD_TOOL}) | ||
| 67 | + message(FATAL_ERROR "op_build tool not found: ${OP_BUILD_TOOL} (requires CANN >= 9.2.0)") | ||
| 68 | +endif() | ||
| 69 | + | ||
| 70 | +# CANN 包完整性: tikcpp 目录(内部变量派生) | ||
| 71 | +if (EXISTS ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/tikcpp/ascendc_kernel_cmake) | ||
| 72 | + set(ASCEND_PROJECT_DIR ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/tikcpp/ascendc_kernel_cmake) | ||
| 73 | +endif() | ||
| 74 | + | ||
| 75 | +# 仓自身 util 脚本目录(内部变量; gym 自有脚本, 非全部展开以避免路径重复) | ||
| 76 | +set(GYM_UTIL_SCRIPT_DIR ${PYPTO_GYM_SRC_DIR}/cmake/scripts/util) | ||
| 77 | + | ||
| 78 | +# 工具链前置检查(fail-fast): bisheng/asc_opc 由 opc gen 脚本消费, | ||
| 79 | +# 在 configure 期检查保证任意入口(build_ci.py / 手工 cmake)均得到相同保护. | ||
| 80 | +# PREPARE_BUILD 二次 configure 会重复执行, 检查幂等, 仅以 guard 避免重复日志. | ||
| 81 | +if (NOT PREPARE_BUILD) | ||
| 82 | + foreach(_gym_tool bisheng asc_opc) | ||
| 83 | + find_program(_gym_tool_path ${_gym_tool}) | ||
| 84 | + if(NOT _gym_tool_path) | ||
| 85 | + message(FATAL_ERROR "'${_gym_tool}' not found in PATH (source CANN set_env.sh first)") | ||
| 86 | + endif() | ||
| 87 | + unset(_gym_tool_path CACHE) | ||
| 88 | + endforeach() | ||
| 89 | +endif() | ||
| 90 | + | ||
| 91 | +######################################################################################################################## | ||
| 92 | +# 2 CMake 选项, 缺省参数设置 (构建系统自身配置) | ||
| 93 | +# 按 CMake 构建过程对 CMake 选项, CMake 缺省参数进行配置 | ||
| 94 | +# CMake 构建过程: 1) 配置阶段(Configure); 2) 构建阶段(Build); 3) 安装阶段(Install); | ||
| 95 | +######################################################################################################################## | ||
| 96 | + | ||
| 97 | +# 构建阶段(Build) | ||
| 98 | +# 构建类型 | ||
| 99 | +# CMake中的Generator(生成器)是用于生成本地/本机构建系统的工具. 一般分为两种: | ||
| 100 | +# 1. 单配置生成器(Single-configuration generator): | ||
| 101 | +# 在配置(Configuration)阶段, 仅允许指定一种构建类型, 通过变量 CMAKE_BUILD_TYPE 指定; | ||
| 102 | +# 在构建阶段(Build)无法更改构建类型, 仅允许使用配置(Configuration)阶段通过变量 CMAKE_BUILD_TYPE 指定的构建类型; | ||
| 103 | +# 常见的此类型生成器有: Ninja, Unix Makefiles | ||
| 104 | +# 2. 多配置生成器(Multi-configuration generator) : | ||
| 105 | +# 在配置(Configuration)阶段, 仅指定构建阶段(Build)可用的构建类型列表, 通过变量 CMAKE_CONFIGURATION_TYPES 指定; | ||
| 106 | +# 在构建阶段(Build)通过 "--config" 参数, 指定构建阶段具体的构建类型; | ||
| 107 | +# 常见的此类型生成器有: Xcode, Visual Studio | ||
| 108 | +# 所以: | ||
| 109 | +# 1. 单配置生成器(Single-configuration generator)场景下, 如果构建类型(CMAKE_BUILD_TYPE)未指定, 则默认为 Debug ; | ||
| 110 | +# 2. 多配置生成器(Multi-configuration generator)场景下, 如果构建阶段可选的构建类型(CMAKE_CONFIGURATION_TYPES)未指定, | ||
| 111 | +# 则默认将其指定为CMake允许的构建类型全集 [Debug;Release;MinSizeRel;RelWithDebInfo] | ||
| 112 | +message(STATUS "CMAKE_GENERATOR=${CMAKE_GENERATOR}") | ||
| 113 | +get_property(GENERATOR_IS_MULTI_CONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) | ||
| 114 | +if (GENERATOR_IS_MULTI_CONFIG) | ||
| 115 | + if (NOT CMAKE_CONFIGURATION_TYPES) | ||
| 116 | + set(CMAKE_CONFIGURATION_TYPES "Debug;Release;MinSizeRel;RelWithDebInfo" CACHE STRING "Configuration Build type" FORCE) | ||
| 117 | + endif () | ||
| 118 | +else () | ||
| 119 | + if (NOT CMAKE_BUILD_TYPE) | ||
| 120 | + set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Build type(default Release)" FORCE) | ||
| 121 | + endif () | ||
| 122 | + message(STATUS "CMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}") | ||
| 123 | +endif () | ||
| 124 | + | ||
| 125 | +# 构建阶段(Build) | ||
| 126 | +# 可执行文件运行时库文件搜索路径 RPATH | ||
| 127 | +# 在 UTest 及 STest 场景不略去 RPATH (预留: ENABLE_TESTS 选项落地时生效) | ||
| 128 | +if (ENABLE_TESTS) | ||
| 129 | + set(CMAKE_SKIP_RPATH FALSE) | ||
| 130 | +else () | ||
| 131 | + set(CMAKE_SKIP_RPATH TRUE) | ||
| 132 | +endif () | ||
| 133 | + | ||
| 134 | +# 构建阶段(Build) | ||
| 135 | +# 语言标准 | ||
| 136 | +set(CMAKE_C_STANDARD 11) # 指定 C 语言使用 ISO C11 标准 | ||
| 137 | +set(CMAKE_C_STANDARD_REQUIRED ON) # 要求严格支持 C11 标准 | ||
| 138 | +set(CMAKE_C_EXTENSIONS OFF) # 禁用 C 编译器扩展, 使用纯 ISO C 标准 | ||
| 139 | +set(CMAKE_CXX_STANDARD 17) # 指定 C++ 语言使用 ISO C++17 标准 | ||
| 140 | +set(CMAKE_CXX_STANDARD_REQUIRED ON) # 要求严格支持 C++17 标准 | ||
| 141 | +set(CMAKE_CXX_EXTENSIONS OFF) # 禁用 C++ 编译器扩展, 使用纯 ISO C++17 标准 | ||
| 142 | + | ||
| 143 | +# 构建阶段(Build) | ||
| 144 | +# 构建选项 | ||
| 145 | +set(CMAKE_C_FLAGS_RELEASE "") | ||
| 146 | +set(CMAKE_CXX_FLAGS_RELEASE "") | ||
| 147 | + | ||
| 148 | +# 构建阶段(Build) | ||
| 149 | +# CCACHE 配置 | ||
| 150 | +find_program(CCACHE_PROGRAM ccache) | ||
| 151 | +if (CCACHE_PROGRAM) | ||
| 152 | + set(CMAKE_C_COMPILER_LAUNCHER ${CCACHE_PROGRAM} CACHE PATH "C cache Compiler") | ||
| 153 | + set(CMAKE_CXX_COMPILER_LAUNCHER ${CCACHE_PROGRAM} CACHE PATH "CXX cache Compiler") | ||
| 154 | + message(STATUS "Use ccache, CCACHE_BASEDIR=$ENV{CCACHE_BASEDIR}") | ||
| 155 | +else () | ||
| 156 | + message(STATUS "ccache not found.") | ||
| 157 | +endif () | ||
| 158 | + | ||
| 159 | +# 安装阶段(Install) | ||
| 160 | +# 安装路径 | ||
| 161 | +# 未显示设置 CMAKE_INSTALL_PREFIX (即 CMAKE_INSTALL_PREFIX 取缺省值)时, 设置与构建树根目录 CMAKE_CURRENT_BINARY_DIR 平级 | ||
| 162 | +if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) | ||
| 163 | + get_filename_component(_Install_Path_Prefix "${CMAKE_CURRENT_BINARY_DIR}/../build_out" REALPATH) | ||
| 164 | + set(CMAKE_INSTALL_PREFIX "${_Install_Path_Prefix}" CACHE STRING "Install path" FORCE) | ||
| 165 | +endif () | ||
| 166 | +message(STATUS "CMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX}") | ||
| 167 | + | ||
| 168 | + | ||
| 169 | +######################################################################################################################## | ||
| 170 | +# 3 入参校验与规范化 (gym 业务入参) | ||
| 171 | +######################################################################################################################## | ||
| 172 | + | ||
| 173 | +# 单 soc 契约: 一次 cmake 调用只处理一个 soc, 多 soc 由外部按 soc 循环驱动(build_ci.py). | ||
| 174 | +# 此处强制契约: 非空、且不含列表分隔符(;/,) —— 违约即报错, 避免编译多 soc 而打包只取其一的不一致状态. | ||
| 175 | +if (NOT ASCEND_COMPUTE_UNIT) | ||
| 176 | + message(FATAL_ERROR "ASCEND_COMPUTE_UNIT must be a non-empty soc name (e.g. ascend950)") | ||
| 177 | +endif() | ||
| 178 | +if (ASCEND_COMPUTE_UNIT MATCHES "[;,]") | ||
| 179 | + message(FATAL_ERROR "ASCEND_COMPUTE_UNIT must be a single soc, got '${ASCEND_COMPUTE_UNIT}'; " | ||
| 180 | + "multi-soc is driven by the external per-soc build loop (build_ci.py)") | ||
| 181 | +endif() | ||
| 182 | + | ||
| 183 | +# 当前仅支持 ascend950; soc -> opc soc / pypto arch 映射见 cmake/scripts/util/const_var.py | ||
| 184 | +set(GYM_SUPPORTED_SOC ascend950) | ||
| 185 | +if (NOT ASCEND_COMPUTE_UNIT IN_LIST GYM_SUPPORTED_SOC) | ||
| 186 | + message(FATAL_ERROR "unsupported soc '${ASCEND_COMPUTE_UNIT}': gym currently supports ${GYM_SUPPORTED_SOC} only") | ||
| 187 | +endif() | ||
| 188 | + | ||
| 189 | +# 算子名单规范化: 逗号分隔 -> CMake list(供 gym_op_discovery 白名单过滤与 prepare.sh 转发) | ||
| 190 | +string(REPLACE "," ";" ASCEND_OP_NAME "${ASCEND_OP_NAME}") | ||
| 191 | + | ||
| 192 | + | ||
| 193 | +######################################################################################################################## | ||
| 194 | +# 4 预处理 (构建前置动作) | ||
| 195 | +######################################################################################################################## | ||
| 196 | + | ||
| 197 | +# [预留能力·原样保留] GCOV 编译器守卫(ENABLE_GCOV 选项落地时生效) | ||
| 198 | +if (NOT "${CMAKE_C_COMPILER_ID}" STREQUAL "GNU") | ||
| 199 | + if (ENABLE_GCOV) | ||
| 200 | + set(ENABLE_GCOV OFF) | ||
| 201 | + message(WARNING "GCov only supported in GNU Compiler, Current Compiler is ${CMAKE_C_COMPILER_ID}, Auto turn off it.") | ||
| 202 | + endif () | ||
| 203 | +endif () | ||
| 204 | + | ||
| 205 | +# [预留能力·原样保留] ASAN/UBSAN 用例执行环境配置(ENABLE_TESTS_EXECUTE 选项落地时生效). | ||
| 206 | +# 编译执行用例场景下, 将相关检查在编译前执行, 避免出现编译完成后又无法执行的情况, 影响使用体验. | ||
| 207 | +if ((ENABLE_ASAN OR ENABLE_UBSAN) AND ENABLE_TESTS_EXECUTE) | ||
| 208 | + # 用于向外传递 XSAN 相关配置, 以保证 whl 包 ASan 场景的兼容性 | ||
| 209 | + set(XSAN_CONFIG_FILE "${PYPTO_GYM_SRC_DIR}/_pypto_gym_xsan_config.txt") | ||
| 210 | + file(WRITE "${XSAN_CONFIG_FILE}" "") | ||
| 211 | + | ||
| 212 | + # LD_PRELOAD, 仅 GNU 编译器需要设置 | ||
| 213 | + set(XSAN_LD_PRELOAD) | ||
| 214 | + if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") | ||
| 215 | + if (ENABLE_ASAN) | ||
| 216 | + # libasan.so | ||
| 217 | + execute_process(COMMAND ${CMAKE_C_COMPILER} --print-file-name=libasan.so | ||
| 218 | + RESULT_VARIABLE _RST | ||
| 219 | + OUTPUT_VARIABLE ASAN_SHARED_PATH) | ||
| 220 | + if (_RST) | ||
| 221 | + message(FATAL_ERROR "Can't get libasan.so path with ${CMAKE_C_COMPILER}") | ||
| 222 | + endif () | ||
| 223 | + get_filename_component(ASAN_SHARED_PATH "${ASAN_SHARED_PATH}" DIRECTORY) | ||
| 224 | + get_filename_component(ASAN_SHARED_PATH "${ASAN_SHARED_PATH}/libasan.so" REALPATH) | ||
| 225 | + if (NOT EXISTS ${ASAN_SHARED_PATH}) | ||
| 226 | + message(FATAL_ERROR | ||
| 227 | + "ASAN_SHARED_PATH=${ASAN_SHARED_PATH} not exist. Please check the completeness of the compiler installation.") | ||
| 228 | + endif () | ||
| 229 | + list(APPEND XSAN_LD_PRELOAD ${ASAN_SHARED_PATH}) | ||
| 230 | + endif () | ||
| 231 | + if (ENABLE_UBSAN) | ||
| 232 | + # libubsan.so | ||
| 233 | + execute_process(COMMAND ${CMAKE_C_COMPILER} --print-file-name=libubsan.so | ||
| 234 | + RESULT_VARIABLE _RST | ||
| 235 | + OUTPUT_VARIABLE UBSAN_SHARED_PATH) | ||
| 236 | + if (_RST) | ||
| 237 | + message(FATAL_ERROR "Can't get libubsan.so path with ${CMAKE_C_COMPILER}") | ||
| 238 | + endif () | ||
| 239 | + get_filename_component(UBSAN_SHARED_PATH "${UBSAN_SHARED_PATH}" DIRECTORY) | ||
| 240 | + get_filename_component(UBSAN_SHARED_PATH "${UBSAN_SHARED_PATH}/libubsan.so" REALPATH) | ||
| 241 | + if (NOT EXISTS ${UBSAN_SHARED_PATH}) | ||
| 242 | + message(FATAL_ERROR | ||
| 243 | + "UBSAN_SHARED_PATH=${UBSAN_SHARED_PATH} not exist. Please check the completeness of the compiler installation.") | ||
| 244 | + endif () | ||
| 245 | + list(APPEND XSAN_LD_PRELOAD ${UBSAN_SHARED_PATH}) | ||
| 246 | + endif () | ||
| 247 | + # libstdc++.so | ||
| 248 | + execute_process(COMMAND ${CMAKE_C_COMPILER} --print-file-name=libstdc++.so | ||
| 249 | + RESULT_VARIABLE _RST | ||
| 250 | + OUTPUT_VARIABLE STDC_SHARED_PATH) | ||
| 251 | + if (_RST) | ||
| 252 | + message(FATAL_ERROR "Can't get libstdc++.so path with ${CMAKE_C_COMPILER}") | ||
| 253 | + endif () | ||
| 254 | + get_filename_component(STDC_SHARED_PATH "${STDC_SHARED_PATH}" DIRECTORY) | ||
| 255 | + get_filename_component(STDC_SHARED_PATH "${STDC_SHARED_PATH}/libstdc++.so" REALPATH) | ||
| 256 | + if (NOT EXISTS ${STDC_SHARED_PATH}) | ||
| 257 | + message(FATAL_ERROR | ||
| 258 | + "STDC_SHARED_PATH=${STDC_SHARED_PATH} not exist. Please check the completeness of the compiler installation.") | ||
| 259 | + endif () | ||
| 260 | + list(APPEND XSAN_LD_PRELOAD ${STDC_SHARED_PATH}) | ||
| 261 | + # 结果修正 | ||
| 262 | + string(REPLACE ";" ":" XSAN_LD_PRELOAD "${XSAN_LD_PRELOAD}") | ||
| 263 | + set(XSAN_LD_PRELOAD "LD_PRELOAD=${XSAN_LD_PRELOAD}") | ||
| 264 | + endif () | ||
| 265 | + if (XSAN_LD_PRELOAD) | ||
| 266 | + file(APPEND "${XSAN_CONFIG_FILE}" "${XSAN_LD_PRELOAD}\n") | ||
| 267 | + endif () | ||
| 268 | + | ||
| 269 | + set(ASAN_OPTIONS) | ||
| 270 | + if (ENABLE_ASAN) | ||
| 271 | + # 谨慎修改 ASAN_OPTIONS 取值, 当前出现告警会使 GTest 失败. | ||
| 272 | + # halt_on_error=1, 出现告警时停止运行进而触发构建失败, 避免主进程或 fork 出的子进程出现错误无法发现的情况 | ||
| 273 | + # detect_stack_use_after_return=1, 栈空间返回后使用检测 | ||
| 274 | + # check_initialization_order, 尝试捕获初始化顺序问题 | ||
| 275 | + # strict_init_order, 动态初始化器永远不能访问来自其他模块的全局变量, 及时或者已经初始化 | ||
| 276 | + # strict_string_checks, 检查字符串参数是否正确以 null 终止 | ||
| 277 | + # detect_leaks=1, 内存泄漏检测 | ||
| 278 | + set(ASAN_OPTIONS "ASAN_OPTIONS=halt_on_error=1,detect_stack_use_after_return=1,check_initialization_order=1,strict_init_order=1,strict_string_checks=1,symbolize=1,detect_leaks=1") | ||
| 279 | + if (ENABLE_FEATURE_PYTHON_FRONT_END) | ||
| 280 | + set(LSAN_OPTIONS "LSAN_OPTIONS=suppressions=${PTO_FWK_SRC_ROOT}/cmake/asan_suppressions.txt") | ||
| 281 | + file(APPEND "${XSAN_CONFIG_FILE}" "${LSAN_OPTIONS}\n") | ||
| 282 | + endif () | ||
| 283 | + endif () | ||
| 284 | + if (ASAN_OPTIONS) | ||
| 285 | + file(APPEND "${XSAN_CONFIG_FILE}" "${ASAN_OPTIONS}\n") | ||
| 286 | + endif () | ||
| 287 | + | ||
| 288 | + set(UBSAN_OPTIONS) | ||
| 289 | + if (ENABLE_UBSAN) | ||
| 290 | + # 谨慎修改 UBSAN_OPTIONS 取值, 当前出现告警会使 UT 失败. | ||
| 291 | + # halt_on_error=1, 出现告警时停止运行进而触发构建失败, 避免主进程或 fork 出的子进程出现错误无法发现的情况 | ||
| 292 | + # print_stacktrace=1, 出错时打印调用栈 | ||
| 293 | + set(UBSAN_OPTIONS "UBSAN_OPTIONS=halt_on_error=0,print_stacktrace=1") | ||
| 294 | + endif () | ||
| 295 | + if (UBSAN_OPTIONS) | ||
| 296 | + file(APPEND "${XSAN_CONFIG_FILE}" "${UBSAN_OPTIONS}\n") | ||
| 297 | + endif () | ||
| 298 | +endif () | ||
| 299 | + | ||
| 300 | +# 构建树输出目录(prepare.sh 的直接输入)与自定义 opp 目录 | ||
| 301 | +set(ASCEND_IMPL_OUT_DIR ${CMAKE_BINARY_DIR}/impl CACHE STRING "adapt py output directories") | ||
| 302 | +set(ASCEND_BINARY_OUT_DIR ${CMAKE_BINARY_DIR}/binary CACHE STRING "kernel binary output directories") | ||
| 303 | +set(ASCEND_AUTOGEN_DIR ${CMAKE_BINARY_DIR}/autogen CACHE STRING "op_build autogen directories") | ||
| 304 | +set(ASCEND_CUSTOM_OPTIONS ${ASCEND_AUTOGEN_DIR}/custom_compile_options.ini) | ||
| 305 | +set(ASCEND_CUSTOM_OPC_OPTIONS ${ASCEND_AUTOGEN_DIR}/custom_opc_options.ini) | ||
| 306 | +file(MAKE_DIRECTORY ${ASCEND_AUTOGEN_DIR}) | ||
| 307 | +foreach(_ini ${ASCEND_CUSTOM_OPTIONS} ${ASCEND_CUSTOM_OPC_OPTIONS}) | ||
| 308 | + file(REMOVE ${_ini}) | ||
| 309 | + file(TOUCH ${_ini}) | ||
| 310 | +endforeach() | ||
| 311 | + | ||
| 312 | +# 二次构建机制: 主 configure 期先跑 prepare.sh(PREPARE_BUILD=ON 的第二次 cmake + make prepare_build), | ||
| 313 | +# 产出 autogen(ops-info.ini/aclnn 源) 与 impl(adapt py), 供主构建图消费 | ||
| 314 | +if (NOT PREPARE_BUILD AND ENABLE_OPS_KERNEL) | ||
| 315 | + string(REPLACE ";" "::" EP_ASCEND_OP_NAME "${ASCEND_OP_NAME}") | ||
| 316 | + execute_process(COMMAND bash ${PYPTO_GYM_SRC_DIR}/cmake/scripts/prepare.sh | ||
| 317 | + -s ${CMAKE_CURRENT_SOURCE_DIR} | ||
| 318 | + -b ${CMAKE_BINARY_DIR}/prepare_build | ||
| 319 | + -p ${ASCEND_CANN_PACKAGE_PATH} | ||
| 320 | + --autogen-dir ${ASCEND_AUTOGEN_DIR} | ||
| 321 | + --binary-out-dir ${ASCEND_BINARY_OUT_DIR} | ||
| 322 | + --impl-out-dir ${ASCEND_IMPL_OUT_DIR} | ||
| 323 | + --op-build-tool ${OP_BUILD_TOOL} | ||
| 324 | + --ascend-cmake-dir ${ASCEND_PROJECT_DIR} | ||
| 325 | + --ascend-compute_unit ${ASCEND_COMPUTE_UNIT} | ||
| 326 | + --ascend-op_name ${EP_ASCEND_OP_NAME} | ||
| 327 | + RESULT_VARIABLE result) | ||
| 328 | + if (result) | ||
| 329 | + message(FATAL_ERROR "Error: gym prepare build failed.") | ||
| 330 | + endif () | ||
| 331 | +endif () | ||
| @@ -0,0 +1,377 @@ | |||
| 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 | +# gym custom 包编排: 算子接入后的 host 侧目标创建(三 .so/核对程序) + kernel 编译链 + install + 打包支撑. | ||
| 12 | +# 依赖顺序: op stub(obj_func.cmake) -> 算子接入(CMakeLists 顶层) -> 本文件(读回登记, 创建目标). | ||
| 13 | + | ||
| 14 | +get_property(_aclnn_default_ops GLOBAL PROPERTY GYM_ACLNN_TYPE_aclnn) | ||
| 15 | +get_property(_aclnn_inner_ops GLOBAL PROPERTY GYM_ACLNN_TYPE_aclnn_inner) | ||
| 16 | +get_property(_aclnn_exclude_ops GLOBAL PROPERTY GYM_ACLNN_TYPE_aclnn_exclude) | ||
| 17 | +list(REMOVE_DUPLICATES _aclnn_default_ops) | ||
| 18 | +list(REMOVE_DUPLICATES _aclnn_inner_ops) | ||
| 19 | +list(REMOVE_DUPLICATES _aclnn_exclude_ops) | ||
| 20 | + | ||
| 21 | +# inner/exc 无算子时用 stub, 保证 op_build 三份 ops-info.ini 齐套 | ||
| 22 | +if(NOT _aclnn_inner_ops) | ||
| 23 | + set(_inner_stub ${CMAKE_BINARY_DIR}/op_host_aclnn_inner_stub.cpp) | ||
| 24 | + file(WRITE ${_inner_stub} "// stub for empty aclnnInner op set\n") | ||
| 25 | + target_sources(op_host_aclnnInner PRIVATE ${_inner_stub}) | ||
| 26 | +endif() | ||
| 27 | +if(NOT _aclnn_exclude_ops) | ||
| 28 | + set(_exc_stub ${CMAKE_BINARY_DIR}/op_host_aclnn_exc_stub.cpp) | ||
| 29 | + file(WRITE ${_exc_stub} "// stub for empty aclnnExc op set\n") | ||
| 30 | + target_sources(op_host_aclnnExc PRIVATE ${_exc_stub}) | ||
| 31 | +endif() | ||
| 32 | + | ||
| 33 | +# ---------------------------------------- op_build 反射目标 ---------------------------------------- | ||
| 34 | +set(base_aclnn_binary_dir ${ASCEND_AUTOGEN_DIR}) | ||
| 35 | +set(generate_aclnn_srcs) | ||
| 36 | +set(generate_aclnn_headers) | ||
| 37 | +foreach(_op_name ${_aclnn_default_ops}) | ||
| 38 | + list(APPEND generate_aclnn_srcs ${base_aclnn_binary_dir}/aclnn_${_op_name}.cpp) | ||
| 39 | + list(APPEND generate_aclnn_headers ${base_aclnn_binary_dir}/aclnn_${_op_name}.h) | ||
| 40 | +endforeach() | ||
| 41 | + | ||
| 42 | +set(generate_aclnn_inner_srcs) | ||
| 43 | +foreach(_op_name ${_aclnn_inner_ops}) | ||
| 44 | + list(APPEND generate_aclnn_inner_srcs ${base_aclnn_binary_dir}/inner/aclnnInner_${_op_name}.cpp) | ||
| 45 | +endforeach() | ||
| 46 | + | ||
| 47 | +set(generate_exclude_proto_srcs) | ||
| 48 | +foreach(_op_name ${_aclnn_exclude_ops}) | ||
| 49 | + list(APPEND generate_exclude_proto_srcs ${base_aclnn_binary_dir}/exc/${_op_name}_proto.cpp) | ||
| 50 | +endforeach() | ||
| 51 | + | ||
| 52 | +string(REPLACE ";" "\;" OPS_PRODUCT_NAME "${ASCEND_COMPUTE_UNIT}") | ||
| 53 | +if (generate_aclnn_srcs) | ||
| 54 | + add_custom_command(OUTPUT ${generate_aclnn_srcs} ${generate_aclnn_headers} | ||
| 55 | + COMMAND mkdir -p ${base_aclnn_binary_dir} | ||
| 56 | + COMMAND OPS_PROTO_SEPARATE=1 | ||
| 57 | + OPS_ACLNN_GEN=1 | ||
| 58 | + OPS_PROJECT_NAME=aclnn | ||
| 59 | + OPS_PRODUCT_NAME=\"${OPS_PRODUCT_NAME}\" | ||
| 60 | + env LD_PRELOAD= | ||
| 61 | + ${OP_BUILD_TOOL} | ||
| 62 | + $<TARGET_FILE:op_host_aclnn> | ||
| 63 | + ${base_aclnn_binary_dir} | ||
| 64 | + ) | ||
| 65 | +endif () | ||
| 66 | +add_custom_target(opbuild_gen_default | ||
| 67 | + DEPENDS ${generate_aclnn_srcs} ${generate_aclnn_headers} op_host_aclnn) | ||
| 68 | + | ||
| 69 | +if (generate_aclnn_inner_srcs) | ||
| 70 | + add_custom_command(OUTPUT ${generate_aclnn_inner_srcs} | ||
| 71 | + COMMAND mkdir -p ${base_aclnn_binary_dir}/inner | ||
| 72 | + COMMAND OPS_PROTO_SEPARATE=1 | ||
| 73 | + OPS_ACLNN_GEN=1 | ||
| 74 | + OPS_PROJECT_NAME=aclnnInner | ||
| 75 | + OPS_PRODUCT_NAME=\"${OPS_PRODUCT_NAME}\" | ||
| 76 | + env LD_PRELOAD= | ||
| 77 | + ${OP_BUILD_TOOL} | ||
| 78 | + $<TARGET_FILE:op_host_aclnnInner> | ||
| 79 | + ${base_aclnn_binary_dir}/inner | ||
| 80 | + ) | ||
| 81 | +endif () | ||
| 82 | +add_custom_target(opbuild_gen_inner | ||
| 83 | + DEPENDS ${generate_aclnn_inner_srcs} op_host_aclnnInner) | ||
| 84 | + | ||
| 85 | +if (generate_exclude_proto_srcs) | ||
| 86 | + add_custom_command(OUTPUT ${generate_exclude_proto_srcs} | ||
| 87 | + COMMAND mkdir -p ${base_aclnn_binary_dir}/exc | ||
| 88 | + COMMAND OPS_PROTO_SEPARATE=1 | ||
| 89 | + OPS_ACLNN_GEN=0 | ||
| 90 | + OPS_PROJECT_NAME=aclnnExc | ||
| 91 | + OPS_PRODUCT_NAME=\"${OPS_PRODUCT_NAME}\" | ||
| 92 | + env LD_PRELOAD= | ||
| 93 | + ${OP_BUILD_TOOL} | ||
| 94 | + $<TARGET_FILE:op_host_aclnnExc> | ||
| 95 | + ${base_aclnn_binary_dir}/exc | ||
| 96 | + ) | ||
| 97 | +endif () | ||
| 98 | +add_custom_target(opbuild_gen_exc | ||
| 99 | + DEPENDS ${generate_exclude_proto_srcs} op_host_aclnnExc) | ||
| 100 | + | ||
| 101 | +# ---------------------------------------- adapt py 生成 ---------------------------------------- | ||
| 102 | +get_property(_pypto_adapt_ops GLOBAL PROPERTY PYPTO_ENABLED_OPS) | ||
| 103 | +set(PYPTO_ADAPT_OPS_OPTION "") | ||
| 104 | +if (_pypto_adapt_ops) | ||
| 105 | + list(REMOVE_DUPLICATES _pypto_adapt_ops) | ||
| 106 | + list(JOIN _pypto_adapt_ops "," _pypto_adapt_ops_str) | ||
| 107 | + set(PYPTO_ADAPT_OPS_OPTION --pypto-ops ${_pypto_adapt_ops_str}) | ||
| 108 | +endif () | ||
| 109 | + | ||
| 110 | +add_custom_target(generate_gym_adapt_py | ||
| 111 | + COMMAND ${Python3_EXECUTABLE} ${PYPTO_GYM_SRC_DIR}/cmake/scripts/util/ascendc_impl_build.py | ||
| 112 | + \"\" | ||
| 113 | + \"\" | ||
| 114 | + \"\" | ||
| 115 | + \"\" | ||
| 116 | + ${ASCEND_IMPL_OUT_DIR} | ||
| 117 | + ${ASCEND_AUTOGEN_DIR} | ||
| 118 | + --opsinfo-dir ${base_aclnn_binary_dir} ${base_aclnn_binary_dir}/inner ${base_aclnn_binary_dir}/exc | ||
| 119 | + --compute-unit ${ASCEND_COMPUTE_UNIT} | ||
| 120 | + ${PYPTO_ADAPT_OPS_OPTION} | ||
| 121 | +) | ||
| 122 | +add_dependencies(generate_gym_adapt_py opbuild_gen_default opbuild_gen_inner opbuild_gen_exc) | ||
| 123 | + | ||
| 124 | +# ---------------------------------------- 聚合目标 ---------------------------------------- | ||
| 125 | +add_custom_target(prepare_build ALL) | ||
| 126 | +add_custom_target(generate_compile_cmd ALL) | ||
| 127 | +add_dependencies(prepare_build generate_gym_adapt_py generate_compile_cmd) | ||
| 128 | + | ||
| 129 | +foreach (compute_unit ${ASCEND_COMPUTE_UNIT}) | ||
| 130 | + add_compile_cmd_target(COMPUTE_UNIT ${compute_unit}) | ||
| 131 | +endforeach () | ||
| 132 | + | ||
| 133 | +if (ENABLE_OPS_KERNEL) | ||
| 134 | + add_custom_target(ops_gym_kernel ALL) | ||
| 135 | + add_custom_target(ops_gym_config ALL) | ||
| 136 | + add_dependencies(ops_gym_kernel ops_gym_config) | ||
| 137 | + foreach (compute_unit ${ASCEND_COMPUTE_UNIT}) | ||
| 138 | + add_bin_compile_target( | ||
| 139 | + COMPUTE_UNIT ${compute_unit} | ||
| 140 | + OP_INFO ${OP_DIR_LIST}) | ||
| 141 | + endforeach () | ||
| 142 | +endif () | ||
| 143 | + | ||
| 144 | +# ---------------------------------------- host 侧: 三 .so + vendors staging ---------------------------------------- | ||
| 145 | +# pass-2(PREPARE_BUILD) 跳过: autogen 源尚不存在, 且 host 产物不属于 prepare 阶段 | ||
| 146 | +if (ENABLE_OPS_HOST AND NOT PREPARE_BUILD) | ||
| 147 | + | ||
| 148 | + set(_vendor_dir packages/vendors/${VENDOR_NAME}) | ||
| 149 | + set(_arch_lib_dir ${_vendor_dir}/op_proto/lib/linux/${CMAKE_SYSTEM_PROCESSOR}) | ||
| 150 | + | ||
| 151 | + get_property(_infer_srcs GLOBAL PROPERTY GYM_INFER_SRCS) | ||
| 152 | + get_property(_tiling_srcs GLOBAL PROPERTY GYM_TILING_SRCS) | ||
| 153 | + get_property(_opapi_srcs GLOBAL PROPERTY GYM_OPAPI_SRCS) | ||
| 154 | + get_property(_pypto_gen_dirs GLOBAL PROPERTY GYM_PYPTO_GEN_DIRS) | ||
| 155 | + get_property(_tiling_check_srcs GLOBAL PROPERTY GYM_TILING_CHECK_SRCS) | ||
| 156 | + list(REMOVE_DUPLICATES _infer_srcs) | ||
| 157 | + list(REMOVE_DUPLICATES _tiling_srcs) | ||
| 158 | + list(REMOVE_DUPLICATES _opapi_srcs) | ||
| 159 | + list(REMOVE_DUPLICATES _pypto_gen_dirs) | ||
| 160 | + list(REMOVE_DUPLICATES _tiling_check_srcs) | ||
| 161 | + | ||
| 162 | + # autogen 源清单 | ||
| 163 | + set(_autogen_aclnn_srcs) | ||
| 164 | + set(_autogen_proto_srcs) | ||
| 165 | + set(_autogen_aclnn_headers) | ||
| 166 | + foreach(_op_name ${_aclnn_default_ops}) | ||
| 167 | + list(APPEND _autogen_aclnn_srcs ${base_aclnn_binary_dir}/aclnn_${_op_name}.cpp) | ||
| 168 | + list(APPEND _autogen_aclnn_headers ${base_aclnn_binary_dir}/aclnn_${_op_name}.h) | ||
| 169 | + list(APPEND _autogen_proto_srcs ${base_aclnn_binary_dir}/${_op_name}_proto.cpp) | ||
| 170 | + endforeach() | ||
| 171 | + | ||
| 172 | + # host 编译公共含头(地面真值裁剪自 ops-transformer 参照构建) | ||
| 173 | + set(GYM_HOST_INCLUDES | ||
| 174 | + ${ASCEND_CANN_PACKAGE_PATH}/include | ||
| 175 | + ${ASCEND_CANN_PACKAGE_PATH}/include/exe_graph | ||
| 176 | + ${ASCEND_CANN_PACKAGE_PATH}/include/external | ||
| 177 | + ${ASCEND_CANN_PACKAGE_PATH}/include/platform | ||
| 178 | + ${ASCEND_CANN_PACKAGE_PATH}/include/experiment/msprof | ||
| 179 | + ${ASCEND_CANN_PACKAGE_PATH}/include/experiment/runtime | ||
| 180 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/include | ||
| 181 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/pkg_inc | ||
| 182 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/include/exe_graph | ||
| 183 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/include/aclnn | ||
| 184 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/ascendc/include | ||
| 185 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/ascendc/include/highlevel_api | ||
| 186 | + ${base_aclnn_binary_dir}) | ||
| 187 | + set(GYM_HOST_LINK_DIRS | ||
| 188 | + ${ASCEND_CANN_PACKAGE_PATH}/lib64 | ||
| 189 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/lib64) | ||
| 190 | + set(GYM_CANN_LIBS_DIR ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/lib64) | ||
| 191 | + | ||
| 192 | + # ---------- infer/proto obj → cust_opsproto_rt2.0.so ---------- | ||
| 193 | + add_library(ophost_gym_infer_obj OBJECT EXCLUDE_FROM_ALL) | ||
| 194 | + set_target_properties(ophost_gym_infer_obj PROPERTIES POSITION_INDEPENDENT_CODE ON) | ||
| 195 | + target_include_directories(ophost_gym_infer_obj PRIVATE ${GYM_HOST_INCLUDES}) | ||
| 196 | + if (_autogen_proto_srcs) | ||
| 197 | + target_sources(ophost_gym_infer_obj PRIVATE ${_autogen_proto_srcs}) | ||
| 198 | + endif() | ||
| 199 | + if (_infer_srcs) | ||
| 200 | + target_sources(ophost_gym_infer_obj PRIVATE ${_infer_srcs}) | ||
| 201 | + endif() | ||
| 202 | + target_link_libraries(ophost_gym_infer_obj PRIVATE intf_pub) | ||
| 203 | + add_dependencies(ophost_gym_infer_obj opbuild_gen_default) | ||
| 204 | + | ||
| 205 | + add_library(cust_proto SHARED EXCLUDE_FROM_ALL $<TARGET_OBJECTS:ophost_gym_infer_obj>) | ||
| 206 | + set_target_properties(cust_proto PROPERTIES OUTPUT_NAME cust_opsproto_rt2.0) | ||
| 207 | + target_include_directories(cust_proto PRIVATE ${GYM_HOST_INCLUDES}) | ||
| 208 | + target_link_directories(cust_proto PRIVATE ${GYM_HOST_LINK_DIRS}) | ||
| 209 | + target_link_libraries(cust_proto PRIVATE | ||
| 210 | + ${GYM_CANN_LIBS_DIR}/libexe_graph.so | ||
| 211 | + ${GYM_CANN_LIBS_DIR}/libgraph.so | ||
| 212 | + ${GYM_CANN_LIBS_DIR}/libgraph_base.so | ||
| 213 | + ${GYM_CANN_LIBS_DIR}/libregister.so | ||
| 214 | + ${GYM_CANN_LIBS_DIR}/liberror_manager.so | ||
| 215 | + ${GYM_CANN_LIBS_DIR}/libplatform.so | ||
| 216 | + ${GYM_CANN_LIBS_DIR}/librt2_registry.a | ||
| 217 | + ${ASCEND_CANN_PACKAGE_PATH}/lib64/libc_sec.so | ||
| 218 | + ascendalog pthread) | ||
| 219 | + target_link_libraries(cust_proto PRIVATE intf_pub) | ||
| 220 | + add_dependencies(cust_proto ophost_gym_infer_obj) | ||
| 221 | + | ||
| 222 | + # ---------- tiling obj → cust_opmaster_rt2.0.so + liboptiling.so 软链 ---------- | ||
| 223 | + add_library(ophost_gym_tiling_obj OBJECT EXCLUDE_FROM_ALL) | ||
| 224 | + set_target_properties(ophost_gym_tiling_obj PROPERTIES POSITION_INDEPENDENT_CODE ON) | ||
| 225 | + target_include_directories(ophost_gym_tiling_obj PRIVATE ${GYM_HOST_INCLUDES}) | ||
| 226 | + if (_tiling_srcs) | ||
| 227 | + # force-include pypto 生成头进 tiling 源(与 kernel 侧 tiling 定义一致性的权威参照) | ||
| 228 | + set(_force_opts "") | ||
| 229 | + foreach(_gen_dir ${_pypto_gen_dirs}) | ||
| 230 | + file(GLOB _gen_headers ${_gen_dir}/*_tilingkey.h ${_gen_dir}/*_tiling.h) | ||
| 231 | + foreach(_h ${_gen_headers}) | ||
| 232 | + list(APPEND _force_opts -include ${_h}) | ||
| 233 | + endforeach() | ||
| 234 | + endforeach() | ||
| 235 | + if (_force_opts) | ||
| 236 | + set_source_files_properties(${_tiling_srcs} PROPERTIES COMPILE_OPTIONS "${_force_opts}") | ||
| 237 | + endif() | ||
| 238 | + target_sources(ophost_gym_tiling_obj PRIVATE ${_tiling_srcs}) | ||
| 239 | + target_link_libraries(ophost_gym_tiling_obj PRIVATE intf_pub) | ||
| 240 | + endif() | ||
| 241 | + | ||
| 242 | + # tiling 布局核对程序(tiling_layout_check.py 生成, 运行时布局 vs 编译期真值 | ||
| 243 | + # 交叉验证). 构建并在 tiling 编译前执行, 失败即拒(阻断后续编译). | ||
| 244 | + foreach(_chk_src ${_tiling_check_srcs}) | ||
| 245 | + get_filename_component(_chk_name ${_chk_src} NAME_WE) | ||
| 246 | + add_executable(${_chk_name} EXCLUDE_FROM_ALL ${_chk_src}) | ||
| 247 | + target_include_directories(${_chk_name} PRIVATE ${GYM_HOST_INCLUDES}) | ||
| 248 | + target_link_directories(${_chk_name} PRIVATE ${GYM_HOST_LINK_DIRS}) | ||
| 249 | + target_link_libraries(${_chk_name} PRIVATE | ||
| 250 | + ${GYM_CANN_LIBS_DIR}/libopp_registry.so | ||
| 251 | + ${GYM_CANN_LIBS_DIR}/libregister.so | ||
| 252 | + ${ASCEND_CANN_PACKAGE_PATH}/lib64/libc_sec.so | ||
| 253 | + pthread) | ||
| 254 | + add_custom_target(run_${_chk_name} | ||
| 255 | + COMMAND $<TARGET_FILE:${_chk_name}> | ||
| 256 | + DEPENDS ${_chk_name}) | ||
| 257 | + target_link_libraries(${_chk_name} PRIVATE intf_pub) | ||
| 258 | + add_dependencies(ophost_gym_tiling_obj run_${_chk_name}) | ||
| 259 | + endforeach() | ||
| 260 | + | ||
| 261 | + add_library(cust_opmaster SHARED EXCLUDE_FROM_ALL $<TARGET_OBJECTS:ophost_gym_tiling_obj>) | ||
| 262 | + set_target_properties(cust_opmaster PROPERTIES OUTPUT_NAME cust_opmaster_rt2.0) | ||
| 263 | + target_include_directories(cust_opmaster PRIVATE ${GYM_HOST_INCLUDES}) | ||
| 264 | + target_link_directories(cust_opmaster PRIVATE ${GYM_HOST_LINK_DIRS}) | ||
| 265 | + target_link_libraries(cust_opmaster PRIVATE | ||
| 266 | + ${GYM_CANN_LIBS_DIR}/libgraph.so | ||
| 267 | + ${GYM_CANN_LIBS_DIR}/libgraph_base.so | ||
| 268 | + ${GYM_CANN_LIBS_DIR}/libexe_graph.so | ||
| 269 | + ${GYM_CANN_LIBS_DIR}/libplatform.so | ||
| 270 | + ${GYM_CANN_LIBS_DIR}/libregister.so | ||
| 271 | + ${GYM_CANN_LIBS_DIR}/liberror_manager.so | ||
| 272 | + ${GYM_CANN_LIBS_DIR}/librt2_registry.a | ||
| 273 | + ${GYM_CANN_LIBS_DIR}/libtiling_api.a | ||
| 274 | + ${ASCEND_CANN_PACKAGE_PATH}/lib64/libc_sec.so | ||
| 275 | + ${ASCEND_CANN_PACKAGE_PATH}/lib64/libascendalog.so | ||
| 276 | + pthread) | ||
| 277 | + target_link_libraries(cust_opmaster PRIVATE intf_pub) | ||
| 278 | + add_dependencies(cust_opmaster ophost_gym_tiling_obj) | ||
| 279 | + | ||
| 280 | + # liboptiling.so 兼容软链(运行时按旧名查找 tiling 库) | ||
| 281 | + # 目标为安装态相对路径: 软链 install 后位于 op_tiling/ 下, .so 实际在 op_tiling/lib/linux/<arch>/ | ||
| 282 | + # (对齐 ops-transformer symbol.cmake: ALL 目标每次构建 ln -sf 强制刷新, 无陈旧软链问题; | ||
| 283 | + # build/ 内该链悬空属预期, 仅安装态需要解析) | ||
| 284 | + add_custom_target(gym_optiling_compat ALL | ||
| 285 | + COMMAND ln -sf lib/linux/${CMAKE_SYSTEM_PROCESSOR}/$<TARGET_FILE_NAME:cust_opmaster> | ||
| 286 | + ${CMAKE_BINARY_DIR}/liboptiling.so) | ||
| 287 | + | ||
| 288 | + # ---------- aclnn 静态库 → whole-archive 进 cust_opapi ---------- | ||
| 289 | + if (_autogen_aclnn_srcs) | ||
| 290 | + add_library(ops_aclnn STATIC EXCLUDE_FROM_ALL ${_autogen_aclnn_srcs}) | ||
| 291 | + set_target_properties(ops_aclnn PROPERTIES POSITION_INDEPENDENT_CODE ON) | ||
| 292 | + target_link_libraries(ops_aclnn PRIVATE intf_pub) | ||
| 293 | + target_include_directories(ops_aclnn PRIVATE ${GYM_HOST_INCLUDES}) | ||
| 294 | + add_dependencies(ops_aclnn opbuild_gen_default) | ||
| 295 | + # 手写 aclnn 通道: 手写源 whole-archive 一并链入 | ||
| 296 | + if (_opapi_srcs) | ||
| 297 | + add_library(gym_opapi_manual STATIC EXCLUDE_FROM_ALL ${_opapi_srcs}) | ||
| 298 | + set_target_properties(gym_opapi_manual PROPERTIES POSITION_INDEPENDENT_CODE ON) | ||
| 299 | + target_link_libraries(gym_opapi_manual PRIVATE intf_pub) | ||
| 300 | + target_include_directories(gym_opapi_manual PRIVATE ${GYM_HOST_INCLUDES}) | ||
| 301 | + endif() | ||
| 302 | + endif() | ||
| 303 | + | ||
| 304 | + set(_cust_opapi_stub ${CMAKE_BINARY_DIR}/cust_opapi_stub.cpp) | ||
| 305 | + file(WRITE ${_cust_opapi_stub} "// stub translation unit for libcust_opapi.so\n") | ||
| 306 | + add_library(cust_opapi SHARED EXCLUDE_FROM_ALL ${_cust_opapi_stub}) | ||
| 307 | + target_include_directories(cust_opapi PRIVATE ${GYM_HOST_INCLUDES}) | ||
| 308 | + target_link_directories(cust_opapi PRIVATE ${GYM_HOST_LINK_DIRS}) | ||
| 309 | + if (TARGET gym_opapi_manual) | ||
| 310 | + target_link_libraries(cust_opapi PRIVATE | ||
| 311 | + -Wl,--whole-archive | ||
| 312 | + $<TARGET_FILE:ops_aclnn> | ||
| 313 | + $<TARGET_FILE:gym_opapi_manual> | ||
| 314 | + -Wl,--no-whole-archive) | ||
| 315 | + else () | ||
| 316 | + target_link_libraries(cust_opapi PRIVATE | ||
| 317 | + -Wl,--whole-archive | ||
| 318 | + $<TARGET_FILE:ops_aclnn> | ||
| 319 | + -Wl,--no-whole-archive) | ||
| 320 | + endif () | ||
| 321 | + target_link_libraries(cust_opapi PRIVATE | ||
| 322 | + ${GYM_CANN_LIBS_DIR}/libnnopbase.so | ||
| 323 | + ${GYM_CANN_LIBS_DIR}/libprofapi.so | ||
| 324 | + ${GYM_CANN_LIBS_DIR}/libge_common_base.so | ||
| 325 | + ${GYM_CANN_LIBS_DIR}/libascend_dump.so | ||
| 326 | + ascendalog dl) | ||
| 327 | + target_link_libraries(cust_opapi PRIVATE intf_pub) | ||
| 328 | + add_dependencies(cust_opapi ops_aclnn) | ||
| 329 | + add_custom_target(ops_gym_host ALL) | ||
| 330 | + add_dependencies(ops_gym_host cust_opapi cust_proto cust_opmaster gym_optiling_compat) | ||
| 331 | + | ||
| 332 | + if (ENABLE_ASAN OR ENABLE_UBSAN) | ||
| 333 | + message(STATUS "gym sanitizers enabled via intf_pub: ASAN=${ENABLE_ASAN} UBSAN=${ENABLE_UBSAN} (host side)") | ||
| 334 | + endif() | ||
| 335 | + | ||
| 336 | + # ---------- ops-info.json (三 ini 合成) ---------- | ||
| 337 | + foreach (compute_unit ${ASCEND_COMPUTE_UNIT}) | ||
| 338 | + set(_ops_info_json ${ASCEND_AUTOGEN_DIR}/aic-${compute_unit}-ops-info.json) | ||
| 339 | + add_custom_command(OUTPUT ${_ops_info_json} | ||
| 340 | + COMMAND ${Python3_EXECUTABLE} ${GYM_UTIL_SCRIPT_DIR}/parse_ini_to_json.py | ||
| 341 | + ${base_aclnn_binary_dir}/aic-${compute_unit}-ops-info.ini | ||
| 342 | + ${base_aclnn_binary_dir}/inner/aic-${compute_unit}-ops-info.ini | ||
| 343 | + ${base_aclnn_binary_dir}/exc/aic-${compute_unit}-ops-info.ini | ||
| 344 | + ${_ops_info_json} | ||
| 345 | + DEPENDS opbuild_gen_default opbuild_gen_inner opbuild_gen_exc) | ||
| 346 | + add_custom_target(generate_ops_info_${compute_unit} ALL DEPENDS ${_ops_info_json}) | ||
| 347 | + add_dependencies(prepare_build generate_ops_info_${compute_unit}) | ||
| 348 | + endforeach () | ||
| 349 | + | ||
| 350 | + # ---------- vendors staging install 规则(COMPONENT = 包组件, 供 CPack staging 收集) ---------- | ||
| 351 | + install(TARGETS cust_opapi LIBRARY DESTINATION ${_vendor_dir}/op_api/lib COMPONENT ${VENDOR_NAME}) | ||
| 352 | + install(TARGETS cust_proto LIBRARY DESTINATION ${_arch_lib_dir} COMPONENT ${VENDOR_NAME}) | ||
| 353 | + install(TARGETS cust_opmaster | ||
| 354 | + LIBRARY DESTINATION ${_vendor_dir}/op_impl/ai_core/tbe/op_tiling/lib/linux/${CMAKE_SYSTEM_PROCESSOR} | ||
| 355 | + COMPONENT ${VENDOR_NAME}) | ||
| 356 | + install(FILES ${CMAKE_BINARY_DIR}/liboptiling.so | ||
| 357 | + DESTINATION ${_vendor_dir}/op_impl/ai_core/tbe/op_tiling COMPONENT ${VENDOR_NAME}) | ||
| 358 | + if (_autogen_aclnn_headers) | ||
| 359 | + install(FILES ${_autogen_aclnn_headers} DESTINATION ${_vendor_dir}/op_api/include/aclnnop | ||
| 360 | + COMPONENT ${VENDOR_NAME}) | ||
| 361 | + endif() | ||
| 362 | + foreach (compute_unit ${ASCEND_COMPUTE_UNIT}) | ||
| 363 | + install(FILES ${ASCEND_AUTOGEN_DIR}/aic-${compute_unit}-ops-info.json | ||
| 364 | + DESTINATION ${_vendor_dir}/op_impl/ai_core/tbe/config/${compute_unit} | ||
| 365 | + COMPONENT ${VENDOR_NAME}) | ||
| 366 | + endforeach () | ||
| 367 | + foreach (_op_dir ${OP_DIR_LIST}) | ||
| 368 | + get_filename_component(_op_name ${_op_dir} NAME) | ||
| 369 | + install(FILES ${ASCEND_IMPL_OUT_DIR}/dynamic/${_op_name}.py | ||
| 370 | + DESTINATION ${_vendor_dir}/op_impl/ai_core/tbe/${VENDOR_NAME}_impl/dynamic OPTIONAL | ||
| 371 | + COMPONENT ${VENDOR_NAME}) | ||
| 372 | + install(DIRECTORY ${_op_dir}/op_kernel | ||
| 373 | + DESTINATION ${_vendor_dir}/op_impl/ai_core/tbe/${VENDOR_NAME}_impl/ascendc/${_op_name} | ||
| 374 | + OPTIONAL COMPONENT ${VENDOR_NAME} | ||
| 375 | + PATTERN "__pycache__" EXCLUDE) | ||
| 376 | + endforeach () | ||
| 377 | +endif () | ||
| @@ -0,0 +1,326 @@ | |||
| 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 | +# gym 算子发现 + pypto 桥接 + kernel 编译目标, 机制对齐 ops-transformer cmake/func.cmake (裁剪版) | ||
| 12 | + | ||
| 13 | +# 发现 ops/{pro,tensor} 下的算子目录(锚定算子级 CMakeLists.txt, 对齐 ops-transformer op_add_subdirectory); | ||
| 14 | +# 算子契约: <op>/CMakeLists.txt(dispatcher) + <op>/op_host/(算子身份判定, 过滤中间层目录); | ||
| 15 | +# 显式 --ops 时仅编名单内算子, 否则全量 | ||
| 16 | +function(gym_op_discovery OP_LIST OP_DIR_LIST) | ||
| 17 | + set(_OP_LIST) | ||
| 18 | + set(_OP_DIR_LIST) | ||
| 19 | + | ||
| 20 | + set(_explicit_ops) | ||
| 21 | + if(DEFINED ASCEND_OP_NAME AND NOT "${ASCEND_OP_NAME}" STREQUAL "ALL") | ||
| 22 | + set(_explicit_ops ${ASCEND_OP_NAME}) | ||
| 23 | + endif() | ||
| 24 | + | ||
| 25 | + # gym 树形: ops/<paradigm>/<network|experimental|common>/<op>/ (实测本 cmake GLOB 的 | ||
| 26 | + # '**' 仅单层, 故按算子深度 1~3 显式展开; 仅 glob pro/tensor 两棵树, 与 setup.py 白名单对账) | ||
| 27 | + file(GLOB _op_cmake_files | ||
| 28 | + "${CMAKE_CURRENT_SOURCE_DIR}/ops/pro/*/CMakeLists.txt" | ||
| 29 | + "${CMAKE_CURRENT_SOURCE_DIR}/ops/pro/*/*/CMakeLists.txt" | ||
| 30 | + "${CMAKE_CURRENT_SOURCE_DIR}/ops/pro/*/*/*/CMakeLists.txt" | ||
| 31 | + "${CMAKE_CURRENT_SOURCE_DIR}/ops/tensor/*/CMakeLists.txt" | ||
| 32 | + "${CMAKE_CURRENT_SOURCE_DIR}/ops/tensor/*/*/CMakeLists.txt" | ||
| 33 | + "${CMAKE_CURRENT_SOURCE_DIR}/ops/tensor/*/*/*/CMakeLists.txt") | ||
| 34 | + | ||
| 35 | + foreach(_cmake_file ${_op_cmake_files}) | ||
| 36 | + get_filename_component(_op_dir "${_cmake_file}" DIRECTORY) | ||
| 37 | + | ||
| 38 | + # 算子身份判定: 必须有 op_host 子目录(过滤 experimental/ 等中间层目录) | ||
| 39 | + if(NOT EXISTS "${_op_dir}/op_host") | ||
| 40 | + continue() | ||
| 41 | + endif() | ||
| 42 | + get_filename_component(_op_name "${_op_dir}" NAME) | ||
| 43 | + | ||
| 44 | + # 白名单过滤 (与 setup.py _PARADIGM_DIRS 语义对账: 仅 pro/tensor 两棵树被 glob, 历史目录天然不参与) | ||
| 45 | + if(_explicit_ops AND NOT _op_name IN_LIST _explicit_ops) | ||
| 46 | + continue() | ||
| 47 | + endif() | ||
| 48 | + | ||
| 49 | + list(APPEND _OP_LIST ${_op_name}) | ||
| 50 | + list(APPEND _OP_DIR_LIST ${_op_dir}) | ||
| 51 | + endforeach() | ||
| 52 | + | ||
| 53 | + # 孤儿检测: 有 op_host 但缺算子级 CMakeLists(dispatcher)的算子不可见, 违约即报错 | ||
| 54 | + file(GLOB _orphan_op_host_files | ||
| 55 | + "${CMAKE_CURRENT_SOURCE_DIR}/ops/pro/*/op_host/CMakeLists.txt" | ||
| 56 | + "${CMAKE_CURRENT_SOURCE_DIR}/ops/pro/*/*/op_host/CMakeLists.txt" | ||
| 57 | + "${CMAKE_CURRENT_SOURCE_DIR}/ops/pro/*/*/*/op_host/CMakeLists.txt" | ||
| 58 | + "${CMAKE_CURRENT_SOURCE_DIR}/ops/tensor/*/op_host/CMakeLists.txt" | ||
| 59 | + "${CMAKE_CURRENT_SOURCE_DIR}/ops/tensor/*/*/op_host/CMakeLists.txt" | ||
| 60 | + "${CMAKE_CURRENT_SOURCE_DIR}/ops/tensor/*/*/*/op_host/CMakeLists.txt") | ||
| 61 | + foreach(_orphan_file ${_orphan_op_host_files}) | ||
| 62 | + get_filename_component(_orphan_op_host_dir "${_orphan_file}" DIRECTORY) | ||
| 63 | + get_filename_component(_orphan_op_dir "${_orphan_op_host_dir}" DIRECTORY) | ||
| 64 | + if(NOT EXISTS "${_orphan_op_dir}/CMakeLists.txt") | ||
| 65 | + get_filename_component(_orphan_op_name "${_orphan_op_dir}" NAME) | ||
| 66 | + if(NOT _explicit_ops OR _orphan_op_name IN_LIST _explicit_ops) | ||
| 67 | + message(FATAL_ERROR "operator '${_orphan_op_name}' has op_host but is missing " | ||
| 68 | + "${_orphan_op_dir}/CMakeLists.txt (op-level dispatcher required; " | ||
| 69 | + "see flex_attention/CMakeLists.txt for the template)") | ||
| 70 | + endif() | ||
| 71 | + endif() | ||
| 72 | + endforeach() | ||
| 73 | + | ||
| 74 | + list(REMOVE_DUPLICATES _OP_LIST) | ||
| 75 | + list(REMOVE_DUPLICATES _OP_DIR_LIST) | ||
| 76 | + list(SORT _OP_LIST) | ||
| 77 | + list(SORT _OP_DIR_LIST) | ||
| 78 | + if(NOT _OP_LIST) | ||
| 79 | + message(FATAL_ERROR "gym_op_discovery: no operator found under ops/{pro,tensor} (explicit ops: '${_explicit_ops}')") | ||
| 80 | + endif() | ||
| 81 | + message(STATUS "gym ops discovered: ${_OP_LIST}") | ||
| 82 | + set(${OP_LIST} ${_OP_LIST} PARENT_SCOPE) | ||
| 83 | + set(${OP_DIR_LIST} ${_OP_DIR_LIST} PARENT_SCOPE) | ||
| 84 | +endfunction() | ||
| 85 | + | ||
| 86 | +macro(add_op_to_compiled_list) | ||
| 87 | + set(COMPILED_OPS ${COMPILED_OPS} ${OP_NAME} CACHE STRING "Compiled Ops" FORCE) | ||
| 88 | + set(COMPILED_OP_DIRS ${COMPILED_OP_DIRS} ${PARENT_DIR} CACHE STRING "Compiled Ops Dirs" FORCE) | ||
| 89 | +endmacro() | ||
| 90 | + | ||
| 91 | +macro(require_pypto_pro op_name) | ||
| 92 | + # 获取 pypto_pro 可用状态 | ||
| 93 | + get_property(_pypto_pro_checked GLOBAL PROPERTY PYPTO_PRO_CHECKED) | ||
| 94 | + if (NOT _pypto_pro_checked) | ||
| 95 | + execute_process( | ||
| 96 | + COMMAND ${Python3_EXECUTABLE} -c | ||
| 97 | + "import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('pypto_pro') else 1)" | ||
| 98 | + RESULT_VARIABLE _pypto_pro_check_result | ||
| 99 | + OUTPUT_QUIET | ||
| 100 | + ERROR_QUIET | ||
| 101 | + ) | ||
| 102 | + if (_pypto_pro_check_result EQUAL 0) | ||
| 103 | + set_property(GLOBAL PROPERTY PYPTO_PRO_AVAILABLE TRUE) | ||
| 104 | + else() | ||
| 105 | + set_property(GLOBAL PROPERTY PYPTO_PRO_AVAILABLE FALSE) | ||
| 106 | + endif() | ||
| 107 | + set_property(GLOBAL PROPERTY PYPTO_PRO_CHECKED TRUE) | ||
| 108 | + endif() | ||
| 109 | + | ||
| 110 | + get_property(_pypto_pro_available GLOBAL PROPERTY PYPTO_PRO_AVAILABLE) | ||
| 111 | + if (NOT _pypto_pro_available) | ||
| 112 | + message(FATAL_ERROR "pypto_pro is unavailable in ${Python3_EXECUTABLE}; operator ${op_name} requires it.") | ||
| 113 | + endif() | ||
| 114 | + | ||
| 115 | + unset(_pypto_pro_checked) | ||
| 116 | + unset(_pypto_pro_check_result) | ||
| 117 | + unset(_pypto_pro_available) | ||
| 118 | +endmacro() | ||
| 119 | + | ||
| 120 | +# enable_pypto_kernel(<op_file>): configure 期跑 pypto codegen 生成 tiling/tilingkey 头 | ||
| 121 | +function(enable_pypto_kernel op_file) | ||
| 122 | + set(_compute_units ${ASCEND_COMPUTE_UNIT}) | ||
| 123 | + list(FILTER _compute_units INCLUDE REGEX ".+") | ||
| 124 | + if (NOT _compute_units) | ||
| 125 | + message(FATAL_ERROR "enable_pypto_kernel: ASCEND_COMPUTE_UNIT is empty") | ||
| 126 | + endif () | ||
| 127 | + list(GET _compute_units 0 _soc_unit) | ||
| 128 | + | ||
| 129 | + set(_gen "${ASCEND_BINARY_OUT_DIR}/${_soc_unit}/${op_file}_pypto_gen") | ||
| 130 | + set(_py "${CMAKE_CURRENT_SOURCE_DIR}/../op_kernel/${op_file}.py") | ||
| 131 | + if (NOT EXISTS ${_py}) | ||
| 132 | + message(FATAL_ERROR "enable_pypto_kernel: kernel python file not found: ${_py}") | ||
| 133 | + endif () | ||
| 134 | + | ||
| 135 | + message(STATUS "pypto codegen: ${op_file} -> ${_gen}") | ||
| 136 | + execute_process( | ||
| 137 | + COMMAND ${Python3_EXECUTABLE} ${PYPTO_GYM_SRC_DIR}/cmake/scripts/pypto_codegen.py | ||
| 138 | + --py-file "${_py}" --out-dir "${_gen}" --op-file "${op_file}" --soc "${_soc_unit}" | ||
| 139 | + RESULT_VARIABLE _rc) | ||
| 140 | + if (NOT _rc EQUAL 0) | ||
| 141 | + message(FATAL_ERROR "pypto codegen failed for ${op_file} (exit ${_rc})") | ||
| 142 | + endif () | ||
| 143 | + | ||
| 144 | + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${_py}) | ||
| 145 | + set(PYPTO_GEN_DIR ${_gen} PARENT_SCOPE) | ||
| 146 | + set(${op_file}_pypto_enabled TRUE CACHE INTERNAL "pypto-enabled kernel ${op_file}") | ||
| 147 | + set(${op_file}_pypto_gen_dir ${_gen} CACHE INTERNAL "pypto gen dir for ${op_file}") | ||
| 148 | + set_property(GLOBAL APPEND PROPERTY PYPTO_ENABLED_OPS ${op_file}) | ||
| 149 | +endfunction() | ||
| 150 | + | ||
| 151 | +function(add_ops_compile_options) | ||
| 152 | + cmake_parse_arguments(OP_COMPILE "" "OP_NAME" "COMPUTE_UNIT;OPTIONS" ${ARGN}) | ||
| 153 | + if(NOT OP_COMPILE_OPTIONS) | ||
| 154 | + return() | ||
| 155 | + endif() | ||
| 156 | + execute_process(COMMAND ${Python3_EXECUTABLE} ${GYM_UTIL_SCRIPT_DIR}/ascendc_gen_options.py | ||
| 157 | + ${ASCEND_CUSTOM_OPTIONS} ${OP_COMPILE_OP_NAME} | ||
| 158 | + ${OP_COMPILE_COMPUTE_UNIT} ${OP_COMPILE_OPTIONS} | ||
| 159 | + RESULT_VARIABLE EXEC_RESULT OUTPUT_QUIET ERROR_QUIET) | ||
| 160 | + if (EXEC_RESULT) | ||
| 161 | + message(FATAL_ERROR "Error: add ops compile options failed for ${OP_COMPILE_OP_NAME}!") | ||
| 162 | + endif () | ||
| 163 | +endfunction() | ||
| 164 | + | ||
| 165 | +function(add_ops_tiling_keys) | ||
| 166 | + cmake_parse_arguments(OP_COMPILE "" "OP_NAME" "COMPUTE_UNIT" "TILING_KEYS" ${ARGN}) | ||
| 167 | + if(NOT OP_COMPILE_TILING_KEYS) | ||
| 168 | + return() | ||
| 169 | + endif() | ||
| 170 | + list(JOIN OP_COMPILE_TILING_KEYS "," STRING_TILING_KEYS) | ||
| 171 | + add_ops_compile_options(OP_NAME ${OP_COMPILE_OP_NAME} OPTIONS --tiling_key=${STRING_TILING_KEYS}) | ||
| 172 | +endfunction() | ||
| 173 | + | ||
| 174 | +function(add_compile_cmd_target) | ||
| 175 | + cmake_parse_arguments(CMD "" "COMPUTE_UNIT" "" ${ARGN}) | ||
| 176 | + | ||
| 177 | + set(OP_DEBUG_CONFIG_OPTION --opc-config-file ${ASCEND_CUSTOM_OPC_OPTIONS}) | ||
| 178 | + set(OP_TILING_KEY_OPTION --kernel_template_input) | ||
| 179 | + | ||
| 180 | + set(_OUT_DIR ${ASCEND_BINARY_OUT_DIR}/${CMD_COMPUTE_UNIT}) | ||
| 181 | + set(GEN_OUT_DIR ${_OUT_DIR}/gen) | ||
| 182 | + set(COMPILE_CMD_TARGET generate_compile_cmd_${CMD_COMPUTE_UNIT}) | ||
| 183 | + | ||
| 184 | + add_custom_target(${COMPILE_CMD_TARGET} ALL | ||
| 185 | + COMMAND ${CMAKE_COMMAND} -E make_directory ${GEN_OUT_DIR} | ||
| 186 | + COMMAND ${Python3_EXECUTABLE} ${GYM_UTIL_SCRIPT_DIR}/ascendc_bin_param_build.py | ||
| 187 | + ${ASCEND_AUTOGEN_DIR}/aic-${CMD_COMPUTE_UNIT}-ops-info.ini | ||
| 188 | + ${GEN_OUT_DIR} ${CMD_COMPUTE_UNIT} ${OP_TILING_KEY_OPTION} ${OP_DEBUG_CONFIG_OPTION} | ||
| 189 | + COMMAND ${Python3_EXECUTABLE} ${GYM_UTIL_SCRIPT_DIR}/ascendc_bin_param_build.py | ||
| 190 | + ${ASCEND_AUTOGEN_DIR}/inner/aic-${CMD_COMPUTE_UNIT}-ops-info.ini | ||
| 191 | + ${GEN_OUT_DIR} ${CMD_COMPUTE_UNIT} ${OP_TILING_KEY_OPTION} ${OP_DEBUG_CONFIG_OPTION} | ||
| 192 | + COMMAND ${Python3_EXECUTABLE} ${GYM_UTIL_SCRIPT_DIR}/ascendc_bin_param_build.py | ||
| 193 | + ${ASCEND_AUTOGEN_DIR}/exc/aic-${CMD_COMPUTE_UNIT}-ops-info.ini | ||
| 194 | + ${GEN_OUT_DIR} ${CMD_COMPUTE_UNIT} ${OP_TILING_KEY_OPTION} ${OP_DEBUG_CONFIG_OPTION} | ||
| 195 | + ) | ||
| 196 | + add_dependencies(${COMPILE_CMD_TARGET} opbuild_gen_default opbuild_gen_inner opbuild_gen_exc) | ||
| 197 | + add_dependencies(generate_compile_cmd ${COMPILE_CMD_TARGET}) | ||
| 198 | +endfunction() | ||
| 199 | + | ||
| 200 | +# 源码 staging: 整目录拷贝(与 ops-transformer add_ops_src_copy 语义一致) + stamp | ||
| 201 | +function(add_ops_src_copy) | ||
| 202 | + cmake_parse_arguments(SRC_COPY "" "TARGET_NAME;SRC;DST;COMPUTE_UNIT" "" ${ARGN}) | ||
| 203 | + set(_stamp ${SRC_COPY_DST}/.${SRC_COPY_TARGET_NAME}.done) | ||
| 204 | + add_custom_command(OUTPUT ${_stamp} | ||
| 205 | + COMMAND ${CMAKE_COMMAND} -E copy_directory ${SRC_COPY_SRC} ${SRC_COPY_DST} | ||
| 206 | + COMMAND ${CMAKE_COMMAND} -E touch ${_stamp} | ||
| 207 | + DEPENDS ${SRC_COPY_SRC} | ||
| 208 | + VERBATIM) | ||
| 209 | + add_custom_target(${SRC_COPY_TARGET_NAME} ALL DEPENDS ${_stamp}) | ||
| 210 | +endfunction() | ||
| 211 | + | ||
| 212 | +# kernel 二进制编译目标: pypto 算子按 ground-truth 命令链执行 opc (asc_opc) | ||
| 213 | +function(add_bin_compile_target) | ||
| 214 | + cmake_parse_arguments(BINARY "" "COMPUTE_UNIT" "OP_INFO" ${ARGN}) | ||
| 215 | + | ||
| 216 | + set(_OUT_DIR ${ASCEND_BINARY_OUT_DIR}/${BINARY_COMPUTE_UNIT}) | ||
| 217 | + set(BIN_OUT_DIR ${_OUT_DIR}/bin) | ||
| 218 | + set(GEN_OUT_DIR ${_OUT_DIR}/gen) | ||
| 219 | + set(SRC_OUT_DIR ${_OUT_DIR}/src) | ||
| 220 | + file(MAKE_DIRECTORY ${BIN_OUT_DIR}) | ||
| 221 | + | ||
| 222 | + foreach(_op_info ${BINARY_OP_INFO}) | ||
| 223 | + get_filename_component(_op_name "${_op_info}" NAME) | ||
| 224 | + set(${_op_name}_dir ${_op_info}) | ||
| 225 | + endforeach() | ||
| 226 | + | ||
| 227 | + set(_ops_target_list) | ||
| 228 | + file(GLOB compile_scripts ${GEN_OUT_DIR}/*.sh) | ||
| 229 | + | ||
| 230 | + foreach(bin_script ${compile_scripts}) | ||
| 231 | + get_filename_component(bin_file ${bin_script} NAME_WE) | ||
| 232 | + string(REPLACE "-" ";" bin_sep ${bin_file}) | ||
| 233 | + list(GET bin_sep 0 op_type) | ||
| 234 | + list(GET bin_sep 1 op_file) | ||
| 235 | + list(GET bin_sep 2 op_index) | ||
| 236 | + | ||
| 237 | + if (NOT DEFINED ${op_file}_dir) | ||
| 238 | + continue() | ||
| 239 | + endif () | ||
| 240 | + | ||
| 241 | + set(OP_TARGET_NAME ${op_file}_${BINARY_COMPUTE_UNIT}) | ||
| 242 | + if (TARGET ${OP_TARGET_NAME}) | ||
| 243 | + # 同算子多 dtype 脚本共享一组 staging 目标 | ||
| 244 | + else () | ||
| 245 | + if (NOT ${op_file}_pypto_enabled) | ||
| 246 | + message(FATAL_ERROR | ||
| 247 | + "op '${op_file}' is not pypto-enabled: gym currently supports PyPTO kernels only") | ||
| 248 | + endif () | ||
| 249 | + add_custom_target(${OP_TARGET_NAME}) | ||
| 250 | + add_dependencies(ops_gym_kernel ${OP_TARGET_NAME}) | ||
| 251 | + list(APPEND _ops_target_list ${OP_TARGET_NAME}) | ||
| 252 | + | ||
| 253 | + set(OP_SRC_OUT_DIR ${SRC_OUT_DIR}/${op_file}) | ||
| 254 | + set(OP_BIN_OUT_DIR ${BIN_OUT_DIR}/${op_file}) | ||
| 255 | + file(MAKE_DIRECTORY ${OP_SRC_OUT_DIR}) | ||
| 256 | + | ||
| 257 | + # vendors staging: kernel 二进制与配置(COMPONENT 供 CPack 收集) | ||
| 258 | + set(_kernel_install_dir packages/vendors/${VENDOR_NAME}/op_impl/ai_core/tbe/kernel) | ||
| 259 | + install(DIRECTORY ${OP_BIN_OUT_DIR} | ||
| 260 | + DESTINATION ${_kernel_install_dir}/${BINARY_COMPUTE_UNIT} OPTIONAL | ||
| 261 | + COMPONENT ${VENDOR_NAME}) | ||
| 262 | + install(FILES ${BIN_OUT_DIR}/${op_file}.json | ||
| 263 | + DESTINATION ${_kernel_install_dir}/config/${BINARY_COMPUTE_UNIT} OPTIONAL | ||
| 264 | + COMPONENT ${VENDOR_NAME}) | ||
| 265 | + | ||
| 266 | + add_ops_src_copy( | ||
| 267 | + TARGET_NAME ${OP_TARGET_NAME}_src_copy | ||
| 268 | + SRC ${${op_file}_dir} | ||
| 269 | + DST ${OP_SRC_OUT_DIR} | ||
| 270 | + COMPUTE_UNIT ${BINARY_COMPUTE_UNIT}) | ||
| 271 | + | ||
| 272 | + set(_pypto_install_stamp ${OP_SRC_OUT_DIR}/op_kernel/.pypto_install.done) | ||
| 273 | + add_custom_command(OUTPUT ${_pypto_install_stamp} | ||
| 274 | + COMMAND ${CMAKE_COMMAND} -E copy_directory ${${op_file}_pypto_gen_dir} ${OP_SRC_OUT_DIR}/op_kernel | ||
| 275 | + COMMAND ${CMAKE_COMMAND} -E touch ${_pypto_install_stamp} | ||
| 276 | + DEPENDS ${OP_TARGET_NAME}_src_copy | ||
| 277 | + VERBATIM) | ||
| 278 | + add_custom_target(${OP_TARGET_NAME}_pypto_install DEPENDS ${_pypto_install_stamp}) | ||
| 279 | + | ||
| 280 | + set(DYNAMIC_PY_FILE ${OP_SRC_OUT_DIR}/${op_type}.py) | ||
| 281 | + add_custom_command(OUTPUT ${DYNAMIC_PY_FILE} | ||
| 282 | + COMMAND cp -rf ${ASCEND_IMPL_OUT_DIR}/dynamic/${op_file}.py ${DYNAMIC_PY_FILE}) | ||
| 283 | + add_custom_target(${OP_TARGET_NAME}_py_copy DEPENDS ${DYNAMIC_PY_FILE}) | ||
| 284 | + | ||
| 285 | + add_custom_command(OUTPUT ${OP_BIN_OUT_DIR} COMMAND mkdir -p ${OP_BIN_OUT_DIR}) | ||
| 286 | + add_custom_target(${OP_TARGET_NAME}_mkdir DEPENDS ${OP_BIN_OUT_DIR}) | ||
| 287 | + endif () | ||
| 288 | + | ||
| 289 | + set(_BUILD_FLAG ${GEN_OUT_DIR}/${OP_TARGET_NAME}_${op_index}.done) | ||
| 290 | + # TILINGKEY_PAR_COMPILE/BIN_FILENAME_HASHED 由 CANN 编译工具链消费 | ||
| 291 | + # (BIN_FILENAME_HASHED=1 即 <OpType>_<md5>.o 哈希文件名来源, ascendc_common_utility.py) | ||
| 292 | + set(_BUILD_COMMAND export TILINGKEY_PAR_COMPILE=1 &&) | ||
| 293 | + list(APPEND _BUILD_COMMAND export BIN_FILENAME_HASHED=1 &&) | ||
| 294 | + list(APPEND _BUILD_COMMAND bash ${bin_script} ${SRC_OUT_DIR}/${op_file}/${op_type}.py ${OP_BIN_OUT_DIR}) | ||
| 295 | + if(CMAKE_GENERATOR MATCHES "Unix Makefiles") | ||
| 296 | + list(APPEND _BUILD_COMMAND && echo $(MAKE)) | ||
| 297 | + endif() | ||
| 298 | + | ||
| 299 | + add_custom_command(OUTPUT ${_BUILD_FLAG} | ||
| 300 | + COMMAND ${_BUILD_COMMAND} | ||
| 301 | + COMMAND touch ${_BUILD_FLAG} | ||
| 302 | + WORKING_DIRECTORY ${GEN_OUT_DIR}) | ||
| 303 | + add_custom_target(${OP_TARGET_NAME}_${op_index} DEPENDS ${_BUILD_FLAG}) | ||
| 304 | + add_dependencies(${OP_TARGET_NAME}_${op_index} | ||
| 305 | + ${OP_TARGET_NAME}_src_copy ${OP_TARGET_NAME}_py_copy ${OP_TARGET_NAME}_mkdir | ||
| 306 | + ${OP_TARGET_NAME}_pypto_install generate_compile_cmd) | ||
| 307 | + add_dependencies(${OP_TARGET_NAME} ${OP_TARGET_NAME}_${op_index}) | ||
| 308 | + endforeach() | ||
| 309 | + | ||
| 310 | + if (_ops_target_list) | ||
| 311 | + set(OPS_CONFIG_TARGET ops_config_${BINARY_COMPUTE_UNIT}) | ||
| 312 | + set(BINARY_INFO_CONFIG_FILE ${BIN_OUT_DIR}/binary_info_config.json) | ||
| 313 | + add_custom_command(OUTPUT ${BINARY_INFO_CONFIG_FILE} | ||
| 314 | + COMMAND ${Python3_EXECUTABLE} ${GYM_UTIL_SCRIPT_DIR}/ascendc_ops_config.py -p ${BIN_OUT_DIR} -s ${BINARY_COMPUTE_UNIT}) | ||
| 315 | + add_custom_target(${OPS_CONFIG_TARGET} DEPENDS ${BINARY_INFO_CONFIG_FILE}) | ||
| 316 | + add_dependencies(ops_gym_config ${OPS_CONFIG_TARGET}) | ||
| 317 | + foreach(_op_target ${_ops_target_list}) | ||
| 318 | + add_dependencies(${OPS_CONFIG_TARGET} ${_op_target}) | ||
| 319 | + endforeach() | ||
| 320 | + set(_kernel_cfg_dir packages/vendors/${VENDOR_NAME}/op_impl/ai_core/tbe/kernel/config/${BINARY_COMPUTE_UNIT}) | ||
| 321 | + install(FILES ${BINARY_INFO_CONFIG_FILE} DESTINATION ${_kernel_cfg_dir} OPTIONAL | ||
| 322 | + COMPONENT ${VENDOR_NAME}) | ||
| 323 | + install(FILES ${BIN_OUT_DIR}/relocatable_kernel_info_config.json | ||
| 324 | + DESTINATION ${_kernel_cfg_dir} OPTIONAL COMPONENT ${VENDOR_NAME}) | ||
| 325 | + endif () | ||
| 326 | +endfunction() | ||
| @@ -0,0 +1,141 @@ | |||
| 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 | +# gym host 侧源收集宏: 算子 op_host/CMakeLists.txt 消费的宏集合. | ||
| 12 | +# 源统一登记到全局属性, 编译目标(ophost_gym_*_obj / 三 .so)在 custom_build.cmake 顶层统一创建. | ||
| 13 | + | ||
| 14 | +function(extract_ops_name SOURCE_DIR OUTPUT_VAR) | ||
| 15 | + file(GLOB_RECURSE OP_DEF_FILES ${SOURCE_DIR}/*_def*.cpp) | ||
| 16 | + foreach(OP_DEF_FILE ${OP_DEF_FILES}) | ||
| 17 | + get_filename_component(OP_DEF_NAME ${OP_DEF_FILE} NAME_WE) | ||
| 18 | + string(REGEX REPLACE "_def$" "" OP_NAME_TMP ${OP_DEF_NAME}) | ||
| 19 | + set(${OUTPUT_VAR} ${OP_NAME_TMP} PARENT_SCOPE) | ||
| 20 | + endforeach() | ||
| 21 | +endfunction() | ||
| 22 | + | ||
| 23 | +# add_modules_sources(OPTYPE <op_types> ACLNNTYPE <aclnn|aclnn_inner|aclnn_exclude> [ACLNN_EXTRA_VERSION ...]) | ||
| 24 | +# def 编入 op_build 反射 .so; infershape/手写 opapi 源登记到全局属性. | ||
| 25 | +macro(add_modules_sources) | ||
| 26 | + set(multiValueArgs OPTYPE ACLNNTYPE ACLNN_EXTRA_VERSION) | ||
| 27 | + cmake_parse_arguments(MODULE "" "" "${multiValueArgs}" ${ARGN}) | ||
| 28 | + set(SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}) | ||
| 29 | + | ||
| 30 | + list(LENGTH MODULE_OPTYPE OpTypeLen) | ||
| 31 | + if(NOT OpTypeLen) | ||
| 32 | + file(GLOB OPDEF_SRCS ${SOURCE_DIR}/*_def*.cpp) | ||
| 33 | + if (OPDEF_SRCS) | ||
| 34 | + message(FATAL_ERROR | ||
| 35 | + "Should Manually specify aclnn/aclnn_inner/aclnn_exclude\n" | ||
| 36 | + "usage: add_modules_sources(OPTYPE optypes ACLNNTYPE aclnntypes)") | ||
| 37 | + endif() | ||
| 38 | + endif() | ||
| 39 | + | ||
| 40 | + math(EXPR _idx "${OpTypeLen} - 1") | ||
| 41 | + if(_idx GREATER -1) | ||
| 42 | + foreach(i RANGE ${_idx}) | ||
| 43 | + list(GET MODULE_OPTYPE ${i} _op_type) | ||
| 44 | + list(GET MODULE_ACLNNTYPE ${i} _aclnn_type) | ||
| 45 | + file(GLOB _def_srcs ${SOURCE_DIR}/${_op_type}_def*.cpp) | ||
| 46 | + if(_def_srcs) | ||
| 47 | + if(_aclnn_type STREQUAL "aclnn" AND TARGET op_host_aclnn) | ||
| 48 | + target_sources(op_host_aclnn PRIVATE ${_def_srcs}) | ||
| 49 | + elseif(_aclnn_type STREQUAL "aclnn_inner" AND TARGET op_host_aclnnInner) | ||
| 50 | + target_sources(op_host_aclnnInner PRIVATE ${_def_srcs}) | ||
| 51 | + elseif(_aclnn_type STREQUAL "aclnn_exclude" AND TARGET op_host_aclnnExc) | ||
| 52 | + target_sources(op_host_aclnnExc PRIVATE ${_def_srcs}) | ||
| 53 | + else() | ||
| 54 | + message(FATAL_ERROR "ACLNN TYPE UNSUPPORTED: ${_aclnn_type}") | ||
| 55 | + endif() | ||
| 56 | + endif() | ||
| 57 | + set_property(GLOBAL APPEND PROPERTY GYM_ACLNN_TYPE_${_aclnn_type} ${_op_type}) | ||
| 58 | + | ||
| 59 | + file(GLOB _infer_srcs ${SOURCE_DIR}/*_infershape*.cpp) | ||
| 60 | + if(_infer_srcs) | ||
| 61 | + set_property(GLOBAL APPEND PROPERTY GYM_INFER_SRCS ${_infer_srcs}) | ||
| 62 | + endif() | ||
| 63 | + # 手写 aclnn 通道: 旧结构 op_host/op_api/ 与新结构同级 op_api/ 均发现 | ||
| 64 | + file(GLOB _opapi_srcs ${SOURCE_DIR}/op_api/*.cpp) | ||
| 65 | + if(NOT _opapi_srcs) | ||
| 66 | + file(GLOB _opapi_srcs ${SOURCE_DIR}/../op_api/*.cpp) | ||
| 67 | + endif() | ||
| 68 | + if(_opapi_srcs) | ||
| 69 | + set_property(GLOBAL APPEND PROPERTY GYM_OPAPI_SRCS ${_opapi_srcs}) | ||
| 70 | + endif() | ||
| 71 | + endforeach() | ||
| 72 | + endif() | ||
| 73 | +endmacro() | ||
| 74 | + | ||
| 75 | +macro(add_modules_sources_with_soc) | ||
| 76 | + add_modules_sources(${ARGN}) | ||
| 77 | +endmacro() | ||
| 78 | + | ||
| 79 | +# tiling 源收集(在 enable_pypto_kernel 之后调用, PYPTO_GEN_DIR 指向生成头目录) | ||
| 80 | +macro(add_tiling_modules) | ||
| 81 | + file(GLOB _tiling_srcs ${CMAKE_CURRENT_SOURCE_DIR}/*_tiling*.cpp) | ||
| 82 | + if(_tiling_srcs) | ||
| 83 | + set_property(GLOBAL APPEND PROPERTY GYM_TILING_SRCS ${_tiling_srcs}) | ||
| 84 | + endif() | ||
| 85 | + file(GLOB _sub_tiling_srcs ${CMAKE_CURRENT_SOURCE_DIR}/op_tiling/*.cpp) | ||
| 86 | + if(_sub_tiling_srcs) | ||
| 87 | + set_property(GLOBAL APPEND PROPERTY GYM_TILING_SRCS ${_sub_tiling_srcs}) | ||
| 88 | + endif() | ||
| 89 | + if(DEFINED PYPTO_GEN_DIR) | ||
| 90 | + set_property(GLOBAL APPEND PROPERTY GYM_PYPTO_GEN_DIRS ${PYPTO_GEN_DIR}) | ||
| 91 | + # tiling 布局校验(configure 期执行, codegen 已由 enable_pypto_kernel 完成). | ||
| 92 | + # 手写 TilingData 与 kernel dataclass 字段级 diff, 不一致即 FATAL_ERROR; | ||
| 93 | + # 一致则登记布局核对程序源(构建期编译并执行)供 custom_build.cmake 消费. | ||
| 94 | + get_filename_component(_tl_op_file ${PYPTO_GEN_DIR} NAME) | ||
| 95 | + string(REGEX REPLACE "_pypto_gen$" "" _tl_op_file ${_tl_op_file}) | ||
| 96 | + set(_tl_emit_dir ${CMAKE_BINARY_DIR}/tiling_check) | ||
| 97 | + execute_process( | ||
| 98 | + COMMAND ${Python3_EXECUTABLE} ${PYPTO_GYM_SRC_DIR}/cmake/scripts/tiling_layout_check.py | ||
| 99 | + --gen-dir ${PYPTO_GEN_DIR} | ||
| 100 | + --host-dir ${CMAKE_CURRENT_SOURCE_DIR} | ||
| 101 | + --op-file ${_tl_op_file} | ||
| 102 | + --emit-dir ${_tl_emit_dir} | ||
| 103 | + RESULT_VARIABLE _tl_rc) | ||
| 104 | + if(NOT _tl_rc EQUAL 0) | ||
| 105 | + message(FATAL_ERROR | ||
| 106 | + "tiling layout check failed for ${_tl_op_file}: " | ||
| 107 | + "handwritten TilingData != kernel dataclass (see diff above)") | ||
| 108 | + endif() | ||
| 109 | + set_property(GLOBAL APPEND PROPERTY GYM_TILING_CHECK_SRCS | ||
| 110 | + ${_tl_emit_dir}/${_tl_op_file}_tiling_layout_check.cpp) | ||
| 111 | + endif() | ||
| 112 | +endmacro() | ||
| 113 | + | ||
| 114 | +function(add_opapi_modules) | ||
| 115 | +endfunction() | ||
| 116 | + | ||
| 117 | +function(add_infer_modules) | ||
| 118 | +endfunction() | ||
| 119 | + | ||
| 120 | +# ---------------------------------------- op_build 反射载体 ---------------------------------------- | ||
| 121 | +# 三个 stub .so: def.cpp 经 add_modules_sources 按通道收集于此, 供 op_build 反射生成 aclnn/ops-info. | ||
| 122 | +# 顺序约束: 必须在算子 op_host 接入(CMakeLists 顶层 add_subdirectory)之前创建. | ||
| 123 | +add_library(op_host_aclnn SHARED EXCLUDE_FROM_ALL) | ||
| 124 | +add_library(op_host_aclnnInner SHARED EXCLUDE_FROM_ALL) | ||
| 125 | +add_library(op_host_aclnnExc SHARED EXCLUDE_FROM_ALL) | ||
| 126 | +foreach(_aclnn_lib op_host_aclnn op_host_aclnnInner op_host_aclnnExc) | ||
| 127 | + target_include_directories(${_aclnn_lib} PRIVATE | ||
| 128 | + ${ASCEND_CANN_PACKAGE_PATH}/include | ||
| 129 | + ${ASCEND_CANN_PACKAGE_PATH}/include/exe_graph | ||
| 130 | + ${ASCEND_CANN_PACKAGE_PATH}/include/external | ||
| 131 | + ${ASCEND_CANN_PACKAGE_PATH}/include/platform | ||
| 132 | + ${ASCEND_CANN_PACKAGE_PATH}/include/experiment/msprof | ||
| 133 | + ${ASCEND_CANN_PACKAGE_PATH}/include/experiment/runtime) | ||
| 134 | + target_link_directories(${_aclnn_lib} PRIVATE | ||
| 135 | + ${ASCEND_CANN_PACKAGE_PATH}/lib64 | ||
| 136 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/lib64) | ||
| 137 | + target_link_libraries(${_aclnn_lib} PRIVATE | ||
| 138 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/lib64/libexe_graph.so | ||
| 139 | + ${ASCEND_CANN_PACKAGE_PATH}/${SYSTEM_PREFIX}/lib64/libregister.so | ||
| 140 | + ${ASCEND_CANN_PACKAGE_PATH}/lib64/libc_sec.so) | ||
| 141 | +endforeach() | ||
| @@ -0,0 +1,47 @@ | |||
| 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 | +# cann/cmake 内部函数依赖该变量;未显式配置时将缓存放入源码树,实现与 prepare 流程共用。 | ||
| 12 | +if (CANN_3RD_LIB_PATH) | ||
| 13 | + get_filename_component(CANN_3RD_LIB_PATH "${CANN_3RD_LIB_PATH}" REALPATH) | ||
| 14 | +elseif (DEFINED ENV{CANN_3RD_LIB_PATH}) | ||
| 15 | + get_filename_component(CANN_3RD_LIB_PATH "$ENV{CANN_3RD_LIB_PATH}" REALPATH) | ||
| 16 | +else() | ||
| 17 | + # 因构建 run 包场景存在 prepare 流程, 此处控制下载三方件到源码树目录下, 实现共用 | ||
| 18 | + get_filename_component(CANN_3RD_LIB_PATH "${CMAKE_SOURCE_DIR}/third_party" REALPATH) | ||
| 19 | +endif() | ||
| 20 | + | ||
| 21 | +if (NOT PROJECT_SOURCE_DIR) | ||
| 22 | + set(CANN_CMAKE_TAG "master-058") | ||
| 23 | + if(CANN_3RD_LIB_PATH AND IS_DIRECTORY "${CANN_3RD_LIB_PATH}/cann-cmake") | ||
| 24 | + include("${CANN_3RD_LIB_PATH}/cann-cmake/function/prepare.cmake") | ||
| 25 | + else() | ||
| 26 | + include(FetchContent) | ||
| 27 | + if(CANN_3RD_LIB_PATH AND EXISTS "${CANN_3RD_LIB_PATH}/cmake-${CANN_CMAKE_TAG}.tar.gz") | ||
| 28 | + FetchContent_Declare( | ||
| 29 | + cann-cmake | ||
| 30 | + URL "${CANN_3RD_LIB_PATH}/cmake-${CANN_CMAKE_TAG}.tar.gz" | ||
| 31 | + URL_HASH SHA256=43fb1a2cb376192bb307bd4003c0c4bd82ab66a7eb62d3ddfa9f70f988b7ff18 | ||
| 32 | + ) | ||
| 33 | + else() | ||
| 34 | + FetchContent_Declare( | ||
| 35 | + cann-cmake | ||
| 36 | + GIT_REPOSITORY https://gitcode.com/cann/cmake.git | ||
| 37 | + GIT_TAG ${CANN_CMAKE_TAG} | ||
| 38 | + GIT_SHALLOW TRUE | ||
| 39 | + ) | ||
| 40 | + endif() | ||
| 41 | + FetchContent_GetProperties(cann-cmake) | ||
| 42 | + if(NOT cann-cmake_POPULATED) | ||
| 43 | + FetchContent_Populate(cann-cmake) | ||
| 44 | + endif() | ||
| 45 | + include("${cann-cmake_SOURCE_DIR}/function/prepare.cmake") | ||
| 46 | + endif() | ||
| 47 | +endif() | ||
| @@ -0,0 +1,55 @@ | |||
| 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 | +# gym 二次构建入口: 主 configure 期由 cmake/config.cmake 调用, | ||
| 13 | +# 以 PREPARE_BUILD=ON 再跑一次 cmake 并 make prepare_build, 产出 autogen 与 impl. | ||
| 14 | + | ||
| 15 | +CPU_NUM=$(($(grep -c "^processor" /proc/cpuinfo)*2)) | ||
| 16 | +JOB_NUM="-j${CPU_NUM}" | ||
| 17 | + | ||
| 18 | +while [[ $# -gt 0 ]]; do | ||
| 19 | + case $1 in | ||
| 20 | + -s) PATH_TO_SOURCE="$2"; shift 2 ;; | ||
| 21 | + -b) PATH_TO_BUILD="$2"; shift 2 ;; | ||
| 22 | + -p) ASCEND_CANN_PACKAGE_PATH="$2"; shift 2 ;; | ||
| 23 | + --autogen-dir) ASCEND_AUTOGEN_DIR="$2"; shift 2 ;; | ||
| 24 | + --binary-out-dir) ASCEND_BINARY_OUT_DIR="$2"; shift 2 ;; | ||
| 25 | + --impl-out-dir) ASCEND_IMPL_OUT_DIR="$2"; shift 2 ;; | ||
| 26 | + --op-build-tool) OP_BUILD_TOOL="$2"; shift 2 ;; | ||
| 27 | + --ascend-cmake-dir) ASCEND_CMAKE_DIR="$2"; shift 2 ;; | ||
| 28 | + --ascend-compute_unit) ASCEND_COMPUTE_UNIT="$2"; shift 2 ;; | ||
| 29 | + --ascend-op_name) ASCEND_OP_NAME="$2"; shift 2 ;; | ||
| 30 | + *) echo "unknown arg: $1"; exit 1 ;; | ||
| 31 | + esac | ||
| 32 | +done | ||
| 33 | + | ||
| 34 | +convert_string() { echo "$1" | sed 's/::/;/g'; } | ||
| 35 | + | ||
| 36 | +CONVERT_ASCEND_COMPUTE_UNIT="$(convert_string ${ASCEND_COMPUTE_UNIT})" | ||
| 37 | +CONVERT_ASCEND_OP_NAME="$(convert_string ${ASCEND_OP_NAME})" | ||
| 38 | + | ||
| 39 | +rm -rf "${PATH_TO_BUILD}" | ||
| 40 | +mkdir -p "${PATH_TO_BUILD}" | ||
| 41 | +cd "${PATH_TO_BUILD}" | ||
| 42 | + | ||
| 43 | +cmake ${PATH_TO_SOURCE} \ | ||
| 44 | + -DBUILD_OPEN_PROJECT=ON \ | ||
| 45 | + -DPREPARE_BUILD=ON \ | ||
| 46 | + -DCUSTOM_ASCEND_CANN_PACKAGE_PATH=${ASCEND_CANN_PACKAGE_PATH} \ | ||
| 47 | + -DASCEND_AUTOGEN_DIR=${ASCEND_AUTOGEN_DIR} \ | ||
| 48 | + -DASCEND_BINARY_OUT_DIR=${ASCEND_BINARY_OUT_DIR} \ | ||
| 49 | + -DASCEND_IMPL_OUT_DIR=${ASCEND_IMPL_OUT_DIR} \ | ||
| 50 | + -DOP_BUILD_TOOL=${OP_BUILD_TOOL} \ | ||
| 51 | + -DASCEND_CMAKE_DIR=${ASCEND_CMAKE_DIR} \ | ||
| 52 | + -DASCEND_COMPUTE_UNIT=${CONVERT_ASCEND_COMPUTE_UNIT} \ | ||
| 53 | + -DASCEND_OP_NAME=${CONVERT_ASCEND_OP_NAME} \ | ||
| 54 | + | ||
| 55 | +make ${JOB_NUM} prepare_build | ||
| @@ -0,0 +1,121 @@ | |||
| 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 | +# 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 | +PyPTO kernel codegen driver. | ||
| 13 | + | ||
| 14 | +This script is invoked from CMake configure stage for operators marked with enable_pypto_kernel(<op_file>). | ||
| 15 | +It runs host-side binary artifact preparation and copies all generated artifacts into --out-dir. | ||
| 16 | +""" | ||
| 17 | + | ||
| 18 | +import argparse | ||
| 19 | +import importlib.util | ||
| 20 | +import logging | ||
| 21 | +import shutil | ||
| 22 | +import sys | ||
| 23 | +from pathlib import Path | ||
| 24 | +from unittest.mock import MagicMock | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def _install_build_only_torch_stub(): | ||
| 28 | + """Stub runtime-only dependencies that binary codegen does not use.""" | ||
| 29 | + sys.modules["torch"] = MagicMock(name="torch") | ||
| 30 | + sys.modules["torch_npu"] = MagicMock(name="torch_npu") | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +# gym: soc -> pypto arch token, 显式传参(不依赖 prepare_binary_headers 的 3510 默认值) | ||
| 34 | +_ARCH_MAP = { | ||
| 35 | + "ascend950": "3510", | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def _load_legacy_kernel(py_file: Path): | ||
| 40 | + """Load the sole @pl.jit kernel for the legacy header-generation API.""" | ||
| 41 | + from pypto_pro.runtime.jit import _TileJitKernel | ||
| 42 | + | ||
| 43 | + spec = importlib.util.spec_from_file_location("_pypto_codegen_kernel_mod", py_file) | ||
| 44 | + if spec is None or spec.loader is None: | ||
| 45 | + raise RuntimeError(f"cannot load kernel module from {py_file}") | ||
| 46 | + module = importlib.util.module_from_spec(spec) | ||
| 47 | + sys.modules[spec.name] = module | ||
| 48 | + spec.loader.exec_module(module) | ||
| 49 | + | ||
| 50 | + kernels = [ | ||
| 51 | + value for value in vars(module).values() if isinstance(value, _TileJitKernel) | ||
| 52 | + ] | ||
| 53 | + if len(kernels) != 1: | ||
| 54 | + raise RuntimeError( | ||
| 55 | + f"kernel module '{py_file}' must define exactly one @pl.jit kernel, found {len(kernels)}" | ||
| 56 | + ) | ||
| 57 | + return kernels[0] | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def _prepare_binary_headers(py_file: Path, arch: str) -> Path: | ||
| 61 | + try: | ||
| 62 | + from pypto_pro.runtime.opc import prepare_binary_headers | ||
| 63 | + | ||
| 64 | + return Path(prepare_binary_headers(str(py_file), arch)).resolve() | ||
| 65 | + except Exception as error: | ||
| 66 | + logging.warning( | ||
| 67 | + "prepare_binary_headers failed, falling back to generate_binary_headers: %s", | ||
| 68 | + error, | ||
| 69 | + ) | ||
| 70 | + | ||
| 71 | + import pypto_pro.runtime.opc.pypto_compile as pto_compile | ||
| 72 | + | ||
| 73 | + return Path( | ||
| 74 | + pto_compile.generate_binary_headers(_load_legacy_kernel(py_file), arch) | ||
| 75 | + ).resolve() | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def main(): | ||
| 79 | + parser = argparse.ArgumentParser(description="PyPTO kernel codegen driver") | ||
| 80 | + parser.add_argument("--py-file", required=True, help="kernel python source file") | ||
| 81 | + parser.add_argument( | ||
| 82 | + "--out-dir", required=True, help="directory to place generated artifacts" | ||
| 83 | + ) | ||
| 84 | + parser.add_argument( | ||
| 85 | + "--op-file", required=True, help="op file stem (e.g. flash_attention_score_apt)" | ||
| 86 | + ) | ||
| 87 | + parser.add_argument( | ||
| 88 | + "--soc", required=True, help="soc version (e.g. ascend950), mapped to pypto arch" | ||
| 89 | + ) | ||
| 90 | + args = parser.parse_args() | ||
| 91 | + | ||
| 92 | + arch = _ARCH_MAP.get(args.soc) | ||
| 93 | + if arch is None: | ||
| 94 | + raise SystemExit(f"[pypto_codegen] unsupported soc: {args.soc} (supported: {sorted(_ARCH_MAP)})") | ||
| 95 | + | ||
| 96 | + py_file = Path(args.py_file).resolve() | ||
| 97 | + if not py_file.is_file(): | ||
| 98 | + raise SystemExit(f"[pypto_codegen] py-file not found: {py_file}") | ||
| 99 | + | ||
| 100 | + out_dir = Path(args.out_dir) | ||
| 101 | + out_dir.mkdir(parents=True, exist_ok=True) | ||
| 102 | + | ||
| 103 | + _install_build_only_torch_stub() | ||
| 104 | + binary_dir = _prepare_binary_headers(py_file, arch) | ||
| 105 | + shutil.copytree(binary_dir, out_dir, dirs_exist_ok=True) | ||
| 106 | + copied = sorted( | ||
| 107 | + path.relative_to(binary_dir).as_posix() | ||
| 108 | + for path in binary_dir.rglob("*") | ||
| 109 | + if path.is_file() | ||
| 110 | + ) | ||
| 111 | + | ||
| 112 | + logging.info("%s: generated %s into %s", args.op_file, copied, out_dir) | ||
| 113 | + | ||
| 114 | + | ||
| 115 | +if __name__ == "__main__": | ||
| 116 | + logging.basicConfig( | ||
| 117 | + format="[%(asctime)s][%(filename)s:%(lineno)d] %(message)s", | ||
| 118 | + datefmt="%Y-%m-%d %H:%M:%S", | ||
| 119 | + level=logging.INFO, | ||
| 120 | + ) | ||
| 121 | + main() | ||
| @@ -0,0 +1,285 @@ | |||
| 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 | +# 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 | +"""tiling 结构字节级对齐 构建期自动校验. | ||
| 12 | + | ||
| 13 | +参照 ops-transformer attention/flash_attn_grad/op_host/base/flash_attn_grad_tiling_regbase.cpp | ||
| 14 | +的手工 static_assert 方案, gym 将其自动化: TilingData 存在两份互不相干的声明—— | ||
| 15 | + 1. pypto codegen 生成的 <X>_tiling.h: 按 kernel dataclass 声明顺序生成, 是权威布局; | ||
| 16 | + 2. op_host 手写 BEGIN_TILING_DATA_DEF + REGISTER_TILING_DATA_CLASS: 框架按它分配 tiling buffer. | ||
| 17 | +两份漂移不会有任何编译/运行报错, 只会让 kernel 读到整体错位的字段. | ||
| 18 | + | ||
| 19 | +本脚本 (configure 期由 add_tiling_modules 调用, 早于一切编译): | ||
| 20 | + a) 解析两侧字段序列 (名称/类型/数组长度) 做 diff, 不一致即打印 diff 并退出码 1 (报错即拒); | ||
| 21 | + b) 一致则生成 tiling 布局核对程序 (custom_build.cmake 构建并在 tiling 编译前执行): | ||
| 22 | + 运行时构造手写 TilingData, 以 TilingDef::GetDataSize()/GetFieldInfo() 读取框架真实 | ||
| 23 | + buffer 布局, 与编译期 sizeof(kernel dataclass 生成类) 及期望字段序列交叉验证 —— | ||
| 24 | + padding 级漂移 (如 float 字段后的对齐填充) 由框架布局机制兜底钉死. | ||
| 25 | + | ||
| 26 | +注: 手写侧布局由 BEGIN_TILING_DATA_DEF 的 FieldHandler 在运行时累加 (C++ 对象尺寸含 | ||
| 27 | + 每字段 offset+16B reserve 三件套, sizeof 不可比), 故编译期 offsetof/static_assert | ||
| 28 | + 对手写侧不可行 (ops-transformer fag regbase.cpp 亦仅对生成侧下断言, gym 以运行时 | ||
| 29 | + 核对程序补全另一半). | ||
| 30 | +""" | ||
| 31 | + | ||
| 32 | +import argparse | ||
| 33 | +import re | ||
| 34 | +import sys | ||
| 35 | +from dataclasses import dataclass | ||
| 36 | +from pathlib import Path | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +@dataclass | ||
| 40 | +class Field: | ||
| 41 | + ctype: str | ||
| 42 | + name: str | ||
| 43 | + array_len: int # 0 = 标量 | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def _strip_comments(text: str) -> str: | ||
| 47 | + text = re.sub(r"/\*.*?\*/", "", text, flags=re.S) | ||
| 48 | + return re.sub(r"//[^\n]*", "", text) | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def _norm_type(t: str) -> str: | ||
| 52 | + return re.sub(r"\s+", "", t) | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +def parse_generated_header(gen_dir: Path) -> tuple: | ||
| 56 | + """解析 codegen 生成的 <X>_tiling.h (单一 @pl.jit kernel 契约: 恰好一个).""" | ||
| 57 | + candidates = sorted(gen_dir.glob("*_tiling.h")) | ||
| 58 | + if not candidates: | ||
| 59 | + raise SystemExit(f"[tiling_check] no *_tiling.h under {gen_dir}") | ||
| 60 | + if len(candidates) > 1: | ||
| 61 | + raise SystemExit( | ||
| 62 | + f"[tiling_check] multiple *_tiling.h under {gen_dir}: " | ||
| 63 | + f"{[p.name for p in candidates]} (one @pl.jit kernel per entry file)") | ||
| 64 | + text = candidates[0].read_text() | ||
| 65 | + m = re.search(r"(?:class|struct)\s+(\w+)\s*\{[^}]*?public:\s*(.*?)\s*\};", text, re.S) | ||
| 66 | + if not m: | ||
| 67 | + raise SystemExit(f"[tiling_check] cannot parse generated header {candidates[0]}") | ||
| 68 | + gen_name, body = m.group(1), m.group(2) | ||
| 69 | + fields = [] | ||
| 70 | + for tok in body.split(";"): | ||
| 71 | + tok = tok.strip() | ||
| 72 | + if not tok: | ||
| 73 | + continue | ||
| 74 | + fm = re.match(r"^([\w:]+)\s+(\w+)\s*(?:\[(\d+)\])?$", tok) | ||
| 75 | + if not fm: | ||
| 76 | + raise SystemExit(f"[tiling_check] unparsed field '{tok}' in {candidates[0]}") | ||
| 77 | + fields.append(Field(_norm_type(fm.group(1)), fm.group(2), int(fm.group(3) or 0))) | ||
| 78 | + if not fields: | ||
| 79 | + raise SystemExit(f"[tiling_check] empty field list in {candidates[0]}") | ||
| 80 | + return gen_name, fields, candidates[0] | ||
| 81 | + | ||
| 82 | + | ||
| 83 | +def parse_handwritten(host_dir: Path) -> tuple: | ||
| 84 | + """解析 op_host 手写 TilingData: REGISTER_TILING_DATA_CLASS + BEGIN_TILING_DATA_DEF.""" | ||
| 85 | + srcs = sorted(p for p in host_dir.rglob("*") if p.suffix in (".h", ".cpp")) | ||
| 86 | + reg_re = re.compile(r"REGISTER_TILING_DATA_CLASS\s*\(\s*(\w+)\s*,\s*(\w+)\s*\)") | ||
| 87 | + regs = [] | ||
| 88 | + for p in srcs: | ||
| 89 | + for m in reg_re.finditer(_strip_comments(p.read_text())): | ||
| 90 | + regs.append((p, m.group(1), m.group(2))) | ||
| 91 | + if not regs: | ||
| 92 | + raise SystemExit( | ||
| 93 | + f"[tiling_check] no REGISTER_TILING_DATA_CLASS in {host_dir}; " | ||
| 94 | + "pypto built-in op must register its tiling struct") | ||
| 95 | + structs = {(op, s) for _, op, s in regs} | ||
| 96 | + if len(structs) > 1: | ||
| 97 | + raise SystemExit( | ||
| 98 | + f"[tiling_check] ambiguous registrations {sorted(structs)} in {host_dir} " | ||
| 99 | + "(gym contract: one op per op_host dir)") | ||
| 100 | + reg_file, op_type, struct = regs[0] | ||
| 101 | + | ||
| 102 | + begin_re = re.compile( | ||
| 103 | + rf"BEGIN_TILING_DATA_DEF\s*\(\s*{struct}\s*\)(.*?)END_TILING_DATA_DEF", re.S) | ||
| 104 | + block = None | ||
| 105 | + block_file = None | ||
| 106 | + for p in srcs: | ||
| 107 | + m = begin_re.search(_strip_comments(p.read_text())) | ||
| 108 | + if m: | ||
| 109 | + block, block_file = m.group(1), p | ||
| 110 | + break | ||
| 111 | + if block is None: | ||
| 112 | + raise SystemExit(f"[tiling_check] BEGIN_TILING_DATA_DEF({struct}) not found in {host_dir}") | ||
| 113 | + | ||
| 114 | + field_re = re.compile( | ||
| 115 | + r"TILING_DATA_FIELD_DEF(?:_ARR)?\s*\([^()]*\)") | ||
| 116 | + scalar_re = re.compile(r"TILING_DATA_FIELD_DEF\s*\(\s*([^,]+?)\s*,\s*(\w+)\s*\)") | ||
| 117 | + arr_re = re.compile( | ||
| 118 | + r"TILING_DATA_FIELD_DEF_ARR\s*\(\s*([^,]+?)\s*,\s*(\d+)\s*,\s*(\w+)\s*\)") | ||
| 119 | + fields = [] | ||
| 120 | + residue = field_re.sub("", block) | ||
| 121 | + if re.search(r"\S", residue): | ||
| 122 | + unknown = re.search(r"\S[^\n]*", residue).group(0).strip() | ||
| 123 | + raise SystemExit( | ||
| 124 | + f"[tiling_check] unsupported construct '{unknown}' in {block_file} " | ||
| 125 | + "(extend tiling_layout_check.py for nested/struct fields)") | ||
| 126 | + for m in field_re.finditer(block): | ||
| 127 | + stmt = m.group(0) | ||
| 128 | + am = arr_re.fullmatch(stmt) | ||
| 129 | + if am: | ||
| 130 | + fields.append(Field(_norm_type(am.group(1)), am.group(3), int(am.group(2)))) | ||
| 131 | + continue | ||
| 132 | + sm = scalar_re.fullmatch(stmt) | ||
| 133 | + if sm: | ||
| 134 | + fields.append(Field(_norm_type(sm.group(1)), sm.group(2), 0)) | ||
| 135 | + else: | ||
| 136 | + raise SystemExit(f"[tiling_check] unparsed TILING_DATA stmt '{stmt}' in {block_file}") | ||
| 137 | + | ||
| 138 | + ns = "optiling" if re.search(r"namespace\s+optiling", block_file.read_text()) else "" | ||
| 139 | + return op_type, struct, fields, block_file, ns | ||
| 140 | + | ||
| 141 | + | ||
| 142 | +def diff_fields(op_type, gen_name, gen_fields, hw_struct, hw_fields): | ||
| 143 | + issues = [] | ||
| 144 | + if len(gen_fields) != len(hw_fields): | ||
| 145 | + issues.append( | ||
| 146 | + f" field count: kernel dataclass {len(gen_fields)} vs handwritten {len(hw_fields)}") | ||
| 147 | + for i in range(max(len(gen_fields), len(hw_fields))): | ||
| 148 | + g = gen_fields[i] if i < len(gen_fields) else None | ||
| 149 | + h = hw_fields[i] if i < len(hw_fields) else None | ||
| 150 | + if g is None or h is None: | ||
| 151 | + issues.append(f" [{i}] kernel={g or '<missing>'} vs handwritten={h or '<missing>'}") | ||
| 152 | + continue | ||
| 153 | + if g.name != h.name: | ||
| 154 | + issues.append(f" [{i}] name: kernel '{g.name}' vs handwritten '{h.name}'") | ||
| 155 | + if g.ctype != h.ctype: | ||
| 156 | + issues.append(f" [{i}] {g.name}: type kernel '{g.ctype}' vs handwritten '{h.ctype}'") | ||
| 157 | + if g.array_len != h.array_len: | ||
| 158 | + issues.append( | ||
| 159 | + f" [{i}] {g.name}: array len kernel [{g.array_len}] vs handwritten [{h.array_len}]") | ||
| 160 | + if issues: | ||
| 161 | + print(f"[tiling_check] tiling layout check FAILED for {op_type}: " | ||
| 162 | + f"handwritten {hw_struct} != kernel dataclass {gen_name}", file=sys.stderr) | ||
| 163 | + print(" kernel side : " + ", ".join( | ||
| 164 | + f"{f.ctype} {f.name}" + (f"[{f.array_len}]" if f.array_len else "") for f in gen_fields), | ||
| 165 | + file=sys.stderr) | ||
| 166 | + print(" handwritten : " + ", ".join( | ||
| 167 | + f"{f.ctype} {f.name}" + (f"[{f.array_len}]" if f.array_len else "") for f in hw_fields), | ||
| 168 | + file=sys.stderr) | ||
| 169 | + for issue in issues: | ||
| 170 | + print(issue, file=sys.stderr) | ||
| 171 | + print(" fix: sync op_host tiling struct with op_kernel dataclass " | ||
| 172 | + "(field NAMES, ORDER and TYPES must match; PyPTO int -> int64_t, float -> float)", | ||
| 173 | + file=sys.stderr) | ||
| 174 | + return False | ||
| 175 | + return True | ||
| 176 | + | ||
| 177 | + | ||
| 178 | +def emit_check_program(path: Path, hw_header: Path, gen_header: Path, ns, hw_struct, | ||
| 179 | + gen_name, fields, op_type): | ||
| 180 | + qual = f"{ns}::{hw_struct}" if ns else hw_struct | ||
| 181 | + names = ", ".join(f'"{f.name}"' for f in fields) | ||
| 182 | + dtypes = ", ".join(f'"{f.ctype}"' for f in fields) | ||
| 183 | + arrs = ", ".join(str(f.array_len) for f in fields) | ||
| 184 | + lines = [ | ||
| 185 | + f"// Auto-generated by tiling_layout_check.py (tiling layout contract, op {op_type}). Do not edit.", | ||
| 186 | + "#include <cstddef>", | ||
| 187 | + "#include <cstdio>", | ||
| 188 | + "#include <cstring>", | ||
| 189 | + f'#include "{hw_header}"', | ||
| 190 | + f'#include "{gen_header}"', | ||
| 191 | + "", | ||
| 192 | + "namespace {", | ||
| 193 | + "bool IsPaddingPlaceholder(const char *name) {", | ||
| 194 | + " const size_t len = std::strlen(name);", | ||
| 195 | + " return len > 2 && std::strcmp(name + len - 2, \"PH\") == 0;", | ||
| 196 | + "}", | ||
| 197 | + "void DumpRegistered(const std::vector<optiling::FieldInfo> ®istered) {", | ||
| 198 | + " for (const auto &f : registered) {", | ||
| 199 | + " std::fprintf(stderr, \" registered: name=%s dtype=%s classType=%s%s\\n\",", | ||
| 200 | + " f.name_, f.dtype_, f.classType_,", | ||
| 201 | + " std::strcmp(f.classType_, \"1\") == 0 ? \" (array)\" : \"\");", | ||
| 202 | + " }", | ||
| 203 | + "}", | ||
| 204 | + "}", | ||
| 205 | + "", | ||
| 206 | + "int main() {", | ||
| 207 | + f" {qual} td;", | ||
| 208 | + f" const size_t kernelSize = sizeof(::{gen_name});", | ||
| 209 | + " if (td.GetDataSize() != kernelSize) {", | ||
| 210 | + " std::fprintf(stderr,", | ||
| 211 | + f" \"[tiling_check] tiling layout check FAILED {op_type}: tiling buffer size mismatch: \"", | ||
| 212 | + f" \"host {hw_struct}::GetDataSize()=%zu vs kernel sizeof({gen_name})=%zu; \"", | ||
| 213 | + " \"sync op_host tiling struct with op_kernel dataclass\\n\",", | ||
| 214 | + " td.GetDataSize(), kernelSize);", | ||
| 215 | + " return 1;", | ||
| 216 | + " }", | ||
| 217 | + " const auto registered = td.GetFieldInfo();", | ||
| 218 | + f" static const char *kNames[] = {{{names}}};", | ||
| 219 | + f" static const char *kDtypes[] = {{{dtypes}}};", | ||
| 220 | + f" static const size_t kArrLens[] = {{{arrs}}};", | ||
| 221 | + f" const size_t kCount = {len(fields)};", | ||
| 222 | + " // 框架为对齐 padding 插入 \"xxxPH\" uint8_t 占位字段, 序列比对仅看真实字段", | ||
| 223 | + " size_t realCount = 0;", | ||
| 224 | + " for (const auto &f : registered) {", | ||
| 225 | + " if (!IsPaddingPlaceholder(f.name_)) { ++realCount; }", | ||
| 226 | + " }", | ||
| 227 | + " if (realCount != kCount) {", | ||
| 228 | + " std::fprintf(stderr,", | ||
| 229 | + f" \"[tiling_check] tiling layout check FAILED {op_type}: registered real field count %zu != expected %zu\\n\",", | ||
| 230 | + " realCount, kCount);", | ||
| 231 | + " DumpRegistered(registered);", | ||
| 232 | + " return 1;", | ||
| 233 | + " }", | ||
| 234 | + " size_t idx = 0;", | ||
| 235 | + " for (const auto &f : registered) {", | ||
| 236 | + " if (IsPaddingPlaceholder(f.name_)) { continue; }", | ||
| 237 | + " const bool isArray = kArrLens[idx] != 0;", | ||
| 238 | + " const bool fieldIsScalar = std::strcmp(f.classType_, \"0\") == 0;", | ||
| 239 | + " const bool fieldIsArray = std::strcmp(f.classType_, \"1\") == 0;", | ||
| 240 | + " if (std::strcmp(f.name_, kNames[idx]) != 0 ||", | ||
| 241 | + " std::strcmp(f.dtype_, kDtypes[idx]) != 0 ||", | ||
| 242 | + " isArray ? !fieldIsArray : !fieldIsScalar ||", | ||
| 243 | + " (isArray && f.arrSize_ != kArrLens[idx])) {", | ||
| 244 | + " std::fprintf(stderr,", | ||
| 245 | + f" \"[tiling_check] tiling layout check FAILED {op_type}: field[%zu] registered as \"", | ||
| 246 | + " \"(name=%s dtype=%s classType=%s) but expected (name=%s dtype=%s arr=%zu)\\n\",", | ||
| 247 | + " idx, f.name_, f.dtype_, f.classType_,", | ||
| 248 | + " kNames[idx], kDtypes[idx], kArrLens[idx]);", | ||
| 249 | + " DumpRegistered(registered);", | ||
| 250 | + " return 1;", | ||
| 251 | + " }", | ||
| 252 | + " ++idx;", | ||
| 253 | + " }", | ||
| 254 | + " std::printf(\"[tiling_check] OK %s: %zu fields, %zu-byte tiling buffer \"", | ||
| 255 | + f" \"(host {hw_struct} <-> kernel {gen_name})\\n\", \"{op_type}\", kCount, kernelSize);", | ||
| 256 | + " return 0;", | ||
| 257 | + "}", | ||
| 258 | + ] | ||
| 259 | + path.parent.mkdir(parents=True, exist_ok=True) | ||
| 260 | + path.write_text("\n".join(lines) + "\n") | ||
| 261 | + | ||
| 262 | + | ||
| 263 | +def main(): | ||
| 264 | + parser = argparse.ArgumentParser(description="tiling layout byte-alignment contract check") | ||
| 265 | + parser.add_argument("--gen-dir", required=True, help="pypto codegen dir (PYPTO_GEN_DIR)") | ||
| 266 | + parser.add_argument("--host-dir", required=True, help="operator op_host dir") | ||
| 267 | + parser.add_argument("--op-file", required=True, help="op file stem, e.g. flex_attention") | ||
| 268 | + parser.add_argument("--emit-dir", required=True, help="dir for the static_assert TU") | ||
| 269 | + args = parser.parse_args() | ||
| 270 | + | ||
| 271 | + gen_name, gen_fields, gen_header = parse_generated_header(Path(args.gen_dir)) | ||
| 272 | + op_type, hw_struct, hw_fields, hw_header, ns = parse_handwritten(Path(args.host_dir)) | ||
| 273 | + | ||
| 274 | + if not diff_fields(op_type, gen_name, gen_fields, hw_struct, hw_fields): | ||
| 275 | + raise SystemExit(1) | ||
| 276 | + | ||
| 277 | + tu = Path(args.emit_dir) / f"{args.op_file}_tiling_layout_check.cpp" | ||
| 278 | + emit_check_program(tu, hw_header.resolve(), gen_header.resolve(), ns, hw_struct, | ||
| 279 | + gen_name, gen_fields, op_type) | ||
| 280 | + print(f"[tiling_check] OK {op_type}: {len(gen_fields)} fields consistent " | ||
| 281 | + f"({gen_name} <-> {hw_struct}); check program -> {tu}") | ||
| 282 | + | ||
| 283 | + | ||
| 284 | +if __name__ == "__main__": | ||
| 285 | + main() | ||
| @@ -0,0 +1,93 @@ | |||
| 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 | +# 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 | +""" | ||
| 13 | + | ||
| 14 | +import sys | ||
| 15 | +import stat | ||
| 16 | +import os | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +def write_options_to_file( | ||
| 20 | + file_name: str, options_str: str, op_type: str, compute_unit: str, split_char: str | ||
| 21 | +): | ||
| 22 | + flags = os.O_WRONLY | os.O_CREAT | ||
| 23 | + modes = stat.S_IWUSR | stat.S_IRUSR | ||
| 24 | + try: | ||
| 25 | + with os.fdopen(os.open(file_name, flags, modes), "a") as fd: | ||
| 26 | + fd.write( | ||
| 27 | + op_type + split_char + compute_unit + split_char + options_str + "\n" | ||
| 28 | + ) | ||
| 29 | + except Exception as err: | ||
| 30 | + print("write compile options config file failed") | ||
| 31 | + raise (err) | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +def gen_compile_options( | ||
| 35 | + compile_options_file: str, op_type: str, compute_unit: str, compile_options: list | ||
| 36 | +): | ||
| 37 | + base_dir = os.path.dirname(compile_options_file) | ||
| 38 | + opc_config_file = os.path.join(base_dir, "custom_opc_options.ini") | ||
| 39 | + compile_opt = [] | ||
| 40 | + opc_debug_config = [] | ||
| 41 | + opc_tiling_keys = "" | ||
| 42 | + for opts in compile_options: | ||
| 43 | + if "oom" in opts: | ||
| 44 | + if opts == "--oom": | ||
| 45 | + opc_debug_config.append("oom") | ||
| 46 | + else: | ||
| 47 | + raise RuntimeError(f"Unknown oom option format {opts}") | ||
| 48 | + elif "--save-temp-files" in opts: | ||
| 49 | + opc_debug_config.append("dump_cce") | ||
| 50 | + elif opts.startswith("--op_relocatable_kernel_binary"): | ||
| 51 | + opc_debug_config.append(opts) | ||
| 52 | + elif opts.startswith("--op_super_kernel_options"): | ||
| 53 | + opc_debug_config.append(opts) | ||
| 54 | + elif "--tiling_key" in opts: | ||
| 55 | + keys = opts.strip().split("=")[1].split(",") | ||
| 56 | + keys_str = ";".join([key for key in keys]) | ||
| 57 | + opc_tiling_keys = keys_str | ||
| 58 | + else: | ||
| 59 | + compile_opt.append(opts) | ||
| 60 | + if len(compile_opt) > 0: | ||
| 61 | + options_str = ";".join([opt for opt in compile_opt]) | ||
| 62 | + write_options_to_file( | ||
| 63 | + compile_options_file, options_str, op_type, compute_unit, "," | ||
| 64 | + ) | ||
| 65 | + opc_config_str = "" | ||
| 66 | + if opc_debug_config: | ||
| 67 | + opc_config_str = "--op_debug_config=" + ";".join( | ||
| 68 | + [opt for opt in opc_debug_config] | ||
| 69 | + ) | ||
| 70 | + if len(opc_tiling_keys) > 0: | ||
| 71 | + if opc_config_str != "": | ||
| 72 | + opc_config_str += "@" | ||
| 73 | + opc_config_str += "--tiling_key=" + opc_tiling_keys | ||
| 74 | + | ||
| 75 | + if opc_config_str != "": | ||
| 76 | + write_options_to_file( | ||
| 77 | + opc_config_file, opc_config_str, op_type, compute_unit, "@" | ||
| 78 | + ) | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +if __name__ == "__main__": | ||
| 82 | + if len(sys.argv) < 4: | ||
| 83 | + raise RuntimeError("arguments must greater than 4") | ||
| 84 | + compute_soc = "" | ||
| 85 | + comp_options = [] | ||
| 86 | + for i in range(len(sys.argv) - 3): | ||
| 87 | + if sys.argv[i + 3].upper().startswith("ASCEND"): | ||
| 88 | + compute_soc += sys.argv[i + 3] + ";" | ||
| 89 | + else: | ||
| 90 | + comp_options.append(sys.argv[i + 3]) | ||
| 91 | + if compute_soc != "": | ||
| 92 | + compute_soc = compute_soc[0:-1] | ||
| 93 | + gen_compile_options(sys.argv[1], sys.argv[2], compute_soc, comp_options) | ||
| @@ -0,0 +1,396 @@ | |||
| 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 | +# 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 | +""" | ||
| 13 | + | ||
| 14 | +import os | ||
| 15 | +import glob | ||
| 16 | +import json | ||
| 17 | +import sys | ||
| 18 | +import argparse | ||
| 19 | +from typing import NamedTuple, Dict | ||
| 20 | +import const_var | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class OpConfig(NamedTuple): | ||
| 24 | + op_type: str | ||
| 25 | + support_info: Dict | ||
| 26 | + core_type: str | ||
| 27 | + task_ration: str | ||
| 28 | + obj_file: str | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def load_json(json_file: str): | ||
| 32 | + with open(json_file, encoding="utf-8") as file: | ||
| 33 | + json_content = json.load(file) | ||
| 34 | + return json_content | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def get_specified_suffix_file(root_dir, suffix): | ||
| 38 | + specified_suffix = os.path.join(root_dir, "**/*{}".format(suffix)) | ||
| 39 | + all_suffix_files = glob.glob(specified_suffix, recursive=True) | ||
| 40 | + return sorted(all_suffix_files) | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +def add_dict_key(dict_to_add, key, value): | ||
| 44 | + if value is None: | ||
| 45 | + return | ||
| 46 | + dict_to_add[key] = value | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +def correct_format_mode(format_mode): | ||
| 50 | + if format_mode == "FormatDefault": | ||
| 51 | + return "nd_agnostic" | ||
| 52 | + if format_mode == "FormatAgnostic": | ||
| 53 | + return "static_nd_agnostic" | ||
| 54 | + if format_mode == "FormatFixed": | ||
| 55 | + return "normal" | ||
| 56 | + return format_mode | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def get_input_or_output_config(in_or_out): | ||
| 60 | + param_dict = {} | ||
| 61 | + name = in_or_out.get("name") | ||
| 62 | + index = in_or_out.get("index") | ||
| 63 | + param_type = in_or_out.get("paramType") | ||
| 64 | + | ||
| 65 | + format_match_mode = in_or_out.get("format_match_mode") | ||
| 66 | + format_mode = correct_format_mode(format_match_mode) | ||
| 67 | + | ||
| 68 | + dtype_mode = in_or_out.get("dtype_match_mode") | ||
| 69 | + if dtype_mode == "DtypeByte": | ||
| 70 | + dtype_mode = "bit" | ||
| 71 | + | ||
| 72 | + add_dict_key(param_dict, "name", name) | ||
| 73 | + add_dict_key(param_dict, "index", index) | ||
| 74 | + add_dict_key(param_dict, "paramType", param_type) | ||
| 75 | + add_dict_key(param_dict, "dtypeMode", dtype_mode) | ||
| 76 | + add_dict_key(param_dict, "formatMode", format_mode) | ||
| 77 | + return param_dict | ||
| 78 | + | ||
| 79 | + | ||
| 80 | +def get_inputs_or_outputs_config(inputs_or_outputs): | ||
| 81 | + if inputs_or_outputs is None: | ||
| 82 | + return None | ||
| 83 | + inputs_or_outputs_list = [] | ||
| 84 | + | ||
| 85 | + for in_or_out in inputs_or_outputs: | ||
| 86 | + if isinstance(in_or_out, dict): | ||
| 87 | + dict_param_config = get_input_or_output_config(in_or_out) | ||
| 88 | + inputs_or_outputs_list.append(dict_param_config) | ||
| 89 | + elif isinstance(in_or_out, list): | ||
| 90 | + param_info = in_or_out[0] | ||
| 91 | + list_param_config = get_input_or_output_config(param_info) | ||
| 92 | + tmp_list = [list_param_config] | ||
| 93 | + inputs_or_outputs_list.append(tmp_list) | ||
| 94 | + return inputs_or_outputs_list | ||
| 95 | + | ||
| 96 | + | ||
| 97 | +def gen_attrs_config(attrs): | ||
| 98 | + attrs_list = [] | ||
| 99 | + for attr in attrs: | ||
| 100 | + attrs_dict = {} | ||
| 101 | + name = attr.get("name") | ||
| 102 | + mode = attr.get("mode") | ||
| 103 | + add_dict_key(attrs_dict, "name", name) | ||
| 104 | + add_dict_key(attrs_dict, "mode", mode) | ||
| 105 | + attrs_list.append(attrs_dict) | ||
| 106 | + return attrs_list | ||
| 107 | + | ||
| 108 | + | ||
| 109 | +def get_params_config(support_info): | ||
| 110 | + params_dict = {} | ||
| 111 | + | ||
| 112 | + inputs = support_info.get("inputs") | ||
| 113 | + inputs_list = get_inputs_or_outputs_config(inputs) | ||
| 114 | + params_dict["inputs"] = inputs_list | ||
| 115 | + | ||
| 116 | + outputs = support_info.get("outputs") | ||
| 117 | + outputs_list = get_inputs_or_outputs_config(outputs) | ||
| 118 | + params_dict["outputs"] = outputs_list | ||
| 119 | + | ||
| 120 | + attrs = support_info.get("attrs") | ||
| 121 | + if attrs is not None: | ||
| 122 | + attrs_list = gen_attrs_config(attrs) | ||
| 123 | + params_dict["attrs"] = attrs_list | ||
| 124 | + | ||
| 125 | + return params_dict | ||
| 126 | + | ||
| 127 | + | ||
| 128 | +def add_simplified_config(op_info, binary_info_config, config): | ||
| 129 | + simplified_key = op_info.support_info.get("simplifiedKey") | ||
| 130 | + | ||
| 131 | + json_path = op_info.obj_file.split(".")[0] + ".json" | ||
| 132 | + | ||
| 133 | + simple_cfg = config.get(binary_info_config) | ||
| 134 | + op_cfg = simple_cfg.get(op_info.op_type) | ||
| 135 | + if not op_cfg: | ||
| 136 | + op_cfg = {"dynamicRankSupport": True} | ||
| 137 | + | ||
| 138 | + simplified_key_mode = op_info.support_info.get("simplifiedKeyMode") | ||
| 139 | + add_dict_key(op_cfg, "simplifiedKeyMode", simplified_key_mode) | ||
| 140 | + | ||
| 141 | + optional_input_mode = op_info.support_info.get("optionalInputMode") | ||
| 142 | + optional_output_mode = op_info.support_info.get("optionalOutputMode") | ||
| 143 | + add_dict_key(op_cfg, "optionalInputMode", optional_input_mode) | ||
| 144 | + if optional_output_mode is not None: | ||
| 145 | + add_dict_key(op_cfg, "optionalOutputMode", optional_output_mode) | ||
| 146 | + | ||
| 147 | + params_info = get_params_config(op_info.support_info) | ||
| 148 | + op_cfg["params"] = params_info | ||
| 149 | + op_cfg["binaryList"] = [] | ||
| 150 | + simple_cfg[op_info.op_type] = op_cfg | ||
| 151 | + | ||
| 152 | + bin_list = op_cfg.get("binaryList") | ||
| 153 | + if op_info.core_type == 0 and op_info.task_ration == "tilingKey": | ||
| 154 | + bin_list.append( | ||
| 155 | + { | ||
| 156 | + "coreType": op_info.core_type, | ||
| 157 | + "simplifiedKey": simplified_key, | ||
| 158 | + "multiKernelType": 1, | ||
| 159 | + "binPath": op_info.obj_file, | ||
| 160 | + "jsonPath": json_path, | ||
| 161 | + } | ||
| 162 | + ) | ||
| 163 | + else: | ||
| 164 | + bin_list.append( | ||
| 165 | + { | ||
| 166 | + "coreType": op_info.core_type, | ||
| 167 | + "simplifiedKey": simplified_key, | ||
| 168 | + "binPath": op_info.obj_file, | ||
| 169 | + "jsonPath": json_path, | ||
| 170 | + } | ||
| 171 | + ) | ||
| 172 | + | ||
| 173 | + | ||
| 174 | +def add_op_config(op_file, bin_info, config): | ||
| 175 | + op_cfg = config.get(op_file) | ||
| 176 | + if not op_cfg: | ||
| 177 | + op_cfg = {"binList": []} | ||
| 178 | + config[op_file] = op_cfg | ||
| 179 | + op_cfg.get("binList").append(bin_info) | ||
| 180 | + | ||
| 181 | + | ||
| 182 | +def gen_ops_config(json_file, soc, binary_info_config, config): | ||
| 183 | + core_type_map = { | ||
| 184 | + "MIX": 0, | ||
| 185 | + "AiCore": 1, | ||
| 186 | + "VectorCore": 2, | ||
| 187 | + "MIX_AICORE": 3, | ||
| 188 | + "MIX_VECTOR_CORE": 4, | ||
| 189 | + "MIX_AIV": 4, | ||
| 190 | + } | ||
| 191 | + contents = load_json(json_file) | ||
| 192 | + if ("binFileName" not in contents) or ("supportInfo" not in contents): | ||
| 193 | + return | ||
| 194 | + json_base_name = os.path.basename(json_file) | ||
| 195 | + op_dir = os.path.basename(os.path.dirname(json_file)) | ||
| 196 | + | ||
| 197 | + support_info = contents.get("supportInfo") | ||
| 198 | + bin_name = contents.get("binFileName") | ||
| 199 | + bin_suffix = contents.get("binFileSuffix") | ||
| 200 | + core_type = contents.get("coreType") | ||
| 201 | + task_ration = contents.get("taskRation") | ||
| 202 | + core_type = core_type_map.get(core_type, -1) | ||
| 203 | + if core_type == -1 and soc != "ascend310b": | ||
| 204 | + raise Exception("[ERROR]: must set coreType in json when soc version is {soc}.") | ||
| 205 | + | ||
| 206 | + bin_file_name = bin_name + bin_suffix | ||
| 207 | + op_type = bin_name.split("_")[0] | ||
| 208 | + op_file = op_dir + ".json" | ||
| 209 | + bin_info = {} | ||
| 210 | + | ||
| 211 | + add_dict_key(bin_info, "implMode", support_info.get("implMode")) | ||
| 212 | + add_dict_key(bin_info, "int64Mode", support_info.get("int64Mode")) | ||
| 213 | + add_dict_key(bin_info, "simplifiedKeyMode", support_info.get("simplifiedKeyMode")) | ||
| 214 | + | ||
| 215 | + simplified_key = support_info.get("simplifiedKey") | ||
| 216 | + if simplified_key is not None: | ||
| 217 | + bin_info["simplifiedKey"] = simplified_key | ||
| 218 | + obj_file = os.path.join(soc, op_dir, bin_file_name) | ||
| 219 | + op_info = OpConfig( | ||
| 220 | + op_type=op_type, | ||
| 221 | + support_info=support_info, | ||
| 222 | + core_type=core_type, | ||
| 223 | + task_ration=task_ration, | ||
| 224 | + obj_file=obj_file, | ||
| 225 | + ) | ||
| 226 | + add_simplified_config(op_info, binary_info_config, config) | ||
| 227 | + | ||
| 228 | + add_dict_key(bin_info, "dynamicParamMode", support_info.get("dynamicParamMode")) | ||
| 229 | + bin_info["staticKey"] = support_info.get("staticKey") | ||
| 230 | + bin_info["inputs"] = support_info.get("inputs") | ||
| 231 | + bin_info["outputs"] = support_info.get("outputs") | ||
| 232 | + if support_info.get("attrs"): | ||
| 233 | + bin_info["attrs"] = support_info.get("attrs") | ||
| 234 | + | ||
| 235 | + add_dict_key(bin_info, "opMode", support_info.get("opMode")) | ||
| 236 | + add_dict_key(bin_info, "optionalInputMode", support_info.get("optionalInputMode")) | ||
| 237 | + add_dict_key(bin_info, "deterministic", support_info.get("deterministic")) | ||
| 238 | + if support_info.get("optionalOutputMode") is not None: | ||
| 239 | + add_dict_key( | ||
| 240 | + bin_info, "optionalOutputMode", support_info.get("optionalOutputMode") | ||
| 241 | + ) | ||
| 242 | + | ||
| 243 | + bin_info["binInfo"] = {"jsonFilePath": os.path.join(soc, op_dir, json_base_name)} | ||
| 244 | + add_op_config(op_file, bin_info, config) | ||
| 245 | + | ||
| 246 | + | ||
| 247 | +def check_single_op_is_void(root_dir): | ||
| 248 | + for root, dirs, _ in os.walk(root_dir): | ||
| 249 | + for sub_dir in dirs: | ||
| 250 | + dir_path = os.path.join(root, sub_dir) | ||
| 251 | + if len(os.listdir(dir_path)) == 0: | ||
| 252 | + print(f"[ERROR] op {sub_dir}: not any obj compile success") | ||
| 253 | + sys.exit(1) | ||
| 254 | + | ||
| 255 | + | ||
| 256 | +def write_jsons(out_dir, file_list, config): | ||
| 257 | + for json_name in file_list: | ||
| 258 | + json_file = os.path.join(out_dir, json_name) | ||
| 259 | + with os.fdopen( | ||
| 260 | + os.open(json_file, const_var.WFLAGS, const_var.WMODES), "w" | ||
| 261 | + ) as fd: | ||
| 262 | + json.dump(config.get(json_name), fd, indent=" ") | ||
| 263 | + | ||
| 264 | + | ||
| 265 | +def generate_operator_cfg_file( | ||
| 266 | + json_files, binary_info_config, soc, out_dir, gen_json_status | ||
| 267 | +): | ||
| 268 | + if not json_files: | ||
| 269 | + return | ||
| 270 | + | ||
| 271 | + if gen_json_status == "not_generated": | ||
| 272 | + return | ||
| 273 | + | ||
| 274 | + json_files.sort() | ||
| 275 | + config = {binary_info_config: {}} | ||
| 276 | + for _json in json_files: | ||
| 277 | + gen_ops_config(_json, soc, binary_info_config, config) | ||
| 278 | + | ||
| 279 | + if gen_json_status == "single_json": | ||
| 280 | + file_list = [ | ||
| 281 | + json_file for json_file in config.keys() if json_file != binary_info_config | ||
| 282 | + ] | ||
| 283 | + elif gen_json_status == "summary_json": | ||
| 284 | + file_list = [binary_info_config] | ||
| 285 | + else: | ||
| 286 | + file_list = config.keys() | ||
| 287 | + | ||
| 288 | + write_jsons(out_dir, file_list, config) | ||
| 289 | + | ||
| 290 | + | ||
| 291 | +def gen_all_config(root_dir, soc, out_dir, skip_binary_info_config, op_range="all"): | ||
| 292 | + if op_range != "relocatable": | ||
| 293 | + check_single_op_is_void(root_dir) | ||
| 294 | + all_json_files = get_specified_suffix_file(root_dir, ".json") | ||
| 295 | + relocatable_json_files = get_specified_suffix_file(root_dir, "_relocatable.json") | ||
| 296 | + normal_json_files = list(set(all_json_files) - set(relocatable_json_files)) | ||
| 297 | + os.makedirs(out_dir, exist_ok=True) | ||
| 298 | + | ||
| 299 | + if op_range != "relocatable": | ||
| 300 | + for _json in all_json_files: | ||
| 301 | + file_path = soc + _json.split(soc, maxsplit=1)[1] | ||
| 302 | + with open(_json, "r+") as f: | ||
| 303 | + data = json.load(f) | ||
| 304 | + data["filePath"] = file_path | ||
| 305 | + f.seek(0) | ||
| 306 | + json.dump(data, f, indent=" ") | ||
| 307 | + f.truncate() | ||
| 308 | + | ||
| 309 | + if skip_binary_info_config: | ||
| 310 | + gen_normale_json = "single_json" | ||
| 311 | + gen_relocatable_json = "not_generated" | ||
| 312 | + else: | ||
| 313 | + gen_normale_json = "all_json" | ||
| 314 | + gen_relocatable_json = "summary_json" | ||
| 315 | + | ||
| 316 | + # normal kernel | ||
| 317 | + if op_range == "all" or op_range == "normal": | ||
| 318 | + binary_info_config = "binary_info_config.json" | ||
| 319 | + generate_operator_cfg_file( | ||
| 320 | + normal_json_files, binary_info_config, soc, out_dir, gen_normale_json | ||
| 321 | + ) | ||
| 322 | + | ||
| 323 | + # relocatable kernel | ||
| 324 | + if op_range == "all" or op_range == "relocatable": | ||
| 325 | + binary_info_config = "relocatable_kernel_info_config.json" | ||
| 326 | + generate_operator_cfg_file( | ||
| 327 | + relocatable_json_files, | ||
| 328 | + binary_info_config, | ||
| 329 | + soc, | ||
| 330 | + out_dir, | ||
| 331 | + gen_relocatable_json, | ||
| 332 | + ) | ||
| 333 | + | ||
| 334 | + | ||
| 335 | +# Parse multiple soc_versions ops in single path. | ||
| 336 | +def gen_all_soc_config(all_path): | ||
| 337 | + soc_roots = glob.glob(os.path.join(all_path, "ascend*")) | ||
| 338 | + | ||
| 339 | + for soc_root in soc_roots: | ||
| 340 | + soc = os.path.basename(soc_root) | ||
| 341 | + gen_all_config(soc_root, soc, soc_root, True) | ||
| 342 | + cfg_files = glob.glob(os.path.join(soc_root, "*.json")) | ||
| 343 | + cfg_path = os.path.join(all_path, "config", soc) | ||
| 344 | + os.makedirs(cfg_path, exist_ok=True) | ||
| 345 | + for cfg_file in cfg_files: | ||
| 346 | + new_file = os.path.join(cfg_path, os.path.basename(cfg_file)) | ||
| 347 | + os.rename(cfg_file, new_file) | ||
| 348 | + | ||
| 349 | + | ||
| 350 | +def args_prase(): | ||
| 351 | + parser = argparse.ArgumentParser() | ||
| 352 | + parser.add_argument( | ||
| 353 | + "-p", | ||
| 354 | + "--path", | ||
| 355 | + nargs="?", | ||
| 356 | + required=True, | ||
| 357 | + help="Parse the path of the json file.", | ||
| 358 | + ) | ||
| 359 | + | ||
| 360 | + parser.add_argument( | ||
| 361 | + "-s", "--soc", nargs="?", required=True, help="Parse the soc_version of ops." | ||
| 362 | + ) | ||
| 363 | + | ||
| 364 | + parser.add_argument("-o", "--out", nargs="?", help="Output directory.") | ||
| 365 | + | ||
| 366 | + parser.add_argument( | ||
| 367 | + "--skip-binary-info-config", | ||
| 368 | + action="store_true", | ||
| 369 | + help="binary_info_config.json file is not parsed.", | ||
| 370 | + ) | ||
| 371 | + | ||
| 372 | + parser.add_argument( | ||
| 373 | + "--op-range", | ||
| 374 | + type=str, | ||
| 375 | + choices=["all", "normal", "relocatable"], | ||
| 376 | + default="all", | ||
| 377 | + help="all operators/normal operators/relocatable operators.", | ||
| 378 | + ) | ||
| 379 | + | ||
| 380 | + return parser.parse_args() | ||
| 381 | + | ||
| 382 | + | ||
| 383 | +def main(): | ||
| 384 | + args = args_prase() | ||
| 385 | + if args.out is None: | ||
| 386 | + out_dir = args.path | ||
| 387 | + else: | ||
| 388 | + out_dir = args.out | ||
| 389 | + | ||
| 390 | + gen_all_config( | ||
| 391 | + args.path, args.soc, out_dir, args.skip_binary_info_config, args.op_range | ||
| 392 | + ) | ||
| 393 | + | ||
| 394 | + | ||
| 395 | +if __name__ == "__main__": | ||
| 396 | + main() | ||