已合并
feat(mega_mhc): 增加二进制交付及预编译 Torch 绑定 #942
liulufang_gitcode创建于 25 天前
feat(mega_mhc): 增加二进制交付及预编译 Torch 绑定 #942
已合并
liulufang_gitcode创建于 25 天前
共 51 个文件变更+11108-109
@@ -38,6 +38,7 @@ option(ENABLE_OPS_HOST "Build ops host." ON)
38option(ENABLE_OPS_KERNEL "Build ops kernel." ON)38option(ENABLE_OPS_KERNEL "Build ops kernel." ON)
39option(ENABLE_ASAN "Enable AddressSanitizer (host side)." OFF)39option(ENABLE_ASAN "Enable AddressSanitizer (host side)." OFF)
40option(ENABLE_UBSAN "Enable UndefinedBehaviorSanitizer (host side)." OFF)40option(ENABLE_UBSAN "Enable UndefinedBehaviorSanitizer (host side)." OFF)
41+option(ENABLE_TORCH_BINDINGS "Include precompiled Torch bindings in the run package." ON)
41 42 
42# 公开编译开关(tests)43# 公开编译开关(tests)
43option(ENABLE_TESTS "Enable tests" OFF) # 算子级 dispatcher 据此派发 tests/ 目录; 亦为 config.cmake 预留 XSAN 块的激活条件44option(ENABLE_TESTS "Enable tests" OFF) # 算子级 dispatcher 据此派发 tests/ 目录; 亦为 config.cmake 预留 XSAN 块的激活条件
@@ -58,6 +59,9 @@ include(cmake/obj_func.cmake)
58if (ENABLE_TESTS)59if (ENABLE_TESTS)
59 add_subdirectory(tests)60 add_subdirectory(tests)
60endif()61endif()
62+if (ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD)
63+ add_subdirectory(torch_extension)
64+endif()
61 65 
62# 算子接入: 发现 ops/{pro,tensor} 树, add 算子级目录(dispatcher 派发 op_host/tests).66# 算子接入: 发现 ops/{pro,tensor} 树, add 算子级目录(dispatcher 派发 op_host/tests).
63# 算子侧只做"申报"(宏登记源到全局属性), 目标创建在接入后的 custom_build.cmake 读回完成.67# 算子侧只做"申报"(宏登记源到全局属性), 目标创建在接入后的 custom_build.cmake 读回完成.
@@ -65,6 +69,9 @@ gym_op_discovery(OP_LIST OP_DIR_LIST)
65foreach(_op_dir ${OP_DIR_LIST})69foreach(_op_dir ${OP_DIR_LIST})
66 add_subdirectory(${_op_dir})70 add_subdirectory(${_op_dir})
67endforeach()71endforeach()
72+if (ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD)
73+ gym_finalize_torch_bindings()
74+endif()
68 75 
69# 读回算子登记, 创建 host 侧目标(三 .so/核对程序)与 kernel 编译链76# 读回算子登记, 创建 host 侧目标(三 .so/核对程序)与 kernel 编译链
70include(cmake/custom_build.cmake) # TODO 看看能不能去掉77include(cmake/custom_build.cmake) # TODO 看看能不能去掉
@@ -12,6 +12,9 @@ PyPTO-Gym 是基于 PyPTO 编程框架构建的样例仓库,面向华为昇腾
12- **编程框架**:PyPTO,基于 Tile 的编程模型12- **编程框架**:PyPTO,基于 Tile 的编程模型
13- **内容**:融合算子样例 + 大模型适配样例13- **内容**:融合算子样例 + 大模型适配样例
14 14 
15+Pro 算子的构建、安装与测试见[构建指南](docs/build-guide.md),预编译 Torch 接口和新算子接入见[Torch 绑定说明](torch_extension/README.md)。
16+`.run` 使用 `--ops ALL`(或省略 `--ops`)时,只构建 [ops/pro/build_ops.yaml](ops/pro/build_ops.yaml) 中列出的算子;路径相对于 `ops/pro`,注释对应行即可取消该算子的构建。
17+ 
15## 核心特性18## 核心特性
16 19 
17- **大模型核心算子样例**:覆盖 DeepSeek 系列、Qwen3 系列、GLM V4.5、Gemma4-31B-it、LLaDA2-MoE 等模型的关键算子实现20- **大模型核心算子样例**:覆盖 DeepSeek 系列、Qwen3 系列、GLM V4.5、Gemma4-31B-it、LLaDA2-MoE 等模型的关键算子实现
@@ -15,7 +15,7 @@ This file provides a unified build entry point for PyPTO-GYM project, supporting
15 whl: jit direct-call mode, python -m build -> build_out/whl/<soc>/*.whl15 whl: jit direct-call mode, python -m build -> build_out/whl/<soc>/*.whl
16 run: built-in mode, CMake full chain -> build_out/run/<soc>/ producing custom run packages16 run: built-in mode, CMake full chain -> build_out/run/<soc>/ producing custom run packages
17 configure -> build -> package (.run)17 configure -> build -> package (.run)
18- stest: -s/--stest runs on-board system tests (whl -> jit / run -> aclnn)18+ stest: -s/--stest runs on-board system tests (whl -> jit / run -> aclnn or torch)
19 19 
20Multi-soc semantics: --soc accepts a comma-separated list; each soc runs a FULL20Multi-soc semantics: --soc accepts a comma-separated list; each soc runs a FULL
21build round in its own binary dir (build/<soc>), producing one .run per soc21build round in its own binary dir (build/<soc>), producing one .run per soc
@@ -35,7 +35,10 @@ Usage:
35 35 
36 Common options:36 Common options:
37 --pkg-type: Specify product type (whl/run)37 --pkg-type: Specify product type (whl/run)
38- --ops: Specify operators to build (comma separated, default ALL)38+ --ops: Specify operators to build (comma separated, default ALL;
39+ run ALL reads ops/pro/build_ops.yaml)
40+ --torch-bindings / --no-torch-bindings: Include/omit precompiled Torch bindings
41+ (enabled by default for run)
39 --soc: Specify soc version (currently ascend950 only;42 --soc: Specify soc version (currently ascend950 only;
40 comma-separated multi-value activates when whitelist expands)43 comma-separated multi-value activates when whitelist expands)
41 --build_type: Specify build type (Debug/Release/MinSizeRel/RelWithDebInfo, run mode)44 --build_type: Specify build type (Debug/Release/MinSizeRel/RelWithDebInfo, run mode)
@@ -51,7 +54,7 @@ Examples:
51 python build_ci.py --pkg-type whl54 python build_ci.py --pkg-type whl
52 55 
53 # Build run package for flex_attention on ascend95056 # Build run package for flex_attention on ascend950
54- python build_ci.py --pkg-type run --ops flex_attention --soc ascend95057+ python build_ci.py --pkg-type run --ops flex_attention --soc ascend950 --no-torch-bindings
55 58 
56 # Debug build with AddressSanitizer on host side59 # Debug build with AddressSanitizer on host side
57 python build_ci.py --pkg-type run --build_type Debug --asan60 python build_ci.py --pkg-type run --build_type Debug --asan
@@ -125,6 +128,12 @@ class FeatureParam(CMakeParam):
125 self.ops: str = args.ops or "ALL" # Operators to build (comma separated)128 self.ops: str = args.ops or "ALL" # Operators to build (comma separated)
126 self.soc: str = args.soc or "ascend950" # Soc versions (comma separated)129 self.soc: str = args.soc or "ascend950" # Soc versions (comma separated)
127 self.whl_isolation: bool = args.isolation # Compile whl package in isolation mode130 self.whl_isolation: bool = args.isolation # Compile whl package in isolation mode
131+ self.torch_bindings_explicit: bool = args.torch_bindings is not None
132+ self.torch_bindings: bool = (
133+ self.pkg_type == "run" if args.torch_bindings is None else args.torch_bindings
134+ )
135+ if self.torch_bindings and self.pkg_type != "run":
136+ raise ValueError("--torch-bindings requires --pkg-type run")
128 137 
129 def __str__(self) -> str:138 def __str__(self) -> str:
130 """Return string representation of feature parameters139 """Return string representation of feature parameters
@@ -138,6 +147,7 @@ class FeatureParam(CMakeParam):
138 run_count = len(self.soc_list)147 run_count = len(self.soc_list)
139 desc += f"\n Soc : {self.soc} ({run_count} run{'s' if run_count > 1 else ''})"148 desc += f"\n Soc : {self.soc} ({run_count} run{'s' if run_count > 1 else ''})"
140 desc += f"\n Isolation : {self.whl_isolation}"149 desc += f"\n Isolation : {self.whl_isolation}"
150+ desc += f"\n TorchBindings : {self.torch_bindings}"
141 return desc151 return desc
142 152 
143 @property153 @property
@@ -167,6 +177,13 @@ class FeatureParam(CMakeParam):
167 177 
168 @staticmethod178 @staticmethod
169 def reg_args(parser):179 def reg_args(parser):
180+ parser.add_argument(
181+ "--torch-bindings", action=argparse.BooleanOptionalAction, default=None,
182+ help="include precompiled Torch bindings (default: enabled for run when at least one "
183+ "selected operator provides one, disabled for whl; requires torch and torch_npu). "
184+ "Use --no-torch-bindings for an ACLNN-only .run; explicit --torch-bindings fails "
185+ "when no selected operator provides a binding.",
186+ )
170 parser.add_argument(187 parser.add_argument(
171 "--pkg-type",188 "--pkg-type",
172 choices=["whl", "run"],189 choices=["whl", "run"],
@@ -178,7 +195,7 @@ class FeatureParam(CMakeParam):
178 nargs="?",195 nargs="?",
179 type=str,196 type=str,
180 default="ALL",197 default="ALL",
181- help="operators to build (comma separated), e.g. flex_attention. Default ALL.",198+ help="operators to build (comma separated); run ALL uses ops/pro/build_ops.yaml. Default ALL.",
182 )199 )
183 parser.add_argument(200 parser.add_argument(
184 "--soc",201 "--soc",
@@ -207,6 +224,7 @@ class FeatureParam(CMakeParam):
207 """224 """
208 cmd = f" -DPACKAGE_TYPE={self.pkg_type}" # Control the type of product package, such as run/rpm/deb225 cmd = f" -DPACKAGE_TYPE={self.pkg_type}" # Control the type of product package, such as run/rpm/deb
209 cmd += f" -DASCEND_OP_NAME={self.ops}" # Control the scope of compilation operators226 cmd += f" -DASCEND_OP_NAME={self.ops}" # Control the scope of compilation operators
227+ cmd += f" -DENABLE_TORCH_BINDINGS={'ON' if self.torch_bindings else 'OFF'}"
210 return cmd228 return cmd
211 229 
212 230 
@@ -350,6 +368,7 @@ class BuildCtrl(CMakeParam):
350 self.third_party_path: Optional[Path] = Path(third_party_path).resolve() if third_party_path else None368 self.third_party_path: Optional[Path] = Path(third_party_path).resolve() if third_party_path else None
351 # Others369 # Others
352 self.feature: FeatureParam = FeatureParam(args=args)370 self.feature: FeatureParam = FeatureParam(args=args)
371+ self.resolve_torch_bindings()
353 self.build: BuildParam = BuildParam(args=args)372 self.build: BuildParam = BuildParam(args=args)
354 self.tests: TestParam = TestParam(args=args)373 self.tests: TestParam = TestParam(args=args)
355 self.jobs: Optional[int] = args.jobs374 self.jobs: Optional[int] = args.jobs
@@ -693,10 +712,20 @@ class BuildCtrl(CMakeParam):
693 found[op_dir.name] = op_dir712 found[op_dir.name] = op_dir
694 return found713 return found
695 714 
696- def _selected_op_dirs(self) -> List[Path]:715+ def selected_op_dirs(self) -> List[Path]:
697 """Resolve --ops into operator dirs for stest."""716 """Resolve --ops into operator dirs for stest."""
698 found = self._discover_op_dirs()717 found = self._discover_op_dirs()
699 if self.feature.ops.strip().upper() == "ALL":718 if self.feature.ops.strip().upper() == "ALL":
719+ if self.feature.pkg_type_run:
720+ scope = subprocess.run(
721+ [sys.executable, str(self.src_root / "cmake/scripts/select_run_ops.py"),
722+ "--source-root", str(self.src_root), "--ops", "ALL", "--format", "paths"],
723+ check=True, capture_output=True, text=True)
724+ selected = [self.src_root / path for path in scope.stdout.splitlines()]
725+ missing = [str(op) for op in selected if not (op / "tests").is_dir()]
726+ if missing:
727+ raise RuntimeError(f"listed run operator tests not found for {missing}")
728+ return selected
700 selected = sorted(found.values(), key=lambda p: p.name)729 selected = sorted(found.values(), key=lambda p: p.name)
701 if not selected:730 if not selected:
702 raise RuntimeError("no operator tests found under ops/{pro,tensor}/**/tests")731 raise RuntimeError("no operator tests found under ops/{pro,tensor}/**/tests")
@@ -720,6 +749,7 @@ class BuildCtrl(CMakeParam):
720 args += ["--mode", mode, "--rootdir", str(self.src_root), "-q"]749 args += ["--mode", mode, "--rootdir", str(self.src_root), "-q"]
721 if mode == "aclnn":750 if mode == "aclnn":
722 args += ["--aclnn-lib-dir", str(self._build_dir(soc) / "tests")]751 args += ["--aclnn-lib-dir", str(self._build_dir(soc) / "tests")]
752+ if mode in ("aclnn", "torch"):
723 args += ["-m", "not jit_only"]753 args += ["-m", "not jit_only"]
724 args += self._pytest_filter_args()754 args += self._pytest_filter_args()
725 cmd = " ".join(shlex.quote(a) for a in args)755 cmd = " ".join(shlex.quote(a) for a in args)
@@ -782,19 +812,57 @@ class BuildCtrl(CMakeParam):
782 "ASCEND_CUSTOM_OPP_PATH": self._prepend_env("ASCEND_CUSTOM_OPP_PATH", str(vendor)),812 "ASCEND_CUSTOM_OPP_PATH": self._prepend_env("ASCEND_CUSTOM_OPP_PATH", str(vendor)),
783 "LD_LIBRARY_PATH": self._prepend_env("LD_LIBRARY_PATH", str(vendor / "op_api" / "lib")),813 "LD_LIBRARY_PATH": self._prepend_env("LD_LIBRARY_PATH", str(vendor / "op_api" / "lib")),
784 }814 }
785- self._run_pytest(op_dirs, mode="aclnn", soc=soc, update_env=update_env)815+ manifest = vendor / "python" / "pypto_gym" / "operators.json"
816+ bound_names = (set(json.loads(manifest.read_text(encoding="utf-8")))
817+ if self.feature.torch_bindings and manifest.is_file() else set())
818+ if bound_names:
819+ update_env["PYTHONPATH"] = self._prepend_env("PYTHONPATH", str(vendor / "python"))
820+ bound = [op for op in op_dirs if op.name in bound_names]
821+ unbound = [op for op in op_dirs if op.name not in bound_names]
822+ if bound:
823+ self._run_pytest(bound, mode="torch", soc=soc, update_env=update_env)
824+ if unbound:
825+ self._run_pytest(unbound, mode="aclnn", soc=soc, update_env=update_env)
786 826 
787 def run_stest(self) -> None:827 def run_stest(self) -> None:
788 """Execute system tests for the selected operators."""828 """Execute system tests for the selected operators."""
789 if not self.tests.enabled:829 if not self.tests.enabled:
790 return830 return
791- op_dirs = self._selected_op_dirs()831+ op_dirs = self.selected_op_dirs()
792 logging.info("STest operators: %s", [d.name for d in op_dirs])832 logging.info("STest operators: %s", [d.name for d in op_dirs])
793 if self.feature.pkg_type_run:833 if self.feature.pkg_type_run:
794 self._run_stest_aclnn(op_dirs, self.feature.soc_list[0])834 self._run_stest_aclnn(op_dirs, self.feature.soc_list[0])
795 else:835 else:
796 self._run_stest_jit(op_dirs)836 self._run_stest_jit(op_dirs)
797 837 
838+ def resolve_torch_bindings(self) -> None:
839+ """Default run builds fall back to ACLNN-only when no selected op has a binding.
840+ 
841+ Keeps the pre-binding behaviour for operators that never adapted Torch, while
842+ an explicit --torch-bindings request still fails loudly in CMake.
843+ """
844+ if not self.feature.pkg_type_run or not self.feature.torch_bindings:
845+ return
846+ if self.feature.torch_bindings_explicit:
847+ return
848+ try:
849+ op_dirs = self._selected_build_dirs()
850+ except (OSError, subprocess.CalledProcessError):
851+ return # Leave the error to CMake's own scope resolution.
852+ if op_dirs and not any((d / "torch_extension" / "CMakeLists.txt").is_file() for d in op_dirs):
853+ logging.warning(
854+ "No selected operator provides a Torch binding; building an ACLNN-only .run "
855+ "(pass --torch-bindings to require bindings)")
856+ self.feature.torch_bindings = False
857+ 
858+ def _selected_build_dirs(self) -> List[Path]:
859+ """Resolve --ops into binary-buildable operator dirs (no tests required)."""
860+ scope = subprocess.run(
861+ [sys.executable, str(self.src_root / "cmake/scripts/select_run_ops.py"),
862+ "--source-root", str(self.src_root), "--ops", self.feature.ops, "--format", "paths"],
863+ check=True, capture_output=True, text=True)
864+ return [self.src_root / path for path in scope.stdout.splitlines()]
865+ 
798 def _duration(self, ts: datetime) -> str:866 def _duration(self, ts: datetime) -> str:
799 """Calculate stage duration and update remaining timeout867 """Calculate stage duration and update remaining timeout
800 868 
@@ -96,11 +96,11 @@ if (NOT PREPARE_BUILD)
96 endforeach()96 endforeach()
97endif()97endif()
98 98 
99-# 测试 aclnn_bridge 依赖(仅 ENABLE_TESTS):99+# Torch 依赖(测试桥或正式 Torch 绑定按需启用):
100-# 1. torch 仅供 pybind11 测试 bridge 使用, 非 run/kernel 构建依赖.100+# 1. 未启用 ENABLE_TESTS/ENABLE_TORCH_BINDINGS 时,run/kernel 构建不依赖 torch.
101# 2. 必须在本文件(根作用域 include)中查找: imported target 为目录作用域, 根作用域创建后101# 2. 必须在本文件(根作用域 include)中查找: imported target 为目录作用域, 根作用域创建后
102# 才能被后续 add_subdirectory 引入的算子 tests 子目录链接.102# 才能被后续 add_subdirectory 引入的算子 tests 子目录链接.
103-if (ENABLE_TESTS)103+if (ENABLE_TESTS OR ENABLE_TORCH_BINDINGS)
104 execute_process(104 execute_process(
105 COMMAND ${Python3_EXECUTABLE} -c "import torch.utils; print(torch.utils.cmake_prefix_path)"105 COMMAND ${Python3_EXECUTABLE} -c "import torch.utils; print(torch.utils.cmake_prefix_path)"
106 OUTPUT_VARIABLE _gym_torch_cmake_prefix106 OUTPUT_VARIABLE _gym_torch_cmake_prefix
@@ -152,8 +152,8 @@ endif ()
152 152 
153# 构建阶段(Build)153# 构建阶段(Build)
154# 可执行文件运行时库文件搜索路径 RPATH154# 可执行文件运行时库文件搜索路径 RPATH
155-# 在 UTest 及 STest 场景不略去 RPATH (预留: ENABLE_TESTS 选项落地时生效)155+# 测试与预编译 Torch 绑定保留运行时搜索路径。
156-if (ENABLE_TESTS)156+if (ENABLE_TESTS OR ENABLE_TORCH_BINDINGS)
157 set(CMAKE_SKIP_RPATH FALSE)157 set(CMAKE_SKIP_RPATH FALSE)
158else ()158else ()
159 set(CMAKE_SKIP_RPATH TRUE)159 set(CMAKE_SKIP_RPATH TRUE)
@@ -61,6 +61,7 @@ if (generate_aclnn_srcs)
61 ${OP_BUILD_TOOL}61 ${OP_BUILD_TOOL}
62 $<TARGET_FILE:op_host_aclnn>62 $<TARGET_FILE:op_host_aclnn>
63 ${base_aclnn_binary_dir}63 ${base_aclnn_binary_dir}
64+ DEPENDS op_host_aclnn
64 )65 )
65endif ()66endif ()
66add_custom_target(opbuild_gen_default67add_custom_target(opbuild_gen_default
@@ -77,6 +78,7 @@ if (generate_aclnn_inner_srcs)
77 ${OP_BUILD_TOOL}78 ${OP_BUILD_TOOL}
78 $<TARGET_FILE:op_host_aclnnInner>79 $<TARGET_FILE:op_host_aclnnInner>
79 ${base_aclnn_binary_dir}/inner80 ${base_aclnn_binary_dir}/inner
81+ DEPENDS op_host_aclnnInner
80 )82 )
81endif ()83endif ()
82add_custom_target(opbuild_gen_inner84add_custom_target(opbuild_gen_inner
@@ -93,6 +95,7 @@ if (generate_exclude_proto_srcs)
93 ${OP_BUILD_TOOL}95 ${OP_BUILD_TOOL}
94 $<TARGET_FILE:op_host_aclnnExc>96 $<TARGET_FILE:op_host_aclnnExc>
95 ${base_aclnn_binary_dir}/exc97 ${base_aclnn_binary_dir}/exc
98+ DEPENDS op_host_aclnnExc
96 )99 )
97endif ()100endif ()
98add_custom_target(opbuild_gen_exc101add_custom_target(opbuild_gen_exc
@@ -151,10 +154,14 @@ if (ENABLE_OPS_HOST AND NOT PREPARE_BUILD)
151 get_property(_infer_srcs GLOBAL PROPERTY GYM_INFER_SRCS)154 get_property(_infer_srcs GLOBAL PROPERTY GYM_INFER_SRCS)
152 get_property(_tiling_srcs GLOBAL PROPERTY GYM_TILING_SRCS)155 get_property(_tiling_srcs GLOBAL PROPERTY GYM_TILING_SRCS)
153 get_property(_opapi_srcs GLOBAL PROPERTY GYM_OPAPI_SRCS)156 get_property(_opapi_srcs GLOBAL PROPERTY GYM_OPAPI_SRCS)
157+ # Collect generated headers for kernel rebuild dependencies; force-includes
158+ # below still use the per-source mapping to keep operators isolated.
159+ get_property(_pypto_gen_dirs GLOBAL PROPERTY GYM_PYPTO_GEN_DIRS)
154 get_property(_tiling_check_srcs GLOBAL PROPERTY GYM_TILING_CHECK_SRCS)160 get_property(_tiling_check_srcs GLOBAL PROPERTY GYM_TILING_CHECK_SRCS)
155 list(REMOVE_DUPLICATES _infer_srcs)161 list(REMOVE_DUPLICATES _infer_srcs)
156 list(REMOVE_DUPLICATES _tiling_srcs)162 list(REMOVE_DUPLICATES _tiling_srcs)
157 list(REMOVE_DUPLICATES _opapi_srcs)163 list(REMOVE_DUPLICATES _opapi_srcs)
164+ list(REMOVE_DUPLICATES _pypto_gen_dirs)
158 list(REMOVE_DUPLICATES _tiling_check_srcs)165 list(REMOVE_DUPLICATES _tiling_check_srcs)
159 166 
160 # autogen 源清单167 # autogen 源清单
@@ -347,14 +354,18 @@ if (ENABLE_OPS_HOST AND NOT PREPARE_BUILD)
347 # ---------- ops-info.json (三 ini 合成) ----------354 # ---------- ops-info.json (三 ini 合成) ----------
348 foreach (compute_unit ${ASCEND_COMPUTE_UNIT})355 foreach (compute_unit ${ASCEND_COMPUTE_UNIT})
349 set(_ops_info_json ${ASCEND_AUTOGEN_DIR}/aic-${compute_unit}-ops-info.json)356 set(_ops_info_json ${ASCEND_AUTOGEN_DIR}/aic-${compute_unit}-ops-info.json)
350- add_custom_command(OUTPUT ${_ops_info_json}357+ # 名单可能在单算子与 ALL 之间切换;每次按本次 op_build 的 ini 重建清单,
358+ # 避免沿用构建目录中旧的单算子 JSON。
359+ add_custom_target(generate_ops_info_${compute_unit} ALL
351 COMMAND ${Python3_EXECUTABLE} ${GYM_UTIL_SCRIPT_DIR}/parse_ini_to_json.py360 COMMAND ${Python3_EXECUTABLE} ${GYM_UTIL_SCRIPT_DIR}/parse_ini_to_json.py
352 ${base_aclnn_binary_dir}/aic-${compute_unit}-ops-info.ini361 ${base_aclnn_binary_dir}/aic-${compute_unit}-ops-info.ini
353 ${base_aclnn_binary_dir}/inner/aic-${compute_unit}-ops-info.ini362 ${base_aclnn_binary_dir}/inner/aic-${compute_unit}-ops-info.ini
354 ${base_aclnn_binary_dir}/exc/aic-${compute_unit}-ops-info.ini363 ${base_aclnn_binary_dir}/exc/aic-${compute_unit}-ops-info.ini
355- ${_ops_info_json}364+ ${_ops_info_json}.tmp.json
365+ COMMAND ${CMAKE_COMMAND} -E copy_if_different ${_ops_info_json}.tmp.json ${_ops_info_json}
366+ COMMAND ${CMAKE_COMMAND} -E rm -f ${_ops_info_json}.tmp.json
367+ BYPRODUCTS ${_ops_info_json}
356 DEPENDS opbuild_gen_default opbuild_gen_inner opbuild_gen_exc)368 DEPENDS opbuild_gen_default opbuild_gen_inner opbuild_gen_exc)
357- add_custom_target(generate_ops_info_${compute_unit} ALL DEPENDS ${_ops_info_json})
358 add_dependencies(prepare_build generate_ops_info_${compute_unit})369 add_dependencies(prepare_build generate_ops_info_${compute_unit})
359 endforeach ()370 endforeach ()
360 371 
@@ -384,6 +395,23 @@ if (ENABLE_OPS_HOST AND NOT PREPARE_BUILD)
384 foreach(_kernel_target ${_gym_kernel_targets})395 foreach(_kernel_target ${_gym_kernel_targets})
385 add_dependencies(${_kernel_target} gym_opstore_stage)396 add_dependencies(${_kernel_target} gym_opstore_stage)
386 endforeach ()397 endforeach ()
398+ # 依赖 tiling 的实际输入文件;部分 SDK 的 depfile 会让 host 库反复重链,
399+ # 不能仅因 .so 的时间戳变化就重编所有 kernel。
400+ set(_kernel_tiling_inputs ${_tiling_srcs})
401+ foreach(_tiling_src ${_tiling_srcs})
402+ get_filename_component(_tiling_host_dir ${_tiling_src} DIRECTORY)
403+ file(GLOB _tiling_host_headers ${_tiling_host_dir}/*.h)
404+ list(APPEND _kernel_tiling_inputs ${_tiling_host_headers})
405+ endforeach()
406+ foreach(_gen_dir ${_pypto_gen_dirs})
407+ file(GLOB _gen_headers ${_gen_dir}/*.h)
408+ list(APPEND _kernel_tiling_inputs ${_gen_headers})
409+ endforeach()
410+ get_property(_gym_kernel_outputs GLOBAL PROPERTY GYM_KERNEL_OUTPUTS)
411+ foreach(_kernel_output ${_gym_kernel_outputs})
412+ add_custom_command(OUTPUT ${_kernel_output} APPEND
413+ DEPENDS ${_kernel_tiling_inputs} ${ASCEND_AUTOGEN_DIR}/aic-${ASCEND_COMPUTE_UNIT}-ops-info.json)
414+ endforeach()
387 415 
388 # ---------- vendors staging install 规则(COMPONENT = 包组件, 供 CPack staging 收集) ----------416 # ---------- vendors staging install 规则(COMPONENT = 包组件, 供 CPack staging 收集) ----------
389 install(TARGETS cust_opapi LIBRARY DESTINATION ${_vendor_dir}/op_api/lib COMPONENT ${VENDOR_NAME})417 install(TARGETS cust_opapi LIBRARY DESTINATION ${_vendor_dir}/op_api/lib COMPONENT ${VENDOR_NAME})
@@ -12,14 +12,41 @@
12 12 
13# 发现 ops/{pro,tensor} 下的算子目录(锚定算子级 CMakeLists.txt);13# 发现 ops/{pro,tensor} 下的算子目录(锚定算子级 CMakeLists.txt);
14# 算子契约: <op>/CMakeLists.txt(dispatcher) + <op>/op_host/(算子身份判定, 过滤中间层目录);14# 算子契约: <op>/CMakeLists.txt(dispatcher) + <op>/op_host/(算子身份判定, 过滤中间层目录);
15-# 显式 --ops 时仅编名单内算子, 否则全量15+# ALL 使用 ops/pro/build_ops.yaml;显式 --ops 使用命令行名单。
16function(gym_op_discovery OP_LIST OP_DIR_LIST)16function(gym_op_discovery OP_LIST OP_DIR_LIST)
17 set(_OP_LIST)17 set(_OP_LIST)
18 set(_OP_DIR_LIST)18 set(_OP_DIR_LIST)
19 19 
20+ if(NOT Python3_EXECUTABLE)
21+ find_package(Python3 REQUIRED COMPONENTS Interpreter)
22+ endif()
23+ set(_requested_ops "ALL")
24+ if(DEFINED ASCEND_OP_NAME AND NOT "${ASCEND_OP_NAME}" STREQUAL "")
25+ set(_requested_ops "${ASCEND_OP_NAME}")
26+ endif()
27+ set(_scope_script "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/scripts/select_run_ops.py")
28+ execute_process(
29+ COMMAND "${Python3_EXECUTABLE}" "${_scope_script}"
30+ --source-root "${CMAKE_CURRENT_SOURCE_DIR}" --ops "${_requested_ops}" --format paths
31+ RESULT_VARIABLE _scope_rc OUTPUT_VARIABLE _scope_names ERROR_VARIABLE _scope_error
32+ OUTPUT_STRIP_TRAILING_WHITESPACE)
33+ if(NOT _scope_rc EQUAL 0)
34+ message(FATAL_ERROR "run operator selection failed: ${_scope_error}")
35+ endif()
36+ string(REPLACE "\n" ";" _scope_paths "${_scope_names}")
37+ set(_selected_dirs)
20 set(_explicit_ops)38 set(_explicit_ops)
21- if(DEFINED ASCEND_OP_NAME AND NOT "${ASCEND_OP_NAME}" STREQUAL "ALL")39+ foreach(_scope_path ${_scope_paths})
22- set(_explicit_ops ${ASCEND_OP_NAME})40+ list(APPEND _selected_dirs "${CMAKE_CURRENT_SOURCE_DIR}/${_scope_path}")
41+ get_filename_component(_scope_name "${_scope_path}" NAME)
42+ list(APPEND _explicit_ops "${_scope_name}")
43+ endforeach()
44+ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_scope_script}")
45+ string(TOUPPER "${_requested_ops}" _scope_mode)
46+ if(_scope_mode STREQUAL "ALL")
47+ set(_scope_file "${CMAKE_CURRENT_SOURCE_DIR}/ops/pro/build_ops.yaml")
48+ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_scope_file}")
49+ message(STATUS "gym ALL scope: ${_scope_file} -> ${_scope_paths}")
23 endif()50 endif()
24 51 
25 # gym 树形: ops/<paradigm>/<network|experimental|common>/<op>/ (实测本 cmake GLOB 的52 # gym 树形: ops/<paradigm>/<network|experimental|common>/<op>/ (实测本 cmake GLOB 的
@@ -42,7 +69,7 @@ function(gym_op_discovery OP_LIST OP_DIR_LIST)
42 get_filename_component(_op_name "${_op_dir}" NAME)69 get_filename_component(_op_name "${_op_dir}" NAME)
43 70 
44 # 白名单过滤 (与 setup.py _PARADIGM_DIRS 语义对账: 仅 pro/tensor 两棵树被 glob, 历史目录天然不参与)71 # 白名单过滤 (与 setup.py _PARADIGM_DIRS 语义对账: 仅 pro/tensor 两棵树被 glob, 历史目录天然不参与)
45- if(_explicit_ops AND NOT _op_name IN_LIST _explicit_ops)72+ if(NOT _op_dir IN_LIST _selected_dirs)
46 continue()73 continue()
47 endif()74 endif()
48 75 
@@ -50,31 +77,9 @@ function(gym_op_discovery OP_LIST OP_DIR_LIST)
50 list(APPEND _OP_DIR_LIST ${_op_dir})77 list(APPEND _OP_DIR_LIST ${_op_dir})
51 endforeach()78 endforeach()
52 79 
53- # 孤儿检测: 有 op_host 但缺算子级 CMakeLists(dispatcher)的算子不可见, 违约即报错80+ # 算子目录缺少 op-level CMakeLists 的情况已由 select_run_ops.py 在返回前拒绝
54- file(GLOB _orphan_op_host_files81+ # (no binary build directory),此处不再重复检测。
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 82 
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)83 if(NOT _OP_LIST)
79 message(FATAL_ERROR "gym_op_discovery: no operator found under ops/{pro,tensor} (explicit ops: '${_explicit_ops}')")84 message(FATAL_ERROR "gym_op_discovery: no operator found under ops/{pro,tensor} (explicit ops: '${_explicit_ops}')")
80 endif()85 endif()
@@ -220,10 +225,14 @@ endfunction()
220function(add_ops_src_copy)225function(add_ops_src_copy)
221 cmake_parse_arguments(SRC_COPY "" "TARGET_NAME;SRC;DST;COMPUTE_UNIT" "" ${ARGN})226 cmake_parse_arguments(SRC_COPY "" "TARGET_NAME;SRC;DST;COMPUTE_UNIT" "" ${ARGN})
222 set(_stamp ${SRC_COPY_DST}/.${SRC_COPY_TARGET_NAME}.done)227 set(_stamp ${SRC_COPY_DST}/.${SRC_COPY_TARGET_NAME}.done)
228+ file(GLOB_RECURSE _copy_sources CONFIGURE_DEPENDS
229+ "${SRC_COPY_SRC}/*.py" "${SRC_COPY_SRC}/*.cpp" "${SRC_COPY_SRC}/*.h"
230+ "${SRC_COPY_SRC}/*.cmake" "${SRC_COPY_SRC}/*.json" "${SRC_COPY_SRC}/*.ini"
231+ "${SRC_COPY_SRC}/CMakeLists.txt")
223 add_custom_command(OUTPUT ${_stamp}232 add_custom_command(OUTPUT ${_stamp}
224 COMMAND ${CMAKE_COMMAND} -E copy_directory ${SRC_COPY_SRC} ${SRC_COPY_DST}233 COMMAND ${CMAKE_COMMAND} -E copy_directory ${SRC_COPY_SRC} ${SRC_COPY_DST}
225 COMMAND ${CMAKE_COMMAND} -E touch ${_stamp}234 COMMAND ${CMAKE_COMMAND} -E touch ${_stamp}
226- DEPENDS ${SRC_COPY_SRC}235+ DEPENDS ${SRC_COPY_SRC} ${_copy_sources}
227 VERBATIM)236 VERBATIM)
228 add_custom_target(${SRC_COPY_TARGET_NAME} ALL DEPENDS ${_stamp})237 add_custom_target(${SRC_COPY_TARGET_NAME} ALL DEPENDS ${_stamp})
229endfunction()238endfunction()
@@ -246,6 +255,7 @@ function(add_bin_compile_target)
246 endforeach()255 endforeach()
247 256 
248 set(_ops_target_list)257 set(_ops_target_list)
258+ set(_kernel_op_names)
249 file(GLOB compile_scripts ${GEN_OUT_DIR}/*.sh)259 file(GLOB compile_scripts ${GEN_OUT_DIR}/*.sh)
250 260 
251 foreach(bin_script ${compile_scripts})261 foreach(bin_script ${compile_scripts})
@@ -270,6 +280,7 @@ function(add_bin_compile_target)
270 add_custom_target(${OP_TARGET_NAME})280 add_custom_target(${OP_TARGET_NAME})
271 add_dependencies(ops_gym_kernel ${OP_TARGET_NAME})281 add_dependencies(ops_gym_kernel ${OP_TARGET_NAME})
272 list(APPEND _ops_target_list ${OP_TARGET_NAME})282 list(APPEND _ops_target_list ${OP_TARGET_NAME})
283+ list(APPEND _kernel_op_names ${op_file})
273 set_property(GLOBAL APPEND PROPERTY GYM_KERNEL_TARGETS ${OP_TARGET_NAME})284 set_property(GLOBAL APPEND PROPERTY GYM_KERNEL_TARGETS ${OP_TARGET_NAME})
274 285 
275 set(OP_SRC_OUT_DIR ${SRC_OUT_DIR}/${op_file})286 set(OP_SRC_OUT_DIR ${SRC_OUT_DIR}/${op_file})
@@ -292,10 +303,12 @@ function(add_bin_compile_target)
292 COMPUTE_UNIT ${BINARY_COMPUTE_UNIT})303 COMPUTE_UNIT ${BINARY_COMPUTE_UNIT})
293 304 
294 set(_pypto_install_stamp ${OP_SRC_OUT_DIR}/op_kernel/.pypto_install.done)305 set(_pypto_install_stamp ${OP_SRC_OUT_DIR}/op_kernel/.pypto_install.done)
306+ file(GLOB _pypto_install_headers ${${op_file}_pypto_gen_dir}/*.h)
295 add_custom_command(OUTPUT ${_pypto_install_stamp}307 add_custom_command(OUTPUT ${_pypto_install_stamp}
296 COMMAND ${CMAKE_COMMAND} -E copy_directory ${${op_file}_pypto_gen_dir} ${OP_SRC_OUT_DIR}/op_kernel308 COMMAND ${CMAKE_COMMAND} -E copy_directory ${${op_file}_pypto_gen_dir} ${OP_SRC_OUT_DIR}/op_kernel
297 COMMAND ${CMAKE_COMMAND} -E touch ${_pypto_install_stamp}309 COMMAND ${CMAKE_COMMAND} -E touch ${_pypto_install_stamp}
298 DEPENDS ${OP_TARGET_NAME}_src_copy310 DEPENDS ${OP_TARGET_NAME}_src_copy
311+ ${OP_SRC_OUT_DIR}/.${OP_TARGET_NAME}_src_copy.done ${_pypto_install_headers}
299 VERBATIM)312 VERBATIM)
300 add_custom_target(${OP_TARGET_NAME}_pypto_install DEPENDS ${_pypto_install_stamp})313 add_custom_target(${OP_TARGET_NAME}_pypto_install DEPENDS ${_pypto_install_stamp})
301 314 
@@ -315,6 +328,7 @@ function(add_bin_compile_target)
315 endif ()328 endif ()
316 329 
317 set(_BUILD_FLAG ${GEN_OUT_DIR}/${OP_TARGET_NAME}_${op_index}.done)330 set(_BUILD_FLAG ${GEN_OUT_DIR}/${OP_TARGET_NAME}_${op_index}.done)
331+ set_property(GLOBAL APPEND PROPERTY GYM_KERNEL_OUTPUTS ${_BUILD_FLAG})
318 # TILINGKEY_PAR_COMPILE/BIN_FILENAME_HASHED 由 CANN 编译工具链消费332 # TILINGKEY_PAR_COMPILE/BIN_FILENAME_HASHED 由 CANN 编译工具链消费
319 # (BIN_FILENAME_HASHED=1 即 <OpType>_<md5>.o 哈希文件名来源, ascendc_common_utility.py)333 # (BIN_FILENAME_HASHED=1 即 <OpType>_<md5>.o 哈希文件名来源, ascendc_common_utility.py)
320 set(_BUILD_COMMAND export TILINGKEY_PAR_COMPILE=1 &&)334 set(_BUILD_COMMAND export TILINGKEY_PAR_COMPILE=1 &&)
@@ -331,6 +345,8 @@ function(add_bin_compile_target)
331 add_custom_command(OUTPUT ${_BUILD_FLAG}345 add_custom_command(OUTPUT ${_BUILD_FLAG}
332 COMMAND ${_BUILD_COMMAND}346 COMMAND ${_BUILD_COMMAND}
333 COMMAND touch ${_BUILD_FLAG}347 COMMAND touch ${_BUILD_FLAG}
348+ DEPENDS ${bin_script} ${SRC_OUT_DIR}/${op_file}/${op_type}.py
349+ ${SRC_OUT_DIR}/${op_file}/op_kernel/.pypto_install.done
334 WORKING_DIRECTORY ${GEN_OUT_DIR})350 WORKING_DIRECTORY ${GEN_OUT_DIR})
335 add_custom_target(${OP_TARGET_NAME}_${op_index} DEPENDS ${_BUILD_FLAG})351 add_custom_target(${OP_TARGET_NAME}_${op_index} DEPENDS ${_BUILD_FLAG})
336 add_dependencies(${OP_TARGET_NAME}_${op_index}352 add_dependencies(${OP_TARGET_NAME}_${op_index}
@@ -342,9 +358,13 @@ function(add_bin_compile_target)
342 if (_ops_target_list)358 if (_ops_target_list)
343 set(OPS_CONFIG_TARGET ops_config_${BINARY_COMPUTE_UNIT})359 set(OPS_CONFIG_TARGET ops_config_${BINARY_COMPUTE_UNIT})
344 set(BINARY_INFO_CONFIG_FILE ${BIN_OUT_DIR}/binary_info_config.json)360 set(BINARY_INFO_CONFIG_FILE ${BIN_OUT_DIR}/binary_info_config.json)
345- add_custom_command(OUTPUT ${BINARY_INFO_CONFIG_FILE}361+ # 生成本次所选全部算子的汇总,每次在 kernel 完成后刷新;输出文件存在
346- COMMAND ${Python3_EXECUTABLE} ${GYM_UTIL_SCRIPT_DIR}/ascendc_ops_config.py -p ${BIN_OUT_DIR} -s ${BINARY_COMPUTE_UNIT})362+ # 不代表其内容已经覆盖新增算子,也不能把旧目录内未选择的算子带入包。
347- add_custom_target(${OPS_CONFIG_TARGET} DEPENDS ${BINARY_INFO_CONFIG_FILE})363+ add_custom_target(${OPS_CONFIG_TARGET}
364+ COMMAND ${Python3_EXECUTABLE} ${GYM_UTIL_SCRIPT_DIR}/ascendc_ops_config.py
365+ -p ${BIN_OUT_DIR} -s ${BINARY_COMPUTE_UNIT} --ops ${_kernel_op_names}
366+ BYPRODUCTS ${BINARY_INFO_CONFIG_FILE}
367+ VERBATIM)
348 add_dependencies(ops_gym_config ${OPS_CONFIG_TARGET})368 add_dependencies(ops_gym_config ${OPS_CONFIG_TARGET})
349 foreach(_op_target ${_ops_target_list})369 foreach(_op_target ${_ops_target_list})
350 add_dependencies(${OPS_CONFIG_TARGET} ${_op_target})370 add_dependencies(${OPS_CONFIG_TARGET} ${_op_target})
@@ -11,6 +11,7 @@
11 11 
12# 二次构建入口: 主 configure 期由 cmake/config.cmake 调用,12# 二次构建入口: 主 configure 期由 cmake/config.cmake 调用,
13# 以 PREPARE_BUILD=ON 再跑一次 cmake 并 make prepare_build, 产出 autogen 与 impl.13# 以 PREPARE_BUILD=ON 再跑一次 cmake 并 make prepare_build, 产出 autogen 与 impl.
14+# 准备阶段不编译 Torch 绑定,显式关闭以避免使用主构建的默认开启值。
14 15 
15CPU_NUM=$(($(grep -c "^processor" /proc/cpuinfo)*2))16CPU_NUM=$(($(grep -c "^processor" /proc/cpuinfo)*2))
16JOB_NUM="-j${CPU_NUM}"17JOB_NUM="-j${CPU_NUM}"
@@ -43,6 +44,7 @@ cd "${PATH_TO_BUILD}"
43cmake ${PATH_TO_SOURCE} \44cmake ${PATH_TO_SOURCE} \
44 -DBUILD_OPEN_PROJECT=ON \45 -DBUILD_OPEN_PROJECT=ON \
45 -DPREPARE_BUILD=ON \46 -DPREPARE_BUILD=ON \
47+ -DENABLE_TORCH_BINDINGS=OFF \
46 -DCUSTOM_ASCEND_CANN_PACKAGE_PATH=${ASCEND_CANN_PACKAGE_PATH} \48 -DCUSTOM_ASCEND_CANN_PACKAGE_PATH=${ASCEND_CANN_PACKAGE_PATH} \
47 -DASCEND_AUTOGEN_DIR=${ASCEND_AUTOGEN_DIR} \49 -DASCEND_AUTOGEN_DIR=${ASCEND_AUTOGEN_DIR} \
48 -DASCEND_BINARY_OUT_DIR=${ASCEND_BINARY_OUT_DIR} \50 -DASCEND_BINARY_OUT_DIR=${ASCEND_BINARY_OUT_DIR} \
@@ -0,0 +1,122 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+"""Resolve the .run operator scope shared by CMake and system tests."""
10+import argparse
11+import itertools
12+import logging
13+from pathlib import Path, PurePosixPath
14+import re
15+import sys
16+ 
17+ 
18+_PATH_PART = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]*")
19+ 
20+ 
21+def _available_operators(root):
22+ available = {}
23+ for paradigm, depth in itertools.product(("pro", "tensor"), (1, 2, 3)):
24+ pattern = "/".join(["*"] * depth + ["CMakeLists.txt"])
25+ for cmake in (root / "ops" / paradigm).glob(pattern):
26+ op = cmake.parent
27+ if (op / "op_host").is_dir():
28+ available.setdefault(op.name, []).append(op)
29+ return available
30+ 
31+ 
32+def _load_manifest(manifest):
33+ try:
34+ import yaml
35+ except ImportError as error:
36+ raise ValueError("reading build_ops.yaml requires PyYAML; install PyYAML>=6.0") from error
37+ try:
38+ with manifest.open(encoding="utf-8") as stream:
39+ entries = yaml.safe_load(stream)
40+ except (OSError, yaml.YAMLError) as error:
41+ raise ValueError(f"{manifest}: {error}") from error
42+ if entries is None:
43+ entries = []
44+ if not isinstance(entries, list) or any(not isinstance(entry, str) or not entry for entry in entries):
45+ raise ValueError(f"{manifest}: expected a YAML list of nonempty operator path strings")
46+ if not entries:
47+ raise ValueError(f"{manifest}: no operators listed; add at least one uncommented path")
48+ return entries
49+ 
50+ 
51+def _select_from_manifest(root, available, manifest):
52+ selected = []
53+ for entry in _load_manifest(manifest):
54+ relative = PurePosixPath(entry)
55+ if (relative.is_absolute() or entry != relative.as_posix() or
56+ any(part in (".", "..") or not _PATH_PART.fullmatch(part) for part in relative.parts)):
57+ raise ValueError(f"{manifest}: invalid path relative to ops/pro: {entry!r}")
58+ op = root / "ops/pro" / relative
59+ if op not in available.get(op.name, []):
60+ raise ValueError(f"{manifest}: {entry!r} has no binary build directory "
61+ "(requires operator CMakeLists.txt and op_host/)")
62+ selected.append(op)
63+ return selected
64+ 
65+ 
66+def _select_from_names(available, requested):
67+ names = [name.strip() for name in requested.replace(";", ",").split(",")]
68+ if not all(names):
69+ raise ValueError("--ops must be ALL or a nonempty comma-separated operator list")
70+ selected = []
71+ for name in names:
72+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
73+ raise ValueError(f"invalid operator directory name: {name!r}")
74+ candidates = available.get(name, [])
75+ if not candidates:
76+ raise ValueError(f"operator {name!r} has no binary build directory "
77+ "(requires operator CMakeLists.txt and op_host/)")
78+ if len(candidates) > 1:
79+ raise ValueError(f"ambiguous operator {name!r}: {candidates}")
80+ selected.append(candidates[0])
81+ return selected
82+ 
83+ 
84+def select_run_op_dirs(source_root, requested="ALL"):
85+ root = Path(source_root).resolve()
86+ requested = requested.strip()
87+ available = _available_operators(root)
88+ if requested.upper() == "ALL":
89+ selected = _select_from_manifest(root, available, root / "ops/pro/build_ops.yaml")
90+ else:
91+ selected = _select_from_names(available, requested)
92+ selected = sorted(set(selected))
93+ names = [op.name for op in selected]
94+ if len(names) != len(set(names)):
95+ raise ValueError("selected operator directories must have unique operator names")
96+ return selected
97+ 
98+ 
99+def select_run_ops(source_root, requested="ALL"):
100+ return [op.name for op in select_run_op_dirs(source_root, requested)]
101+ 
102+ 
103+def main():
104+ parser = argparse.ArgumentParser(description=__doc__)
105+ parser.add_argument("--source-root", required=True, type=Path)
106+ parser.add_argument("--ops", default="ALL")
107+ parser.add_argument("--format", choices=("names", "paths"), default="names")
108+ args = parser.parse_args()
109+ logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
110+ try:
111+ selected = select_run_op_dirs(args.source_root, args.ops)
112+ except ValueError as error:
113+ parser.error(str(error))
114+ if args.format == "paths":
115+ root = args.source_root.resolve()
116+ logging.info("%s", "\n".join(op.relative_to(root).as_posix() for op in selected))
117+ else:
118+ logging.info("%s", "\n".join(op.name for op in selected))
119+ 
120+ 
121+if __name__ == "__main__":
122+ main()
@@ -615,6 +615,12 @@ check_stop
615 f">> {self.op_file}-{str(index)}.txt\n"615 f">> {self.op_file}-{str(index)}.txt\n"
616 )616 )
617 build_cmd_var += f'echo "[{self.soc}] Generating {bin_file} Done"\n'617 build_cmd_var += f'echo "[{self.soc}] Generating {bin_file} Done"\n'
618+ # These scripts are kernel build dependencies. Preserve their timestamps
619+ # when only rerunning command generation (for example during packaging).
620+ if os.path.isfile(compile_file):
621+ with open(compile_file, encoding="utf-8") as existing:
622+ if existing.read() == build_cmd_var:
623+ return
618 with os.fdopen(624 with os.fdopen(
619 os.open(compile_file, const_var.WFLAGS, const_var.WMODES), "w"625 os.open(compile_file, const_var.WFLAGS, const_var.WMODES), "w"
620 ) as fd:626 ) as fd:
@@ -245,12 +245,14 @@ def gen_ops_config(json_file, soc, binary_info_config, config):
245 245 
246 246 
247def check_single_op_is_void(root_dir):247def check_single_op_is_void(root_dir):
248+ candidates = [root_dir]
248 for root, dirs, _ in os.walk(root_dir):249 for root, dirs, _ in os.walk(root_dir):
249 for sub_dir in dirs:250 for sub_dir in dirs:
250- dir_path = os.path.join(root, sub_dir)251+ candidates.append(os.path.join(root, sub_dir))
251- if len(os.listdir(dir_path)) == 0:252+ for dir_path in candidates:
252- print(f"[ERROR] op {sub_dir}: not any obj compile success")253+ if os.path.isdir(dir_path) and not os.listdir(dir_path):
253- sys.exit(1)254+ raise RuntimeError(
255+ f"[ERROR] op {os.path.basename(dir_path)}: not any obj compile success")
254 256 
255 257 
256def write_jsons(out_dir, file_list, config):258def write_jsons(out_dir, file_list, config):
@@ -288,11 +290,15 @@ def generate_operator_cfg_file(
288 write_jsons(out_dir, file_list, config)290 write_jsons(out_dir, file_list, config)
289 291 
290 292 
291-def gen_all_config(root_dir, soc, out_dir, skip_binary_info_config, op_range="all"):293+def gen_all_config(root_dir, soc, out_dir, skip_binary_info_config, op_range="all", op_names=None):
294+ roots = [os.path.join(root_dir, name) for name in op_names] if op_names else [root_dir]
292 if op_range != "relocatable":295 if op_range != "relocatable":
293- check_single_op_is_void(root_dir)296+ # Validate only the operators selected for this build. Empty directories
294- all_json_files = get_specified_suffix_file(root_dir, ".json")297+ # left by earlier/unrelated builds must not fail a filtered build.
295- relocatable_json_files = get_specified_suffix_file(root_dir, "_relocatable.json")298+ for root in roots:
299+ check_single_op_is_void(root)
300+ all_json_files = [path for root in roots for path in get_specified_suffix_file(root, ".json")]
301+ relocatable_json_files = [path for path in all_json_files if path.endswith("_relocatable.json")]
296 normal_json_files = list(set(all_json_files) - set(relocatable_json_files))302 normal_json_files = list(set(all_json_files) - set(relocatable_json_files))
297 os.makedirs(out_dir, exist_ok=True)303 os.makedirs(out_dir, exist_ok=True)
298 304 
@@ -362,6 +368,7 @@ def args_prase():
362 )368 )
363 369 
364 parser.add_argument("-o", "--out", nargs="?", help="Output directory.")370 parser.add_argument("-o", "--out", nargs="?", help="Output directory.")
371+ parser.add_argument("--ops", nargs="+", help="Only include these operator directories.")
365 372 
366 parser.add_argument(373 parser.add_argument(
367 "--skip-binary-info-config",374 "--skip-binary-info-config",
@@ -387,9 +394,13 @@ def main():
387 else:394 else:
388 out_dir = args.out395 out_dir = args.out
389 396 
390- gen_all_config(397+ try:
391- args.path, args.soc, out_dir, args.skip_binary_info_config, args.op_range398+ gen_all_config(
392- )399+ args.path, args.soc, out_dir, args.skip_binary_info_config, args.op_range, args.ops
400+ )
401+ except RuntimeError as error:
402+ print(error)
403+ sys.exit(1)
393 404 
394 405 
395if __name__ == "__main__":406if __name__ == "__main__":
@@ -115,8 +115,8 @@ def pytest_addoption(parser: pytest.Parser):
115 help="Number of cards required for each test case. Default is 1 (single-card cases)."115 help="Number of cards required for each test case. Default is 1 (single-card cases)."
116 )116 )
117 parser.addoption(117 parser.addoption(
118- "--mode", choices=["jit", "aclnn"], default="jit",118+ "--mode", choices=["jit", "aclnn", "torch"], default="jit",
119- help="Test execution mode: jit (Python host wrapper) / aclnn (C++ aclnn via pybind11 bridge)"119+ help="Test execution mode: jit / aclnn (test bridge) / torch (installed binary Torch binding)"
120 )120 )
121 parser.addoption(121 parser.addoption(
122 "--aclnn-lib-dir", default="",122 "--aclnn-lib-dir", default="",
@@ -293,13 +293,24 @@ def _is_case_match_soc(item, target_soc):
293 return target_tag in supported_socs293 return target_tag in supported_socs
294 294 
295 295 
296+def _is_host_only(item) -> bool:
297+ """Host-only unit tests live under tests/unit and must bypass device filtering."""
298+ path = Path(str(item.fspath)).resolve()
299+ return (Path(__file__).resolve().parent / "tests" / "unit") in path.parents
300+ 
301+ 
296@pytest.hookimpl(trylast=True)302@pytest.hookimpl(trylast=True)
297def pytest_collection_modifyitems(config, items):303def pytest_collection_modifyitems(config, items):
298 if not items:304 if not items:
299 return305 return
300 306 
301- target_soc = _get_soc_version()307+ # tests/unit do not require an NPU, so never query the SoC version for them.
302- filtered_items = [item for item in items if _is_case_match_soc(item, target_soc)]308+ host_items = [item for item in items if _is_host_only(item)]
309+ device_items = [item for item in items if not _is_host_only(item)]
310+ filtered_items = list(host_items)
311+ if device_items:
312+ target_soc = _get_soc_version()
313+ filtered_items += [item for item in device_items if _is_case_match_soc(item, target_soc)]
303 314 
304 cards_per_case = config.getoption("--cards-per-case", 1)315 cards_per_case = config.getoption("--cards-per-case", 1)
305 card_filtered_items = [item for item in filtered_items316 card_filtered_items = [item for item in filtered_items
@@ -8,10 +8,10 @@ PyPTO-Gym 是 PyPTO 实验算子仓,应该提供从算子源码到可安装产
8 8 
9重构后对于 Pro 模式算子,每个算子只需编写一次,即可同时交付两种产物形态:9重构后对于 Pro 模式算子,每个算子只需编写一次,即可同时交付两种产物形态:
10 10 
11-| 产物 | 命令 | 安装方式 | 适用场景 |11+| 产物 | 命令 | 安装方式 | 适用场景 |
12-| --- | --- | --- | --- |12+| ------------------------------- | -------------------------------------- | --------------- | --------------------------------- |
13-| **whl**(JIT 直调) | `python3 build_ci.py --pkg-type whl` | `pip install` | 开发调试、快速验证、PIP源生态发布 |13+| **whl**(JIT 直调) | `python3 build_ci.py --pkg-type whl` | `pip install` | 开发调试、快速验证、PIP源生态发布 |
14-| **.run**(custom run 包) | `python3 build_ci.py --pkg-type run` | `bash *.run` | 生产部署、批量交付 |14+| **.run**(custom run 包) | `python3 build_ci.py --pkg-type run` | `bash *.run` | 生产部署、批量交付 |
15 15 
16### 1.2. 两种产物模式的区别16### 1.2. 两种产物模式的区别
17 17 
@@ -38,31 +38,67 @@ bash cann-950-pypto_gym_9.2.0_linux-aarch64.run
38- 内含预编译产物:kernel `.o`(按 dtype 组合)+ host 侧三个 `.so` + aclnn 头文件 + ops-info.json38- 内含预编译产物:kernel `.o`(按 dtype 组合)+ host 侧三个 `.so` + aclnn 头文件 + ops-info.json
39- 安装后零 JIT 开销,aclnn 接口直接查找已编译二进制39- 安装后零 JIT 开销,aclnn 接口直接查找已编译二进制
40 40 
41+正式 Torch 绑定默认一并预编译、装入 `.run`,当前支持
42+`mega_mhc`。已加载 CANN 基础环境时,安装到其 `opp` 后即可使用
43+`pypto_gym.mega_mhc(...)`;直接调用 `torch.ops.pypto_gym.mega_mhc(...)` 前需先
44+`import pypto_gym` 并调用 `pypto_gym.load()`(或先访问任一 `pypto_gym.<op>`)。
45+`import pypto_gym` 本身不导入 torch、不加载绑定库,无需运行时编译。
46+构建环境需有 torch/torch_npu;部署环境需与其 ABI 兼容。标准 CANN 安装自动登记
47+Python 入口并使用绑定库的相对运行时路径,无需额外 source vendor 脚本。
48+自定义位置安装仍可使用 vendor 的 `set_env.bash`。
49+ 
50+```bash
51+python3 build_ci.py --pkg-type run --ops mega_mhc --stest
52+```
53+ 
54+默认情况下,`--stest` 对已提供绑定的算子使用 `--mode torch`;未提供绑定的算子使用 `--mode aclnn`。
55+`run` 默认尝试启用绑定,但若所选算子**都没有**接入绑定,会自动降级为 ACLNN-only 包(打印
56+WARNING),仍按原有的 ACLNN 方式调用和测试。仅需 ACLNN 接口时可显式传
57+`--no-torch-bindings`(手工 CMake 对应 `-DENABLE_TORCH_BINDINGS=OFF`);显式传
58+`--torch-bindings` 则要求所选算子中至少有一个提供绑定,否则 configure 阶段报错。
59+`whl` 构建保持 JIT 模式,不启用此绑定。
60+详细接口和新算子接入方式见 [Torch 绑定说明](../torch_extension/README.md)。
61+ 
41### 1.3. 快速开始62### 1.3. 快速开始
42 63 
43#### 1.3.1. 前置条件64#### 1.3.1. 前置条件
44 65 
45-| 依赖 | 要求 |66+| 依赖 | 要求 |
46-| --- | --- |67+| ----------------- | -------------------------------------------------- |
47-| CANN 包 | ≥ 9.2.0(含 `op_build` 工具) |68+| CANN 包 | ≥ 9.2.0(含 `op_build` 工具) |
48-| bisheng / asc_opc | 在 PATH 中(`source CANN set_env.sh`) |69+| bisheng / asc_opc | 在 PATH 中(`source CANN set_env.sh`) |
49-| pypto_pro | Python 包可导入 |70+| pypto_pro | Python 包可导入 |
50-| cmake | ≥ 3.18(系统级,非 pip 版) |71+| PyYAML | ≥ 6.0,`.run` 的 `ALL` 构建用于读取 YAML 清单 |
72+| cmake | ≥ 3.18(系统级,非 pip 版) |
51 73 
52#### 1.3.2 构建算子74#### 1.3.2 构建算子
53 75 
54```bash76```bash
55# 构建单个算子的 .run 包77# 构建单个算子的 .run 包
56-python3 build_ci.py --pkg-type run --ops flex_attention78+python3 build_ci.py --pkg-type run --ops flex_attention --no-torch-bindings
57 79 
58-# 构建所有算子(默认)80+# 按 ops/pro/build_ops.yaml 中列出的目录构建 .run(默认 ALL)
59python3 build_ci.py --pkg-type run81python3 build_ci.py --pkg-type run
60 82 
61# 构建 whl83# 构建 whl
62python3 build_ci.py --pkg-type whl84python3 build_ci.py --pkg-type whl
63```85```
64 86 
65-> 测试用的 aclnn 桥默认不参与构建,需要 `ENABLE_TESTS=ON`(`build_ci.py` 暂未暴露该开关,手工 cmake 重配方式见 §2.3)。87+> 添加 `--stest` 会自动设置 `ENABLE_TESTS=ON`,构建测试目标并执行测试;不添加时默认不构建测试桥。手工构建测试桥见 §2.3。
88+ 
89+`.run` 构建的 `--ops ALL`(含省略 `--ops`)使用
90+[ops/pro/build_ops.yaml](../ops/pro/build_ops.yaml) 控制发布范围,使用 YAML 路径列表:
91+ 
92+```yaml
93+- deepseek_v4_1/mega_mhc
94+```
95+ 
96+路径相对于 `ops/pro`。列出的目录参与构建,未列出的目录不参与;不想构建某项时,
97+在对应行首加 `#` 即可。空行和 `#` 注释会被忽略。清单至少需要一个有效算子目录;
98+文件缺失、路径错误或全部被注释时构建报错。
99+`--stest` 使用相同名单,CMake 自动跟踪文件变化。
100+显式 `--ops mega_mhc` 绕过清单,仍按算子目录名选择;多个名称用逗号分隔。
101+`whl` 的 `ALL` 不受此文件影响。
66 102 
67#### 1.3.3. 安装 .run 包103#### 1.3.3. 安装 .run 包
68 104 
@@ -122,7 +158,8 @@ pypto-gym/
122 158 
123### 1.3.6. 算子目录契约159### 1.3.6. 算子目录契约
124 160 
125-新增算子只需满足以下结构,构建链自动发现并接入:161+新增算子需满足以下结构;加入 `.run` 的 `ALL` 发布范围时,还需将相对于 `ops/pro` 的算子目录加入 `ops/pro/build_ops.yaml`。
162+显式使用 `--ops <op_name>` 可直接选择符合构建约定的算子。
126 163 
127```bash164```bash
128ops/<paradigm>/<network>/<op_name>/165ops/<paradigm>/<network>/<op_name>/
@@ -163,12 +200,12 @@ python3 build_ci.py --pkg-type run --soc ascend950,ascend910b
163 200 
164### 1.3.8. 环境变量201### 1.3.8. 环境变量
165 202 
166-| 变量 | 用途 | 默认值 |203+| 变量 | 用途 | 默认值 |
167-| --- | --- | --- |204+| ---------------------- | ------------------------------------- | -------------------------- |
168-| `ASCEND_HOME_PATH` | CANN 包路径 | `/usr/local/Ascend/cann` |205+| `ASCEND_HOME_PATH` | CANN 包路径 | `/usr/local/Ascend/cann` |
169-| `Python3_EXECUTABLE` | Python 解释器 | 系统 python3 |206+| `Python3_EXECUTABLE` | Python 解释器 | 系统 python3 |
170-| `CANN_3RD_LIB_PATH` | 三方库缓存路径 | `<repo>/third_party/` |207+| `CANN_3RD_LIB_PATH` | 三方库缓存路径 | `<repo>/third_party/` |
171-| `GYM_SOC` | pytest aclnn 模式默认桥目录使用的 soc | `ascend950` |208+| `GYM_SOC` | pytest aclnn 模式默认桥目录使用的 soc | `ascend950` |
172 209 
173### 1.3.9 FAQ210### 1.3.9 FAQ
174 211 
@@ -187,10 +224,10 @@ A: JIT 模式依赖 `torch + torch_npu`,需先 source CANN 环境并安装 tor
187 224 
188算子测试支持同一组用例、同一组 golden 在两种模式下执行,通过 `pytest --mode` 切换:225算子测试支持同一组用例、同一组 golden 在两种模式下执行,通过 `pytest --mode` 切换:
189 226 
190-| 模式 | 调用链 | 依赖 | 适用 |227+| 模式 | 调用链 | 依赖 | 适用 |
191-| --- | --- | --- | --- |228+| --------------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------- | --------------------------------- |
192-| `jit`(默认) | `op_caller.get_op_caller("<op>")` → import `op_kernel/<op>.py` 宿主入口 → 首次调用 JIT 编译 kernel | 源码树 + CANN + pypto_pro | 开发调试、改 kernel 后快速验证 |229+| `jit`(默认) | `op_caller.get_op_caller("<op>")` → import `op_kernel/<op>.py` 宿主入口 → 首次调用 JIT 编译 kernel | 源码树 + CANN + pypto_pro | 开发调试、改 kernel 后快速验证 |
193-| `aclnn` | `op_caller.get_op_caller("<op>")` → import `aclnn_bridge_<op>.so` → `dlopen` `libcust_opapi.so` → 调 C++ aclnn 接口 | 预编译桥 + 已安装的 run 包 | 验证 run 包安装后的二进制复用链路 |230+| `aclnn` | `op_caller.get_op_caller("<op>")` → import `aclnn_bridge_<op>.so` → `dlopen` `libcust_opapi.so` → 调 C++ aclnn 接口 | 预编译桥 + 已安装的 run 包 | 验证 run 包安装后的二进制复用链路 |
194 231 
195两种模式共用:232两种模式共用:
196 233 
@@ -216,7 +253,7 @@ pytest ops/pro/experimental/flex_attention/tests --mode jit -q
216 253 
217### 2.3. 构建 aclnn 测试桥254### 2.3. 构建 aclnn 测试桥
218 255 
219-测试桥只在 `ENABLE_TESTS=ON` 时构建(`build_ci.py` 暂未暴露该开关,使用手工 cmake 重配):256+测试桥只在 `ENABLE_TESTS=ON` 时构建。使用 `build_ci.py --pkg-type run --ops flex_attention --no-torch-bindings --stest` 会自动开启该选项并完成构建、安装和测试;也可以手工配置后只构建测试桥:
220 257 
221```bash258```bash
222cmake -S . -B build/ascend950 \259cmake -S . -B build/ascend950 \
@@ -225,6 +262,7 @@ cmake -S . -B build/ascend950 \
225 -DPACKAGE_TYPE=run \262 -DPACKAGE_TYPE=run \
226 -DASCEND_OP_NAME=flex_attention \263 -DASCEND_OP_NAME=flex_attention \
227 -DCMAKE_INSTALL_PREFIX=$PWD/build_out/run/ascend950 \264 -DCMAKE_INSTALL_PREFIX=$PWD/build_out/run/ascend950 \
265+ -DENABLE_TORCH_BINDINGS=OFF \
228 -DENABLE_TESTS=ON266 -DENABLE_TESTS=ON
229 267 
230cmake --build build/ascend950 --target aclnn_bridge_flex_attention -j 32268cmake --build build/ascend950 --target aclnn_bridge_flex_attention -j 32
@@ -234,7 +272,7 @@ cmake --build build/ascend950 --target aclnn_bridge_flex_attention -j 32
234 272 
235说明:273说明:
236 274 
237-- `ENABLE_TESTS=ON` 时 `cmake/config.cmake` 才会查找 torch;`OFF` 时 run/kernel 构建不依赖 torch。275+- `ENABLE_TESTS=ON` 或 `ENABLE_TORCH_BINDINGS=ON` 时需要 torch;两者均关闭时 run/kernel 构建不依赖 torch。
238- 桥的源文件/target/产物/模块名统一为 `aclnn_bridge_<op>`,由 `gym_add_aclnn_bridge(<op>)` 生成。276- 桥的源文件/target/产物/模块名统一为 `aclnn_bridge_<op>`,由 `gym_add_aclnn_bridge(<op>)` 生成。
239- 新增算子时,在算子 `tests/aclnn_bridge/CMakeLists.txt` 调用 `gym_add_aclnn_bridge(<op>)` 并放置 `aclnn_bridge_<op>.cpp` 即可;算子 `tests/CMakeLists.txt` 会自动派发。277- 新增算子时,在算子 `tests/aclnn_bridge/CMakeLists.txt` 调用 `gym_add_aclnn_bridge(<op>)` 并放置 `aclnn_bridge_<op>.cpp` 即可;算子 `tests/CMakeLists.txt` 会自动派发。
240 278 
@@ -289,20 +327,24 @@ ops/<...>/<op>/tests/
289python3 build_ci.py --pkg-type whl --stest327python3 build_ci.py --pkg-type whl --stest
290 328 
291# aclnn:构建 run → 隔离安装到 build_out/run/<soc> → pytest --mode aclnn329# aclnn:构建 run → 隔离安装到 build_out/run/<soc> → pytest --mode aclnn
292-python3 build_ci.py --pkg-type run --ops flex_attention --soc ascend950 --stest330+python3 build_ci.py --pkg-type run --ops flex_attention --soc ascend950 --no-torch-bindings --stest
331+ 
332+# torch:按 YAML 清单构建一个 .run 包,验证其中已接入的正式 Torch 绑定
333+python3 build_ci.py --pkg-type run --ops ALL --soc ascend950 --stest
293 334 
294# 用例过滤:--stest 的值作为 pytest -k 表达式(逗号分隔按 or 处理)335# 用例过滤:--stest 的值作为 pytest -k 表达式(逗号分隔按 or 处理)
295python3 build_ci.py --pkg-type whl --stest=test_fa_mask_info336python3 build_ci.py --pkg-type whl --stest=test_fa_mask_info
296python3 build_ci.py --pkg-type run --ops flex_attention \337python3 build_ci.py --pkg-type run --ops flex_attention \
297- --stest=test_fa_mask_info,test_fa_mask_info_bshd_layout338+ --no-torch-bindings --stest=test_fa_mask_info,test_fa_mask_info_bshd_layout
298```339```
299 340 
300行为说明:341行为说明:
301 342 
302- jit 模式测试依赖**安装后的 whl**:`pip install --target build_out/whl/<soc>/site-packages`,并通过 `ops_registry.json` 让 `op_caller` 从安装包内 `pypto_gym.ops...op_kernel.<op>` 导入;343- jit 模式测试依赖**安装后的 whl**:`pip install --target build_out/whl/<soc>/site-packages`,并通过 `ops_registry.json` 让 `op_caller` 从安装包内 `pypto_gym.ops...op_kernel.<op>` 导入;
303-- run 模式测试安装到 `build_out/run/<soc>`(`--install-path`),只向 pytest 子进程注入 `ASCEND_CUSTOM_OPP_PATH` / `LD_LIBRARY_PATH`,不修改父进程环境、不 source set_env;344+- run 模式测试安装到 `build_out/run/<soc>`(`--install-path`),向 pytest 子进程注入 `ASCEND_CUSTOM_OPP_PATH` / `LD_LIBRARY_PATH`;启用正式 Torch 绑定时还注入 vendor 的 `PYTHONPATH`,不修改父进程环境;
345+- `.run` 的 `ALL` 构建和测试均按 `ops/pro/build_ops.yaml` 选择算子;显式 `--ops` 绕过清单。默认启用 Torch 绑定,已提供绑定的算子使用 torch 模式,其余使用 aclnn 模式;传入 `--no-torch-bindings` 可关闭绑定;
304- 测试结束不清理 `site-packages` / `vendors`;下次 stest 前会先 `--uninstall` 再安装,`-c` 可整体清理;346- 测试结束不清理 `site-packages` / `vendors`;下次 stest 前会先 `--uninstall` 再安装,`-c` 可整体清理;
305-- run/aclnn 自动追加 `-m "not jit_only"`,排除 matrix/perf/prefill 等 JIT-only 用例;347+- run 的 aclnn、torch 模式自动追加 `-m "not jit_only"`,排除 matrix/perf/prefill 等 JIT-only 用例;
306- `--stest` 只允许单个 soc,多 soc 直接报错;`--utest` 暂未提供。348- `--stest` 只允许单个 soc,多 soc 直接报错;`--utest` 暂未提供。
307 349 
308产物布局:350产物布局:
@@ -0,0 +1,12 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+# .run ALL build manifest; paths are relative to ops/pro.
10+# Comment out an entry to exclude it, e.g. # - deepseek_v4_1/mega_mhc
11+# Explicit --ops op_a,op_b still selects operator directory names.
12+- deepseek_v4_1/mega_mhc
@@ -0,0 +1,21 @@
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+# 算子级 dispatcher: 派发算子子目录(op_host 必选, tests 等按需).
11+# 算子接入契约: gym_op_discovery 锚定本文件, 缺失即 FATAL.
12+ 
13+file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
14+if(NOT ENABLE_TESTS)
15+ list(REMOVE_ITEM CURRENT_DIRS tests)
16+endif()
17+foreach(SUB_DIR ${CURRENT_DIRS})
18+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
19+ add_subdirectory(${SUB_DIR})
20+ endif()
21+endforeach()
@@ -0,0 +1,214 @@
1+# MegaMhc(mega_mhc)
2+ 
3+MegaMhc 是面向 Ascend 950 的融合算子,在一次调用中完成四路残差混合、
4+下一轮混合系数更新和当前层 RMSNorm 输出。支持通过
5+`aclnnMegaMhcGetWorkspaceSize` 和 `aclnnMegaMhc` 调用预编译二进制,
6+运行时无需 JIT。
7+ 
8+## 计算与接口
9+ 
10+融合残差混合、下一轮系数更新和 RMSNorm。混合后的残差和旧 pre 系数加权的
11+中间向量各进行一次 BF16 舍入;当前层输出使用旧 pre 系数。FN 输入保持 FP32
12+且只读,保留原生范围检测和 Vector 回退路径。每次非空调用启动一个 MIX kernel。
13+ 
14+| 输入(顺序固定) | 形状 | dtype |
15+| ---------------- | ----------- | ----- |
16+| x | `[T,H]` | BF16 |
17+| residual | `[T,4,H]` | BF16 |
18+| previous_mix | `[T,4]` | FP32 |
19+| post_mix | `[T,4,1]` | FP32 |
20+| comb_res_mix | `[T,4,4]` | FP32 |
21+| fn | `[24,4H]` | FP32 |
22+| mix_scales | `[3]` | FP32 |
23+| mix_bases | `[24]` | FP32 |
24+| rmsnorm_weight | `[H]` | BF16 |
25+ 
26+五个输出依次为 `new_residual [T,4,H] BF16`、`new_post_mix [T,4,1] FP32`、
27+`new_comb_res_mix [T,4,4] FP32`、`y [T,H] BF16`、`new_previous_mix [T,4] FP32`。
28+所有张量均为同设备、连续 ND;输入可以只读共享,输出和 workspace 必须互不重叠,
29+并与输入分离。Torch 绑定在进入异步队列前检查所有输入和输出的真实存储格式,
30+拒绝 NZ 等非 ND 存储,不做隐式格式转换;`is_contiguous()` 为真也不代表格式是 ND。
31+`T >= 0`,`H ∈ {1024,2048,3072,4096,5120,6144,7168}`。
32+每个 H shard 使用一个常驻 AIC 组,设备可用 AIC 数须至少为 `H/256`。
33+ 
34+| ACLNN 属性(位于输入和输出之间) | 默认值 | 约束 |
35+| -------------------------------- | ------ | --------------------------- |
36+| hc_norm_eps | 2e-5 | 有限、正 |
37+| hc_pre_eps | 3e-4 | 有限、非负 |
38+| hc_post_scale | 1.25 | 有限、非负 |
39+| sinkhorn_eps | 2e-6 | 有限、非负 |
40+| num_sinkhorn_iters | 10 | 整数 1..65535 |
41+| rmsnorm_eps | 7e-6 | 有限、正 |
42+| batch | 0 | 0 自动选择;16 强制 batch16 |
43+ 
44+ACLNN 浮点属性以 `double` 传入,host tiling 按 FP32 使用。
45+自动选择在 `H=7168,T>=4096` 时使用内部 batch8/J27,其他形状使用 batch16
46+(H7168/J7,其余 H/J8)。公共 batch8 override 不支持。
47+ 
48+## 数学计算流
49+ 
50+以下计算对每个 token 独立进行。记输入残差为
51+$R\in\mathbb{R}^{4\times H}$,残差混合矩阵为 $C$,
52+旧 pre 系数为 $a$,post 系数为 $p$,RMSNorm 权重为 $\gamma$。
53+`BF16` 表示舍入到 BF16;后续计算读取其舍入后的数值并转为 FP32。
54+ 
55+```mermaid
56+flowchart TD
57+ RX["residual R、x、comb_res_mix C、post_mix p"]
58+ MIX["残差混合<br/>R_new = BF16(CᵀR + p · x)"]
59+ R_OUT["输出 1:new_residual<br/>[T,4,H] BF16"]
60+ OLD_PRE["previous_mix a<br/>当前层使用的旧 pre 系数"]
61+ U["四路加权求和<br/>u = BF16(Σ a_i · R_new_i)"]
62+ NORM["RMSNorm<br/>y = BF16(u · rsqrt(mean(u²) + rmsnorm_eps) · γ)"]
63+ GAMMA["rmsnorm_weight γ"]
64+ Y_OUT["输出 4:y<br/>[T,H] BF16"]
65+ PROJ["展平、FN 投影与 RMS 归一化<br/>z = flatten(R_new)<br/>v = (fn · z) · rsqrt(mean(z²) + hc_norm_eps)"]
66+ FN["fn:24 × 4H,FP32"]
67+ AFFINE["分组缩放与偏置<br/>l = v · broadcast(mix_scales) + mix_bases"]
68+ SB["mix_scales、mix_bases"]
69+ PRE["前 4 项<br/>sigmoid(l_pre) + hc_pre_eps"]
70+ POST["中间 4 项<br/>sigmoid(l_post) · hc_post_scale"]
71+ SOFTMAX["后 16 项重排为 4 × 4<br/>S = softmax_row(l_comb) + sinkhorn_eps"]
72+ COL["首次列归一化<br/>S = S / (列和 + sinkhorn_eps)"]
73+ ITER["再执行 num_sinkhorn_iters − 1 次<br/>行归一化 → 列归一化<br/>每次分母均加 sinkhorn_eps"]
74+ P_OUT["输出 2:new_post_mix<br/>[T,4,1] FP32"]
75+ C_OUT["输出 3:new_comb_res_mix<br/>[T,4,4] FP32"]
76+ A_OUT["输出 5:new_previous_mix<br/>[T,4] FP32,供下一轮使用"]
77+ 
78+ RX --> MIX
79+ MIX --> R_OUT
80+ MIX --> U
81+ OLD_PRE --> U
82+ U --> NORM
83+ GAMMA --> NORM
84+ NORM --> Y_OUT
85+ MIX --> PROJ
86+ FN --> PROJ
87+ PROJ --> AFFINE
88+ SB --> AFFINE
89+ AFFINE --> PRE
90+ AFFINE --> POST
91+ AFFINE --> SOFTMAX
92+ PRE --> A_OUT
93+ POST --> P_OUT
94+ SOFTMAX --> COL
95+ COL --> ITER
96+ ITER --> C_OUT
97+```
98+ 
99+残差混合的索引定义为:
100+ 
101+$$
102+R'_{t,j,h}=\operatorname{BF16}\!\left(
103+\sum_{i=0}^{3}C_{t,i,j}R_{t,i,h}+p_{t,j}x_{t,h}\right),
104+\qquad
105+u_{t,h}=\operatorname{BF16}\!\left(\sum_{j=0}^{3}a_{t,j}R'_{t,j,h}\right).
106+$$
107+ 
108+投影得到的 24 项按 `pre[0:4]`、`post[4:8]`、`comb[8:24]` 分组,
109+三组分别使用 `mix_scales[0]`、`mix_scales[1]`、`mix_scales[2]`。
110+图中的行归一化沿矩阵最后一维求和,列归一化沿倒数第二维求和。
111+两个分支均读取已经舍入到 BF16 的 `R_new`;当前层 `y` 始终使用输入的
112+`previous_mix`,更新后的 `new_previous_mix` 供下一轮调用使用。
113+ 
114+## 二进制构建与调用
115+ 
116+在仓库根目录、已配置 CANN 和 PyPTO-pro 的环境执行:
117+ 
118+```bash
119+python3 build_ci.py --pkg-type run --ops mega_mhc --soc ascend950
120+bash build_out/run/ascend950/cann-950-pypto_gym_*.run \
121+ --install-path="$PWD/build_out/run/ascend950"
122+source build_out/run/ascend950/vendors/pypto_gym/bin/set_env.bash
123+```
124+ 
125+安装后 C++ 使用 `op_api/include/aclnnop/aclnn_mega_mhc.h`:
126+ 
127+```cpp
128+uint64_t workspaceSize = 0;
129+aclOpExecutor *executor = nullptr;
130+auto ret = aclnnMegaMhcGetWorkspaceSize(
131+ x, residual, previousMix, postMix, combResMix, fn, mixScales, mixBases,
132+ rmsnormWeight, 2e-5, 3e-4, 1.25, 2e-6, 10, 7e-6, 0,
133+ newResidual, newPostMix, newCombResMix, y, newPreviousMix,
134+ &workspaceSize, &executor);
135+// 检查 ret;按 workspaceSize 在设备上分配 workspace。
136+ret = aclnnMegaMhc(workspace, workspaceSize, executor, stream);
137+// 检查 ret;异步完成前保持输入、输出、workspace 存活。
138+```
139+ 
140+Q、inverse RMS 和 range flags 被打包到同一 ACLNN workspace,分段按 512 字节
141+对齐,大小由 GetWorkspaceSize 返回。不同在途调用使用独立 workspace。
142+ 
143+`op_kernel/mega_mhc.py` 提供开发用 JIT wrapper,支持上述九输入、标量和
144+`batch=None/16`;输出由 wrapper 内部申请。开发用 `allocate_workspace(x, batch=...)` 返回
145+单个 UINT8 张量(交付 ABI),其容量和偏移由 `select_config` 给出。
146+T=0 时 Python wrapper 和测试桥直接返回空输出。
147+ 
148+## Torch 接口
149+ 
150+`.run` 默认同时交付正式 Torch 绑定;仅需 ACLNN 接口时可传入 `--no-torch-bindings`:
151+ 
152+```bash
153+python3 build_ci.py --pkg-type run --ops mega_mhc --soc ascend950
154+bash build_out/run/ascend950/cann-950-pypto_gym_*.run --install-path="$ASCEND_HOME_PATH/opp"
155+```
156+ 
157+当前终端已加载目标 CANN 基础环境时,安装后即可直接导入,无需额外 source vendor
158+脚本。Python 入口自动登记到 CANN 的 `python/site-packages`,ACLNN 库按绑定库的
159+相对路径加载。安装到非 CANN 的独立目录时,仍可使用其 vendor `set_env.bash`。
160+ 
161+```python
162+import torch
163+import pypto_gym
164+ 
165+result = pypto_gym.mega_mhc(*inputs) # 上表顺序的九个同设备 NPU 输入
166+# 直接使用 torch.ops 前先显式加载绑定:
167+pypto_gym.load()
168+result = torch.ops.pypto_gym.mega_mhc(*inputs, batch=0)
169+```
170+ 
171+`pypto_gym.mega_mhc` 只提供返回值形式,五个输出由绑定内部申请。
172+ 
173+`import pypto_gym` 惰性加载,不导入 torch/torch_npu;访问 `pypto_gym.mega_mhc` 或
174+调用 `pypto_gym.load()` 时才加载已安装的绑定库。
175+ 
176+Python 入口的 `batch=None` 对应 dispatcher 的 `batch=0`。六个标量参数的名称和
177+默认值与上表一致。执行路径为 Torch dispatcher → 编译好的 C++ 绑定 → ACLNN
178+→ 预编译 kernel;绑定本身也随包预编译,调用时无需 PyPTO JIT 或 C++ 编译。
179+绑定支持 Meta/FakeTensor 输出推导;当前提供 forward 计算,不提供 backward。
180+部署时需使用与构建环境兼容的 Python、torch、torch_npu 和 CANN。
181+ 
182+## 测试
183+ 
184+数值测试看护完整算子的典型 shape 和边界,共 **25 项**。每项执行一次完整算子,
185+使用固定默认标量;仅最后一项显式指定 `batch=16`。
186+用例表为每项固定选择一个入口:12 项直接调用 `pypto_gym.mega_mhc`,
187+另 13 项直接调用 `torch.ops.pypto_gym.mega_mhc`,总计仍为 25 项。
188+输出由绑定内部申请,测试不预分配输出。
189+ 
190+另有 **1 项格式边界用例**,通过 `torch.ops.pypto_gym.mega_mhc` 传入 NZ 输入,
191+验证逻辑连续但物理存储不为 ND 时会在调用线程直接报错。
192+ 
193+| 分类 | 数量 | T、H 与覆盖目的 |
194+| ---------------- | ---- | ----------------------------------------------------------------------------------- |
195+| 典型 shape | 8 | `(128,1024/2048/3072/5120/6144)`、`(96,5120)`、`(200,4096)`、`(1025,7168)`;覆盖全部七种 H |
196+| 空输入、单 token | 2 | `(0,1024)`、`(1,7168)` |
197+| 小批次尾部 | 3 | `H=4096,T=31/32/33`;不足、恰好和超过一个 32-token 作业 |
198+| 分块边界 | 6 | `H=4096,T=255/256/257`;`H=7168,T=223/224/225`,覆盖两种 batch16 分块容量的边界 |
199+| 自动配置切换 | 3 | `H=7168,T=4095/4096/4097`;切换前、切换点和切换后的尾部 |
200+| 数值边界 | 2 | `(1,1024)` 的零输入、`(5,3072)` 的近零输入;检查 RMS 退化场景 |
201+| 强制 batch16 | 1 | `(4096,7168,batch=16)`;覆盖大 shape 的显式配置 |
202+ 
203+25 项数值用例都比较五个输出与独立 CPU golden,保留两次 BF16 舍入和原有精度容差。
204+同时检查只读输入不变,以及输入两端的 guard。测试中不做预热、重复调用、
205+状态串联、参数组合扩展或 Torch 框架专项检查。
206+ 
207+将带 Torch 绑定的 `.run` 安装到已加载基础环境的 CANN 后执行:
208+ 
209+```bash
210+pytest ops/pro/deepseek_v4_1/mega_mhc/tests -q
211+```
212+ 
213+测试文件直接导入安装包 `pypto_gym` 并调用上述接口,调用入口由用例表固定指定,
214+不受仓级 `--mode` 参数控制。运行时需要已安装的 Torch 二进制绑定。
@@ -0,0 +1 @@
1+"""Fused mega-mHC operator (Ascend 950 binary delivery)."""
@@ -0,0 +1,9 @@
1+require_pypto_pro(mega_mhc)
2+add_op_to_compiled_list()
3+target_sources(op_host_aclnn PRIVATE mega_mhc_def.cpp)
4+enable_pypto_kernel(mega_mhc)
5+add_modules_sources(OPTYPE mega_mhc ACLNNTYPE aclnn)
6+add_ops_compile_options(OP_NAME MegaMhc OPTIONS --cce-auto-sync=off -Wno-deprecated-declarations)
7+if(NOT BUILD_OPS_RTY_KERNEL)
8+ add_tiling_modules()
9+endif()
@@ -0,0 +1,50 @@
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+#include "register/op_def_registry.h"
12+ 
13+namespace ops {
14+class MegaMhc : public OpDef {
15+public:
16+ explicit MegaMhc(const char *name) : OpDef(name)
17+ {
18+ this->Input("x").ParamType(REQUIRED).DataType({ge::DT_BF16}).Format({ge::FORMAT_ND}).AutoContiguous();
19+ this->Input("residual").ParamType(REQUIRED).DataType({ge::DT_BF16}).Format({ge::FORMAT_ND}).AutoContiguous();
20+ this->Input("previous_mix").ParamType(REQUIRED).DataType({ge::DT_FLOAT}).Format({ge::FORMAT_ND}).AutoContiguous();
21+ this->Input("post_mix").ParamType(REQUIRED).DataType({ge::DT_FLOAT}).Format({ge::FORMAT_ND}).AutoContiguous();
22+ this->Input("comb_res_mix").ParamType(REQUIRED).DataType({ge::DT_FLOAT}).Format({ge::FORMAT_ND}).AutoContiguous();
23+ this->Input("fn").ParamType(REQUIRED).DataType({ge::DT_FLOAT}).Format({ge::FORMAT_ND}).AutoContiguous();
24+ this->Input("mix_scales").ParamType(REQUIRED).DataType({ge::DT_FLOAT}).Format({ge::FORMAT_ND}).AutoContiguous();
25+ this->Input("mix_bases").ParamType(REQUIRED).DataType({ge::DT_FLOAT}).Format({ge::FORMAT_ND}).AutoContiguous();
26+ this->Input("rmsnorm_weight").ParamType(REQUIRED).DataType({ge::DT_BF16}).Format({ge::FORMAT_ND}).AutoContiguous();
27+ this->Output("new_residual").ParamType(REQUIRED).DataType({ge::DT_BF16}).Format({ge::FORMAT_ND});
28+ this->Output("new_post_mix").ParamType(REQUIRED).DataType({ge::DT_FLOAT}).Format({ge::FORMAT_ND});
29+ this->Output("new_comb_res_mix").ParamType(REQUIRED).DataType({ge::DT_FLOAT}).Format({ge::FORMAT_ND});
30+ this->Output("y").ParamType(REQUIRED).DataType({ge::DT_BF16}).Format({ge::FORMAT_ND});
31+ this->Output("new_previous_mix").ParamType(REQUIRED).DataType({ge::DT_FLOAT}).Format({ge::FORMAT_ND});
32+ this->Attr("hc_norm_eps").AttrType(OPTIONAL).Float(2e-5);
33+ this->Attr("hc_pre_eps").AttrType(OPTIONAL).Float(3e-4);
34+ this->Attr("hc_post_scale").AttrType(OPTIONAL).Float(1.25);
35+ this->Attr("sinkhorn_eps").AttrType(OPTIONAL).Float(2e-6);
36+ this->Attr("num_sinkhorn_iters").AttrType(OPTIONAL).Int(10);
37+ this->Attr("rmsnorm_eps").AttrType(OPTIONAL).Float(7e-6);
38+ // 0: automatic; 16: force batch16. Public batch8 remains unsupported.
39+ this->Attr("batch").AttrType(OPTIONAL).Int(0);
40+ OpAICoreConfig config;
41+ config.DynamicCompileStaticFlag(true).DynamicFormatFlag(true)
42+ .DynamicRankSupportFlag(true).DynamicShapeSupportFlag(true)
43+ .NeedCheckSupportFlag(false).PrecisionReduceFlag(false)
44+ .ExtendCfgInfo("opFile.value", "mega_mhc")
45+ .ExtendCfgInfo("aclnnSupport.value", "support_aclnn");
46+ this->AICore().AddConfig("ascend950", config);
47+ }
48+};
49+OP_ADD(MegaMhc);
50+} // namespace ops
@@ -0,0 +1,33 @@
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+#include "register/op_impl_registry.h"
12+namespace ops {
13+static ge::graphStatus InferShape(gert::InferShapeContext *context)
14+{
15+ const auto *x = context->GetInputShape(0);
16+ if (x == nullptr || x->GetDimNum() != 2) return ge::GRAPH_FAILED;
17+ const int64_t t = x->GetDim(0), h = x->GetDim(1);
18+ const gert::Shape shapes[] = {{t, 4, h}, {t, 4, 1}, {t, 4, 4}, {t, h}, {t, 4}};
19+ for (size_t i = 0; i < 5; ++i) {
20+ auto *out = context->GetOutputShape(i);
21+ if (out == nullptr) return ge::GRAPH_FAILED;
22+ *out = shapes[i];
23+ }
24+ return ge::GRAPH_SUCCESS;
25+}
26+static ge::graphStatus InferDataType(gert::InferDataTypeContext *context)
27+{
28+ const ge::DataType types[] = {ge::DT_BF16, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_BF16, ge::DT_FLOAT};
29+ for (size_t i = 0; i < 5; ++i) context->SetOutputDataType(i, types[i]);
30+ return ge::GRAPH_SUCCESS;
31+}
32+IMPL_OP_INFERSHAPE(MegaMhc).InferShape(InferShape).InferDataType(InferDataType);
33+} // namespace ops
@@ -0,0 +1,126 @@
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+#include "mega_mhc_tiling.h"
12+#include "register/op_def_registry.h"
13+#include "tiling/platform/platform_ascendc.h"
14+#include <algorithm>
15+#include <cmath>
16+#include <initializer_list>
17+#include <limits>
18+ 
19+namespace optiling {
20+static bool ShapeIs(const gert::StorageShape *shape, std::initializer_list<int64_t> dims)
21+{
22+ if (shape == nullptr || shape->GetStorageShape().GetDimNum() != dims.size()) return false;
23+ size_t i = 0;
24+ for (auto dim : dims) if (shape->GetStorageShape().GetDim(i++) != dim) return false;
25+ return true;
26+}
27+static size_t Align(size_t bytes) { return (bytes + 511) / 512 * 512; }
28+struct MegaMhcAttrs {
29+ const float *hc = nullptr;
30+ const float *pre = nullptr;
31+ const float *post = nullptr;
32+ const float *sink = nullptr;
33+ const float *norm = nullptr;
34+ const int64_t *repeat = nullptr;
35+ const int64_t *batch = nullptr;
36+};
37+ 
38+static bool ReadAttrs(gert::TilingContext *ctx, MegaMhcAttrs &attr)
39+{
40+ const auto *attrs = ctx->GetAttrs();
41+ if (attrs == nullptr) return false;
42+ attr.hc = attrs->GetFloat(0);
43+ attr.pre = attrs->GetFloat(1);
44+ attr.post = attrs->GetFloat(2);
45+ attr.sink = attrs->GetFloat(3);
46+ attr.norm = attrs->GetFloat(5);
47+ attr.repeat = attrs->GetInt(4);
48+ attr.batch = attrs->GetInt(6);
49+ if (!attr.hc || !attr.pre || !attr.post || !attr.sink || !attr.norm ||
50+ !attr.repeat || !attr.batch) return false;
51+ for (float value : {*attr.hc, *attr.pre, *attr.post, *attr.sink, *attr.norm})
52+ if (!std::isfinite(value) || value < 0) return false;
53+ if (*attr.hc <= 0 || *attr.norm <= 0 || *attr.repeat < 1 || *attr.repeat > 65535 ||
54+ (*attr.batch != 0 && *attr.batch != 16)) return false;
55+ return true;
56+}
57+ 
58+static ge::graphStatus CheckInputs(gert::TilingContext *ctx, int64_t t, int64_t h)
59+{
60+ const std::initializer_list<int64_t> shapes[] = {
61+ {t,h}, {t,4,h}, {t,4}, {t,4,1}, {t,4,4}, {24,4*h}, {3}, {24}, {h}};
62+ const ge::DataType types[] = {ge::DT_BF16,ge::DT_BF16,ge::DT_FLOAT,ge::DT_FLOAT,
63+ ge::DT_FLOAT,ge::DT_FLOAT,ge::DT_FLOAT,ge::DT_FLOAT,ge::DT_BF16};
64+ for (size_t i = 0; i < 9; ++i) {
65+ const auto *desc = ctx->GetInputDesc(i);
66+ if (!ShapeIs(ctx->GetInputShape(i), shapes[i]) || desc == nullptr ||
67+ desc->GetDataType() != types[i] || desc->GetStorageFormat() != ge::FORMAT_ND)
68+ return ge::GRAPH_FAILED;
69+ }
70+ return ge::GRAPH_SUCCESS;
71+}
72+ 
73+static ge::graphStatus CheckOutputs(gert::TilingContext *ctx, int64_t t, int64_t h)
74+{
75+ const std::initializer_list<int64_t> shapes[] = {{t,4,h},{t,4,1},{t,4,4},{t,h},{t,4}};
76+ const ge::DataType types[] = {ge::DT_BF16,ge::DT_FLOAT,ge::DT_FLOAT,ge::DT_BF16,ge::DT_FLOAT};
77+ for (size_t i = 0; i < 5; ++i) {
78+ const auto *desc = ctx->GetOutputDesc(i);
79+ if (!ShapeIs(ctx->GetOutputShape(i), shapes[i]) || desc == nullptr ||
80+ desc->GetDataType() != types[i]) return ge::GRAPH_FAILED;
81+ }
82+ return ge::GRAPH_SUCCESS;
83+}
84+ 
85+static ge::graphStatus BuildTiling(gert::TilingContext *ctx, int64_t t, int64_t h,
86+ const MegaMhcAttrs &attr)
87+{
88+ const bool b8 = *attr.batch == 0 && h == 7168 && t >= 4096;
89+ const int64_t jobs = b8 ? 27 : (h == 7168 ? 7 : 8);
90+ const int64_t rows = std::min(t, 2 * (b8 ? 8 : 16) * jobs);
91+ const int64_t shards = h / 256;
92+ // Cross-core barriers require exactly one resident AIC group per width shard.
93+ auto platform = platform_ascendc::PlatformAscendC(ctx->GetPlatformInfo());
94+ if (platform.GetCoreNumAic() < shards) return ge::GRAPH_FAILED;
95+ const size_t invOffset = Align(rows * shards * 32 * sizeof(float));
96+ const size_t flagsOffset = invOffset + Align(rows * 16 * sizeof(float));
97+ size_t *workspace = ctx->GetWorkspaceSizes(1);
98+ workspace[0] = std::max<size_t>(1024, flagsOffset + Align((shards + 1) * 16 * sizeof(int32_t)));
99+ MegaMhcTilingData data;
100+ data.set_tokens(t); data.set_rows(rows);
101+ data.set_inv_offset(invOffset); data.set_flags_offset(flagsOffset);
102+ data.set_repeat(*attr.repeat); data.set_hc_eps(*attr.hc); data.set_pre_eps(*attr.pre);
103+ data.set_post_scale(*attr.post); data.set_sink_eps(*attr.sink); data.set_norm_eps(*attr.norm);
104+ // Key packs candidate INDEX, not literal value: Width[0:2], BlockJobs[3:4].
105+ ctx->SetTilingKey((h / 1024 - 1) | ((b8 ? 2 : (h == 7168 ? 0 : 1)) << 3));
106+ ctx->SetBlockDim(static_cast<uint32_t>(shards));
107+ data.SaveToBuffer(ctx->GetRawTilingData()->GetData(), ctx->GetRawTilingData()->GetCapacity());
108+ ctx->GetRawTilingData()->SetDataSize(data.GetDataSize());
109+ return ge::GRAPH_SUCCESS;
110+}
111+ 
112+static ge::graphStatus Tiling(gert::TilingContext *ctx)
113+{
114+ const auto *x = ctx->GetInputShape(0);
115+ if (x == nullptr || x->GetStorageShape().GetDimNum() != 2) return ge::GRAPH_FAILED;
116+ const int64_t t = x->GetStorageShape().GetDim(0), h = x->GetStorageShape().GetDim(1);
117+ if (t < 0 || h < 1024 || h > 7168 || h % 1024 != 0 ||
118+ t > std::numeric_limits<int64_t>::max() / (4 * h)) return ge::GRAPH_FAILED;
119+ if (CheckInputs(ctx, t, h) != ge::GRAPH_SUCCESS ||
120+ CheckOutputs(ctx, t, h) != ge::GRAPH_SUCCESS) return ge::GRAPH_FAILED;
121+ MegaMhcAttrs attr;
122+ if (!ReadAttrs(ctx, attr)) return ge::GRAPH_FAILED;
123+ return BuildTiling(ctx, t, h, attr);
124+}
125+IMPL_OP_OPTILING(MegaMhc).Tiling(Tiling);
126+} // namespace optiling
@@ -0,0 +1,30 @@
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+#ifndef MEGA_MHC_TILING_H_
12+#define MEGA_MHC_TILING_H_
13+#include "register/tilingdata_base.h"
14+#include "tiling/tiling_api.h"
15+namespace optiling {
16+BEGIN_TILING_DATA_DEF(MegaMhcTilingData)
17+TILING_DATA_FIELD_DEF(int64_t, tokens)
18+TILING_DATA_FIELD_DEF(int64_t, rows)
19+TILING_DATA_FIELD_DEF(int64_t, inv_offset)
20+TILING_DATA_FIELD_DEF(int64_t, flags_offset)
21+TILING_DATA_FIELD_DEF(int64_t, repeat)
22+TILING_DATA_FIELD_DEF(float, hc_eps)
23+TILING_DATA_FIELD_DEF(float, pre_eps)
24+TILING_DATA_FIELD_DEF(float, post_scale)
25+TILING_DATA_FIELD_DEF(float, sink_eps)
26+TILING_DATA_FIELD_DEF(float, norm_eps)
27+END_TILING_DATA_DEF
28+REGISTER_TILING_DATA_CLASS(MegaMhc, MegaMhcTilingData)
29+} // namespace optiling
30+#endif
@@ -0,0 +1,11 @@
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+"""Kernel entry modules for the enclosing operator."""
@@ -0,0 +1,17 @@
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+# 算子 tests 构建入口(由算子级 dispatcher 在 ENABLE_TESTS 时派发进入).
11+# 目录约定:
12+# aclnn_bridge/ aclnn 模式的 pybind11 桥(C++ 目标, 按需构建)
13+# assets/ golden/参考实现与共享常量(Python, 不参与 CMake)
14+# test_*.py 用例, 位于本目录(pytest 直接收集, 不参与 CMake)
15+# 后续如需新增测试侧 C++ 目标, 在此 add_subdirectory.
16+ 
17+add_subdirectory(aclnn_bridge)
@@ -0,0 +1,3 @@
1+find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
2+gym_add_aclnn_bridge(mega_mhc)
3+target_include_directories(aclnn_bridge_mega_mhc PRIVATE ${Python3_INCLUDE_DIRS})
@@ -0,0 +1,115 @@
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+#include "aclnn_bridge_common.h"
12+#include <array>
13+#include <cmath>
14+#include <limits>
15+ 
16+namespace {
17+using namespace gym_test_bridge;
18+using GetWorkspace = aclnnStatus (*)(
19+ const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *,
20+ double, double, double, double, int64_t, double, int64_t,
21+ const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *, uint64_t *, aclOpExecutor **);
22+using Execute = aclnnStatus (*)(void *, uint64_t, aclOpExecutor *, aclrtStream);
23+std::vector<torch::Tensor> MegaMhc(
24+ torch::Tensor x,
25+ torch::Tensor residual,
26+ torch::Tensor previous_mix,
27+ torch::Tensor post_mix,
28+ torch::Tensor comb_res_mix,
29+ torch::Tensor fn,
30+ torch::Tensor mix_scales,
31+ torch::Tensor mix_bases,
32+ torch::Tensor rmsnorm_weight,
33+ double hc, double pre, double post, double sink, int64_t repeat, double norm,
34+ c10::optional<int64_t> batch, c10::optional<std::vector<torch::Tensor>> out)
35+{
36+ TORCH_CHECK(x.dim() == 2 && x.scalar_type() == at::kBFloat16 && x.device().is_privateuseone(),
37+ "x must be a rank-2 BF16 NPU tensor");
38+ const int64_t t = x.size(0), h = x.size(1);
39+ TORCH_CHECK(h >= 1024 && h <= 7168 && h % 1024 == 0, "unsupported H");
40+ TORCH_CHECK(!batch.has_value() || *batch == 16, "public batch must be None or 16");
41+ for (double v : {hc, pre, post, sink, norm})
42+ TORCH_CHECK(std::isfinite(v) && v >= 0 && v <= std::numeric_limits<float>::max(), "invalid scalar");
43+ TORCH_CHECK(hc > 0 && norm > 0 && repeat >= 1 && repeat <= 65535, "invalid RMS epsilon/iterations");
44+ std::vector<torch::Tensor> inputs = {x, residual, previous_mix, post_mix, comb_res_mix, fn, mix_scales, mix_bases, rmsnorm_weight};
45+ const std::vector<std::vector<int64_t>> shapes = {
46+ {t,h},{t,4,h},{t,4},{t,4,1},{t,4,4},{24,4*h},{3},{24},{h}};
47+ for (size_t i = 0; i < inputs.size(); ++i) {
48+ const auto dtype = (i == 0 || i == 1 || i == 8) ? at::kBFloat16 : at::kFloat;
49+ TORCH_CHECK(inputs[i].device() == x.device() && inputs[i].is_contiguous() &&
50+ inputs[i].scalar_type() == dtype && inputs[i].sizes().vec() == shapes[i], "invalid input ", i);
51+ }
52+ const std::vector<std::vector<int64_t>> outShapes = {{t,4,h},{t,4,1},{t,4,4},{t,h},{t,4}};
53+ std::vector<torch::Tensor> outputs;
54+ if (out.has_value()) outputs = *out;
55+ else for (size_t i = 0; i < 5; ++i)
56+ outputs.push_back(at::empty(outShapes[i], x.options().dtype((i == 0 || i == 3) ? at::kBFloat16 : at::kFloat)));
57+ TORCH_CHECK(outputs.size() == 5, "out must contain five tensors");
58+ std::vector<std::pair<uintptr_t, uintptr_t>> occupied;
59+ for (const auto &value : inputs) {
60+ const auto start = reinterpret_cast<uintptr_t>(value.data_ptr());
61+ occupied.emplace_back(start, start + value.numel() * value.element_size());
62+ }
63+ for (size_t i = 0; i < 5; ++i) {
64+ const auto &value = outputs[i];
65+ TORCH_CHECK(value.device() == x.device() && value.is_contiguous() && value.sizes().vec() == outShapes[i] &&
66+ value.scalar_type() == ((i == 0 || i == 3) ? at::kBFloat16 : at::kFloat), "invalid output ", i);
67+ const auto a = reinterpret_cast<uintptr_t>(value.data_ptr()), b = a + value.numel() * value.element_size();
68+ if (a != b) {
69+ for (const auto &span : occupied)
70+ TORCH_CHECK(span.first == span.second || a >= span.second || span.first >= b, "overlapping output");
71+ occupied.emplace_back(a, b);
72+ }
73+ }
74+ if (t == 0) return outputs;
75+ static auto getWorkspace = reinterpret_cast<GetWorkspace>(get_opapi_func("aclnnMegaMhcGetWorkspaceSize"));
76+ static auto execute = reinterpret_cast<Execute>(get_opapi_func("aclnnMegaMhc"));
77+ // Destroy descriptors even when GetWorkspaceSize or launch fails.
78+ struct Descriptors {
79+ std::vector<aclTensor *> tensors;
80+ ~Descriptors() { for (auto *p : tensors) destroy_acl_tensor(p); }
81+ } descriptors;
82+ for (const auto &value : inputs) descriptors.tensors.push_back(make_acl_tensor(value));
83+ for (const auto &value : outputs) descriptors.tensors.push_back(make_acl_tensor(value));
84+ auto &a = descriptors.tensors;
85+ uint64_t bytes = 0;
86+ aclOpExecutor *executor = nullptr;
87+ auto status = getWorkspace(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8],
88+ hc, pre, post, sink, repeat, norm, batch.value_or(0),
89+ a[9], a[10], a[11], a[12], a[13], &bytes, &executor);
90+ TORCH_CHECK(status == 0, "aclnnMegaMhcGetWorkspaceSize failed: ", status);
91+ auto workspace = at::empty({static_cast<int64_t>(bytes)}, x.options().dtype(at::kByte));
92+ status = execute(bytes ? workspace.data_ptr() : nullptr, bytes, executor, get_current_npu_stream());
93+ TORCH_CHECK(status == 0, "aclnnMegaMhc failed: ", status);
94+ return outputs;
95+}
96+} // namespace
97+ 
98+PYBIND11_MODULE(aclnn_bridge_mega_mhc, m)
99+{
100+ m.def("mega_mhc", &MegaMhc,
101+ pybind11::arg("x"),
102+ pybind11::arg("residual"),
103+ pybind11::arg("previous_mix"),
104+ pybind11::arg("post_mix"),
105+ pybind11::arg("comb_res_mix"),
106+ pybind11::arg("fn"),
107+ pybind11::arg("mix_scales"),
108+ pybind11::arg("mix_bases"),
109+ pybind11::arg("rmsnorm_weight"),
110+ pybind11::kw_only(),
111+ pybind11::arg("hc_norm_eps") = 2e-5, pybind11::arg("hc_pre_eps") = 3e-4,
112+ pybind11::arg("hc_post_scale") = 1.25, pybind11::arg("sinkhorn_eps") = 2e-6,
113+ pybind11::arg("num_sinkhorn_iters") = 10, pybind11::arg("rmsnorm_eps") = 7e-6,
114+ pybind11::arg("batch") = pybind11::none(), pybind11::arg("out") = pybind11::none());
115+}
@@ -0,0 +1,88 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+ 
10+"""Independent CPU equations for vLLM PR #56255's shifted BF16 path.
11+ 
12+Reference: DeepGEMM 39d8c4c, third-party/tilelang_ops/ref_mhc.py.
13+No import of the NPU implementation. Both contract-required BF16 boundaries
14+are explicit.
15+"""
16+from typing import NamedTuple
17+ 
18+import torch
19+ 
20+ 
21+class MegaMhcInputs(NamedTuple):
22+ x: torch.Tensor
23+ residual: torch.Tensor
24+ previous_mix: torch.Tensor
25+ post_mix: torch.Tensor
26+ comb_res_mix: torch.Tensor
27+ fn: torch.Tensor
28+ mix_scales: torch.Tensor
29+ mix_bases: torch.Tensor
30+ rmsnorm_weight: torch.Tensor
31+ 
32+ 
33+def make_inputs(tokens, hidden, seed=2026, mode="random"):
34+ gen = torch.Generator().manual_seed(seed)
35+ 
36+ def randn(shape):
37+ return torch.randn(shape, generator=gen, dtype=torch.float32)
38+ x = randn((tokens, hidden)).bfloat16()
39+ r = randn((tokens, 4, hidden)).bfloat16()
40+ prev = randn((tokens, 4)).sigmoid()
41+ post = randn((tokens, 4, 1)).sigmoid()
42+ comb = torch.rand((tokens, 4, 4), generator=gen)
43+ for _ in range(3):
44+ comb = comb / comb.sum(-1, keepdim=True)
45+ comb = comb / comb.sum(-2, keepdim=True)
46+ fn = randn((24, 4 * hidden)) * 0.01
47+ scales = randn((3,)) * 0.1
48+ bases = randn((24,)) * 0.1
49+ gamma = (randn((hidden,)) * 0.1 + 1.0).bfloat16()
50+ if mode == "zero":
51+ x.zero_()
52+ r.zero_()
53+ elif mode == "tiny":
54+ x = (x.float() * 1e-7).bfloat16()
55+ r = (r.float() * 1e-7).bfloat16()
56+ prev *= 0.125
57+ post *= 0.125
58+ fn *= 4
59+ gamma = (gamma.float() * 0.125).bfloat16()
60+ elif mode != "random":
61+ raise ValueError(mode)
62+ return MegaMhcInputs(x, r, prev, post, comb, fn, scales, bases, gamma)
63+ 
64+ 
65+@torch.no_grad()
66+def mega_mhc_golden_cpu(x, residual, previous_mix, post_mix, comb_res_mix,
67+ fn, mix_scales, mix_bases, rmsnorm_weight, *,
68+ hc_norm_eps=2e-5, hc_pre_eps=3e-4, hc_post_scale=1.25,
69+ sinkhorn_eps=2e-6, num_sinkhorn_iters=10, rmsnorm_eps=7e-6):
70+ if not all(t.device.type == "cpu" for t in (x, residual, fn)):
71+ raise ValueError("golden inputs must be CPU tensors")
72+ r = (torch.einsum("tij,tih->tjh", comb_res_mix.float(), residual.float())
73+ + x.float().unsqueeze(1) * post_mix.float()).bfloat16()
74+ u = (r.float() * previous_mix.float().unsqueeze(-1)).sum(1).bfloat16()
75+ flat = r.float().flatten(1)
76+ logits = (flat @ fn.float().T) * torch.rsqrt(flat.square().mean(1) + hc_norm_eps).unsqueeze(1)
77+ scales = torch.cat((mix_scales[0].expand(4), mix_scales[1].expand(4), mix_scales[2].expand(16)))
78+ logits = logits * scales + mix_bases
79+ new_pre = logits[:, :4].sigmoid() + hc_pre_eps
80+ new_post = (logits[:, 4:8].sigmoid() * hc_post_scale).unsqueeze(-1)
81+ new_comb = logits[:, 8:].reshape(-1, 4, 4).softmax(-1) + sinkhorn_eps
82+ new_comb = new_comb / (new_comb.sum(-2, keepdim=True) + sinkhorn_eps)
83+ for _ in range(num_sinkhorn_iters - 1):
84+ new_comb = new_comb / (new_comb.sum(-1, keepdim=True) + sinkhorn_eps)
85+ new_comb = new_comb / (new_comb.sum(-2, keepdim=True) + sinkhorn_eps)
86+ y = (u.float() * torch.rsqrt(u.float().square().mean(1) + rmsnorm_eps).unsqueeze(1)
87+ * rmsnorm_weight.float()).bfloat16()
88+ return r, new_post, new_comb, y, new_pre
@@ -0,0 +1,34 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+ 
10+"""Fixed per-output tolerances from vLLM PR #56255's correctness test."""
11+import torch
12+ 
13+NAMES = ("new_residual", "new_post_mix", "new_comb_res_mix", "y_bf16", "new_prev_mix")
14+LIMITS = ((1e-5, 1e-2), (1e-6, 1e-3), (1e-6, 1e-3), (1e-5, 1e-2), (1e-6, 1e-3))
15+ 
16+ 
17+def assert_outputs(actual, expected):
18+ if len(actual) != 5 or len(expected) != 5:
19+ raise AssertionError("expected five outputs")
20+ report = {}
21+ for name, a, e, (atol, rtol) in zip(NAMES, actual, expected, LIMITS):
22+ a = a.detach().cpu()
23+ if a.shape != e.shape or a.dtype != e.dtype:
24+ raise AssertionError(f"{name}: shape/dtype mismatch")
25+ if not a.is_contiguous() or not torch.isfinite(a).all():
26+ raise AssertionError(f"{name}: output is not contiguous/finite")
27+ torch.testing.assert_close(a, e, atol=atol, rtol=rtol, msg=lambda m: name + ": " + m)
28+ error = (a.float() - e.float()).abs()
29+ report[name] = {
30+ "atol": atol, "rtol": rtol,
31+ "max_abs": error.max().item() if error.numel() else 0.0,
32+ "max_tolerance_fraction": (error / (atol + rtol * e.float().abs())).max().item() if error.numel() else 0.0,
33+ }
34+ return report
@@ -0,0 +1,106 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+"""End-to-end operator checks for typical shapes and shape/value boundaries."""
10+import math
11+ 
12+import pytest
13+import torch
14+import torch_npu # Register the NPU backend.
15+ 
16+from mega_mhc_golden_cpu import make_inputs, mega_mhc_golden_cpu
17+from mega_mhc_precision_compare import assert_outputs
18+ 
19+import pypto_gym
20+ 
21+# pypto_gym is lazy; register torch.ops before calling it directly.
22+pypto_gym.load()
23+ 
24+pytestmark = pytest.mark.soc('950')
25+ 
26+# T, H, input distribution, batch override, and one explicitly selected Torch API.
27+# Each entry is one complete operator call, not a sub-kernel or framework test.
28+CASES = [
29+ # One typical shape for each supported H, including the two larger workloads.
30+ pytest.param(128, 1024, 'random', None, 'python', id='typical_t128_h1024'),
31+ pytest.param(128, 2048, 'random', None, 'torch', id='typical_t128_h2048'),
32+ pytest.param(128, 3072, 'random', None, 'python', id='typical_t128_h3072'),
33+ pytest.param(200, 4096, 'random', None, 'torch', id='typical_t200_h4096'),
34+ pytest.param(128, 5120, 'random', None, 'python', id='typical_t128_h5120'),
35+ pytest.param(96, 5120, 'random', None, 'torch', id='typical_t96_h5120'),
36+ pytest.param(128, 6144, 'random', None, 'torch', id='typical_t128_h6144'),
37+ pytest.param(1025, 7168, 'random', None, 'python', id='typical_t1025_h7168'),
38+ # Empty and smallest nonempty token dimensions.
39+ pytest.param(0, 1024, 'random', None, 'torch', id='empty_t0_h1024'),
40+ pytest.param(1, 7168, 'random', None, 'python', id='single_t1_h7168'),
41+ # Partial/full/next token job (32 tokens in the batch16 configuration).
42+ pytest.param(31, 4096, 'random', None, 'torch', id='small_tail_t31_h4096'),
43+ pytest.param(32, 4096, 'random', None, 'python', id='small_tail_t32_h4096'),
44+ pytest.param(33, 4096, 'random', None, 'torch', id='small_tail_t33_h4096'),
45+ # Partial/full/next block for the two batch16 block capacities.
46+ pytest.param(255, 4096, 'random', None, 'python', id='block_t255_h4096'),
47+ pytest.param(256, 4096, 'random', None, 'torch', id='block_t256_h4096'),
48+ pytest.param(257, 4096, 'random', None, 'python', id='block_t257_h4096'),
49+ pytest.param(223, 7168, 'random', None, 'torch', id='block_t223_h7168'),
50+ pytest.param(224, 7168, 'random', None, 'python', id='block_t224_h7168'),
51+ pytest.param(225, 7168, 'random', None, 'torch', id='block_t225_h7168'),
52+ # The automatic batch16 -> batch8 shape threshold, including a batch8 tail.
53+ pytest.param(4095, 7168, 'random', None, 'python', id='dispatch_t4095_h7168'),
54+ pytest.param(4096, 7168, 'random', None, 'torch', id='dispatch_t4096_h7168'),
55+ pytest.param(4097, 7168, 'random', None, 'python', id='dispatch_t4097_h7168'),
56+ # Degenerate RMS inputs: zero and small nonzero values.
57+ pytest.param(1, 1024, 'zero', None, 'torch', id='zeros_t1_h1024'),
58+ pytest.param(5, 3072, 'tiny', None, 'python', id='near_zero_t5_h3072'),
59+ # A caller may still force batch16 at the automatic switch point.
60+ pytest.param(4096, 7168, 'random', 16, 'torch', id='force_batch16_t4096_h7168'),
61+]
62+ 
63+ 
64+def guarded(shape, dtype, device):
65+ base = torch.full((math.prod(shape) + 256,), 37, dtype=dtype, device=device)
66+ return base[128:-128].view(shape), base
67+ 
68+ 
69+def check_guards(bases):
70+ for base in bases:
71+ assert bool((base[:128] == 37).all()), 'prefix guard overwritten'
72+ assert bool((base[-128:] == 37).all()), 'suffix guard overwritten'
73+ 
74+ 
75+@pytest.mark.parametrize('tokens,hidden,data_mode,batch,api', CASES)
76+def test_mega_mhc(tokens, hidden, data_mode, batch, api, device):
77+ cpu = make_inputs(tokens, hidden, seed=2026 + tokens, mode=data_mode)
78+ expected = mega_mhc_golden_cpu(*cpu)
79+ input_pairs = [guarded(tuple(value.shape), value.dtype, device) for value in cpu]
80+ inputs = tuple(pair[0] for pair in input_pairs)
81+ for value, original in zip(inputs, cpu):
82+ value.copy_(original)
83+ # Exactly one functional API call per case; the binding allocates outputs.
84+ if api == 'python':
85+ outputs = pypto_gym.mega_mhc(*inputs, batch=batch)
86+ elif batch is None:
87+ outputs = torch.ops.pypto_gym.mega_mhc(*inputs)
88+ else:
89+ outputs = torch.ops.pypto_gym.mega_mhc(*inputs, batch=batch)
90+ torch.npu.synchronize()
91+ assert_outputs(outputs, expected)
92+ for value, original in zip(inputs, cpu):
93+ torch.testing.assert_close(value.cpu(), original, rtol=0, atol=0)
94+ check_guards([base for _, base in input_pairs])
95+ 
96+ 
97+def test_mega_mhc_rejects_internal_storage(device):
98+ inputs = [value.to(device) for value in make_inputs(33, 1024, seed=2026)]
99+ inputs[0] = torch_npu.npu_format_cast(inputs[0], 29) # FRACTAL_NZ
100+ assert inputs[0].is_contiguous() # Logical contiguity cannot detect NZ.
101+ torch.npu.synchronize()
102+ 
103+ # Validation must fail on the caller thread, before any ACLNN work is queued.
104+ with pytest.raises(RuntimeError, match='x must use ND storage format'):
105+ torch.ops.pypto_gym.mega_mhc(*inputs)
106+ torch.npu.synchronize()
@@ -0,0 +1,3 @@
1+if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD)
2+ gym_add_torch_binding(mega_mhc)
3+endif()
@@ -0,0 +1,193 @@
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+#include "gym_aclnn.h"
11+#include <ATen/ATen.h>
12+#include <ATen/core/grad_mode.h>
13+#include <c10/core/DeviceGuard.h>
14+#include <cmath>
15+#include <limits>
16+#include <torch/library.h>
17+#include <tuple>
18+ 
19+namespace {
20+using Result =
21+ std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor>;
22+static void ValidateInputs(const at::Tensor &x,
23+ const std::vector<at::Tensor> &inputs) {
24+ const int64_t t = x.size(0), h = x.size(1);
25+ const char *const names[] = {"x", "residual", "previous_mix",
26+ "post_mix", "comb_res_mix", "fn",
27+ "mix_scales", "mix_bases", "rmsnorm_weight"};
28+ const std::vector<std::vector<int64_t>> shapes = {
29+ {t, h}, {t, 4, h}, {t, 4}, {t, 4, 1}, {t, 4, 4},
30+ {24, 4 * h}, {3}, {24}, {h}};
31+ for (size_t i = 0; i < inputs.size(); ++i) {
32+ const auto dtype =
33+ (i == 0 || i == 1 || i == 8) ? at::kBFloat16 : at::kFloat;
34+ TORCH_CHECK(inputs[i].device() == x.device() && inputs[i].is_contiguous() &&
35+ inputs[i].scalar_type() == dtype &&
36+ inputs[i].sizes().vec() == shapes[i],
37+ "invalid input ", i);
38+ gym_torch::CheckNDStorage(inputs[i], names[i]);
39+ }
40+}
41+ 
42+static std::vector<at::Tensor> AllocateOutputs(
43+ const at::Tensor &x, const std::vector<std::vector<int64_t>> &outShapes,
44+ const char *const outputNames[]) {
45+ std::vector<at::Tensor> outputs;
46+ outputs.reserve(5);
47+ for (size_t i = 0; i < 5; ++i)
48+ outputs.push_back(at::empty(
49+ outShapes[i],
50+ x.options().dtype((i == 0 || i == 3) ? at::kBFloat16 : at::kFloat)));
51+ for (size_t i = 0; i < 5; ++i) {
52+ TORCH_CHECK(outputs[i].device() == x.device() &&
53+ outputs[i].is_contiguous() &&
54+ outputs[i].sizes().vec() == outShapes[i],
55+ "invalid output ", i);
56+ gym_torch::CheckNDStorage(outputs[i], outputNames[i]);
57+ }
58+ return outputs;
59+}
60+ 
61+static void CheckNoGrad(const std::vector<at::Tensor> &inputs) {
62+ for (const auto &value : inputs)
63+ TORCH_CHECK(!at::GradMode::is_enabled() || !value.requires_grad(),
64+ "MegaMhc provides forward computation only; use "
65+ "torch.no_grad() for inference");
66+}
67+ 
68+static void EnqueueMegaMhc(const std::vector<at::Tensor> &inputs,
69+ const std::vector<at::Tensor> &outputs, double hc,
70+ double pre, double post, double sink,
71+ int64_t repeat, double norm, int64_t batch_attr) {
72+ using GetWorkspace = aclnnStatus (*)(
73+ const aclTensor *, const aclTensor *, const aclTensor *,
74+ const aclTensor *, const aclTensor *, const aclTensor *,
75+ const aclTensor *, const aclTensor *, const aclTensor *, double, double,
76+ double, double, int64_t, double, int64_t, const aclTensor *,
77+ const aclTensor *, const aclTensor *, const aclTensor *,
78+ const aclTensor *, uint64_t *, aclOpExecutor **);
79+ static const auto get_workspace =
80+ gym_torch::Symbol<GetWorkspace>("aclnnMegaMhcGetWorkspaceSize");
81+ static const auto execute =
82+ gym_torch::Symbol<gym_torch::Execute>("aclnnMegaMhc");
83+ auto tensors = inputs;
84+ tensors.insert(tensors.end(), outputs.begin(), outputs.end());
85+ gym_torch::Enqueue(
86+ "aclnnMegaMhc", tensors,
87+ [hc, pre, post, sink, repeat, norm, batch_attr](const auto &values,
88+ auto stream) {
89+ std::vector<gym_torch::TensorHandle> handles;
90+ for (const auto &value : values)
91+ handles.push_back(gym_torch::Tensor(value));
92+ uint64_t bytes = 0;
93+ aclOpExecutor *executor = nullptr;
94+ const auto status = get_workspace(
95+ handles[0].get(), handles[1].get(), handles[2].get(),
96+ handles[3].get(), handles[4].get(), handles[5].get(),
97+ handles[6].get(), handles[7].get(), handles[8].get(), hc, pre, post,
98+ sink, repeat, norm, batch_attr, handles[9].get(), handles[10].get(),
99+ handles[11].get(), handles[12].get(), handles[13].get(), &bytes,
100+ &executor);
101+ TORCH_CHECK(status == 0,
102+ "aclnnMegaMhcGetWorkspaceSize failed, status=", status,
103+ ": ", aclGetRecentErrMsg());
104+ gym_torch::ExecuteOp(execute, bytes, executor, stream);
105+ return 0;
106+ });
107+}
108+ 
109+static std::vector<at::Tensor>
110+Run(at::Tensor x, at::Tensor residual, at::Tensor previous_mix,
111+ at::Tensor post_mix, at::Tensor comb_res_mix, at::Tensor fn,
112+ at::Tensor mix_scales, at::Tensor mix_bases, at::Tensor rmsnorm_weight,
113+ double hc, double pre, double post, double sink, int64_t repeat,
114+ double norm, c10::optional<int64_t> batch) {
115+ TORCH_CHECK(x.dim() == 2 && x.scalar_type() == at::kBFloat16 &&
116+ x.device().is_privateuseone(),
117+ "x must be a rank-2 BF16 NPU tensor");
118+ const c10::OptionalDeviceGuard guard(x.device());
119+ const int64_t t = x.size(0), h = x.size(1);
120+ TORCH_CHECK(h >= 1024 && h <= 7168 && h % 1024 == 0, "unsupported H");
121+ TORCH_CHECK(!batch.has_value() || *batch == 0 || *batch == 16,
122+ "batch must be 0 (automatic) or 16");
123+ for (double v : {hc, pre, post, sink, norm})
124+ TORCH_CHECK(std::isfinite(v) && v >= 0 &&
125+ v <= std::numeric_limits<float>::max(),
126+ "invalid scalar");
127+ TORCH_CHECK(hc > 0 && norm > 0 && repeat >= 1 && repeat <= 65535,
128+ "invalid RMS epsilon/iterations");
129+ std::vector<at::Tensor> inputs = {x, residual, previous_mix,
130+ post_mix, comb_res_mix, fn,
131+ mix_scales, mix_bases, rmsnorm_weight};
132+ ValidateInputs(x, inputs);
133+ const std::vector<std::vector<int64_t>> outShapes = {
134+ {t, 4, h}, {t, 4, 1}, {t, 4, 4}, {t, h}, {t, 4}};
135+ const char *const outputNames[] = {
136+ "new_residual", "new_post_mix", "new_comb_res_mix", "y", "new_previous_mix"};
137+ auto outputs = AllocateOutputs(x, outShapes, outputNames);
138+ CheckNoGrad(inputs);
139+ if (t == 0) return outputs;
140+ EnqueueMegaMhc(inputs, outputs, hc, pre, post, sink, repeat, norm,
141+ batch.value_or(0));
142+ return outputs;
143+}
144+ 
145+static Result AsTuple(const std::vector<at::Tensor> &outputs) {
146+ return {outputs[0], outputs[1], outputs[2], outputs[3], outputs[4]};
147+}
148+static Result MegaMhc(const at::Tensor &x, const at::Tensor &residual,
149+ const at::Tensor &previous_mix,
150+ const at::Tensor &post_mix,
151+ const at::Tensor &comb_res_mix, const at::Tensor &fn,
152+ const at::Tensor &mix_scales, const at::Tensor &mix_bases,
153+ const at::Tensor &rmsnorm_weight, double hc, double pre,
154+ double post, double sink, int64_t repeat, double norm,
155+ int64_t batch) {
156+ return AsTuple(Run(x, residual, previous_mix, post_mix, comb_res_mix, fn,
157+ mix_scales, mix_bases, rmsnorm_weight, hc, pre, post, sink,
158+ repeat, norm, batch));
159+}
160+ 
161+static Result Meta(const at::Tensor &x, const at::Tensor &residual,
162+ const at::Tensor &previous_mix, const at::Tensor &post_mix,
163+ const at::Tensor &comb_res_mix, const at::Tensor &fn,
164+ const at::Tensor &mix_scales, const at::Tensor &mix_bases,
165+ const at::Tensor &rmsnorm_weight, double hc, double pre,
166+ double post, double sink, int64_t repeat, double norm,
167+ int64_t batch) {
168+ TORCH_CHECK(x.dim() == 2 && x.scalar_type() == at::kBFloat16,
169+ "x must be a rank-2 BF16 tensor");
170+ const auto t = x.sym_size(0), h = x.sym_size(1);
171+ auto bf16 = x.options().dtype(at::kBFloat16);
172+ auto fp32 = x.options().dtype(at::kFloat);
173+ return {at::empty_symint({t, 4, h}, bf16), at::empty_symint({t, 4, 1}, fp32),
174+ at::empty_symint({t, 4, 4}, fp32), at::empty_symint({t, h}, bf16),
175+ at::empty_symint({t, 4}, fp32)};
176+}
177+ 
178+} // namespace
179+ 
180+TORCH_LIBRARY_FRAGMENT(pypto_gym, m) {
181+ m.def("mega_mhc(Tensor x, Tensor residual, Tensor previous_mix, Tensor "
182+ "post_mix, Tensor comb_res_mix, Tensor fn, Tensor mix_scales, Tensor "
183+ "mix_bases, Tensor rmsnorm_weight, *, float hc_norm_eps=2e-5, float "
184+ "hc_pre_eps=3e-4, float hc_post_scale=1.25, float sinkhorn_eps=2e-6, "
185+ "int num_sinkhorn_iters=10, float rmsnorm_eps=7e-6, int batch=0) -> "
186+ "(Tensor, Tensor, Tensor, Tensor, Tensor)");
187+}
188+TORCH_LIBRARY_IMPL(pypto_gym, PrivateUse1, m) {
189+ m.impl("mega_mhc", TORCH_FN(MegaMhc));
190+}
191+TORCH_LIBRARY_IMPL(pypto_gym, Meta, m) {
192+ m.impl("mega_mhc", TORCH_FN(Meta));
193+}
@@ -0,0 +1,40 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+"""Public Torch frontend for the precompiled MegaMhc operator."""
10+import math
11+import torch
12+ 
13+ 
14+def mega_mhc(x, residual, previous_mix, post_mix, comb_res_mix, fn,
15+ mix_scales, mix_bases, rmsnorm_weight, *, hc_norm_eps=2e-5,
16+ hc_pre_eps=3e-4, hc_post_scale=1.25, sinkhorn_eps=2e-6,
17+ num_sinkhorn_iters=10, rmsnorm_eps=7e-6, batch=None):
18+ """Return (new_residual, new_post_mix, new_comb_res_mix, y, new_previous_mix).
19+ 
20+ Runs the installed ACLNN binary on the current NPU stream. batch=None selects
21+ automatically; batch=16 forces batch16. Outputs are allocated internally.
22+ The operator provides forward computation only.
23+ """
24+ if batch is not None and (type(batch) is not int or batch != 16):
25+ raise ValueError('public batch must be None or 16')
26+ values = (hc_norm_eps, hc_pre_eps, hc_post_scale, sinkhorn_eps, rmsnorm_eps)
27+ if any(isinstance(v, bool) or not isinstance(v, (float, int)) or
28+ not math.isfinite(v) or v < 0 for v in values):
29+ raise ValueError('eps and post scale must be finite nonnegative scalars')
30+ if hc_norm_eps <= 0 or rmsnorm_eps <= 0:
31+ raise ValueError('the two RMS eps values must be positive')
32+ if type(num_sinkhorn_iters) is not int or not 1 <= num_sinkhorn_iters <= 65535:
33+ raise ValueError('num_sinkhorn_iters must be an integer in [1,65535]')
34+ inputs = (x, residual, previous_mix, post_mix, comb_res_mix, fn,
35+ mix_scales, mix_bases, rmsnorm_weight)
36+ attrs = dict(hc_norm_eps=hc_norm_eps, hc_pre_eps=hc_pre_eps,
37+ hc_post_scale=hc_post_scale, sinkhorn_eps=sinkhorn_eps,
38+ num_sinkhorn_iters=num_sinkhorn_iters, rmsnorm_eps=rmsnorm_eps,
39+ batch=0 if batch is None else batch)
40+ return torch.ops.pypto_gym.mega_mhc.default(*inputs, **attrs)
@@ -51,6 +51,7 @@ Repository = "https://gitcode.com/cann/pypto-gym"
51 51 
52[project.optional-dependencies]52[project.optional-dependencies]
53dev = [53dev = [
54+ "PyYAML>=6.0",
54 "setuptools>=70.3.0",55 "setuptools>=70.3.0",
55 "pip",56 "pip",
56 "build",57 "build",
@@ -60,6 +61,7 @@ dev = [
60 "pytest-xdist",61 "pytest-xdist",
61]62]
62tests = [63tests = [
64+ "PyYAML>=6.0",
63 "pytest>=7",65 "pytest>=7",
64 "pytest-forked",66 "pytest-forked",
65 "pytest-xdist",67 "pytest-xdist",
@@ -14,8 +14,8 @@ python_files = test_*.py
14# JUnit XML 报告格式(--junitxml 时生效),xunit1 兼容旧版 CI 解析14# JUnit XML 报告格式(--junitxml 时生效),xunit1 兼容旧版 CI 解析
15junit_family = xunit115junit_family = xunit1
16 16 
17-# 默认测试路径:benchmark 自测 + 算子库本体 + tests/ops(与 upstream 一致)17+# 默认测试路径:benchmark 自测 + 算子库本体 + tests/ops + tests/unit(主机侧单测)
18-testpaths = tests/ops18+testpaths = tests/ops tests/unit
19 19 
20# 测试公共层路径:所有算子的测试可直接 import tests/common 下的模块(pytest>=7)20# 测试公共层路径:所有算子的测试可直接 import tests/common 下的模块(pytest>=7)
21pythonpath = tests/common21pythonpath = tests/common
@@ -3,6 +3,7 @@
3 3 
4pypto>=0.2.04pypto>=0.2.0
5numpy5numpy
6+PyYAML>=6.0
6pytest>=77pytest>=7
7pytest-forked==1.6.08pytest-forked==1.6.0
8pytest-xdist9pytest-xdist
@@ -7,5 +7,6 @@
7 --quiet Quiet mode7 --quiet Quiet mode
8 8 
9 Post-install:9 Post-install:
10- source <opp>/vendors/pypto_gym/bin/set_env.bash Set runtime environment10+ Standard CANN install: import pypto_gym directly with the CANN base environment loaded.
11+ Custom location: source <opp>/vendors/pypto_gym/bin/set_env.bash
11 bash <opp>/vendors/pypto_gym/scripts/uninstall.sh Uninstall (when .run is deleted)12 bash <opp>/vendors/pypto_gym/scripts/uninstall.sh Uninstall (when .run is deleted)
@@ -23,6 +23,7 @@ readonly TMP_PKG_VERSION_FILE="${TMP_PKG_INFO_PATH}/version.info"
23unset tmp_cfd23unset tmp_cfd
24 24 
25readonly VENDOR_NAME="pypto_gym"25readonly VENDOR_NAME="pypto_gym"
26+source "${TMP_PKG_SCRIPTS_PATH}/python_registration.sh"
26 27 
27########################################################################################################################28########################################################################################################################
28# 日志29# 日志
@@ -168,6 +169,29 @@ do_install() {
168 [ -d "${TMP_PKG_ROOT_PATH}/packages/vendors/${VENDOR_NAME}" ] \169 [ -d "${TMP_PKG_ROOT_PATH}/packages/vendors/${VENDOR_NAME}" ] \
169 || exit_log 1 "vendor payload missing in package: ${TMP_PKG_ROOT_PATH}/packages/vendors/${VENDOR_NAME}"170 || exit_log 1 "vendor payload missing in package: ${TMP_PKG_ROOT_PATH}/packages/vendors/${VENDOR_NAME}"
170 171 
172+ local has_bindings=n register_python=n check_rc=0
173+ if [ -f "${TMP_PKG_ROOT_PATH}/packages/vendors/${VENDOR_NAME}/python/pypto_gym/operators.json" ]; then
174+ has_bindings=y
175+ gym_python_check_links "${targetdir}"
176+ check_rc=$?
177+ case "${check_rc}" in
178+ 0) register_python=y ;;
179+ 2) gym_python_warn_degraded "${targetdir}" "CANN site-packages is not writable" ;;
180+ *) exit_log 1 "cannot register Python bindings" ;;
181+ esac
182+ fi
183+ 
184+ # Always drop links left by a previous version; only a writable standard
185+ # CANN layout can recreate them.
186+ if ! gym_python_remove_links "${targetdir}"; then
187+ if [ "${has_bindings}" = y ]; then
188+ gym_python_warn_degraded "${targetdir}" "cannot remove stale Python binding links"
189+ register_python=n
190+ else
191+ exit_log 1 "cannot remove old Python binding registration"
192+ fi
193+ fi
194+ 
171 if [ -d "${targetdir}/${vendordir}" ]; then195 if [ -d "${targetdir}/${vendordir}" ]; then
172 log "[INFO] ${targetdir}/${vendordir} already exists, old version will be replaced"196 log "[INFO] ${targetdir}/${vendordir} already exists, old version will be replaced"
173 chmod -R +w "${targetdir}/${vendordir}" >/dev/null 2>&1197 chmod -R +w "${targetdir}/${vendordir}" >/dev/null 2>&1
@@ -179,12 +203,6 @@ do_install() {
179 if ! cp -rf "${TMP_PKG_ROOT_PATH}/packages/vendors/${VENDOR_NAME}/." "${targetdir}/${vendordir}/"; then203 if ! cp -rf "${TMP_PKG_ROOT_PATH}/packages/vendors/${VENDOR_NAME}/." "${targetdir}/${vendordir}/"; then
180 exit_log 1 "copy vendor files failed"204 exit_log 1 "copy vendor files failed"
181 fi205 fi
182- chmod -R 550 "${targetdir}/${vendordir}" >/dev/null 2>&1
183- if [ "${ARG_INSTALL_FOR_ALL}" = "y" ]; then
184- # multi-user scenario: world-readable vendor tree + config.ini
185- chmod -R 555 "${targetdir}/${vendordir}" >/dev/null 2>&1
186- fi
187- 
188 update_load_priority206 update_load_priority
189 if [ "${ARG_INSTALL_FOR_ALL}" = "y" ] && [ -f "${config_file}" ]; then207 if [ "${ARG_INSTALL_FOR_ALL}" = "y" ] && [ -f "${config_file}" ]; then
190 chmod 755 "${config_file}" 2>/dev/null208 chmod 755 "${config_file}" 2>/dev/null
@@ -201,23 +219,50 @@ do_install() {
201#!/bin/bash219#!/bin/bash
202export ASCEND_CUSTOM_OPP_PATH=${targetdir}/${vendordir}:\${ASCEND_CUSTOM_OPP_PATH}220export ASCEND_CUSTOM_OPP_PATH=${targetdir}/${vendordir}:\${ASCEND_CUSTOM_OPP_PATH}
203export LD_LIBRARY_PATH=${targetdir}/${vendordir}/op_api/lib/:\${LD_LIBRARY_PATH}221export LD_LIBRARY_PATH=${targetdir}/${vendordir}/op_api/lib/:\${LD_LIBRARY_PATH}
222+if [ -d "${targetdir}/${vendordir}/python" ]; then
223+ export PYTHONPATH=${targetdir}/${vendordir}/python:\${PYTHONPATH}
224+fi
204EOF225EOF
205 chmod 550 "${targetdir}/${vendordir}/bin/set_env.bash"226 chmod 550 "${targetdir}/${vendordir}/bin/set_env.bash"
206 227 
207- # uninstall.sh 落到 vendor scripts/ 目录(供 .run 包已删除、仅存安装结果时直接 bash uninstall.sh)228+ if [ "${register_python}" = y ]; then
229+ gym_python_install_links "${targetdir}" || {
230+ gym_python_warn_degraded "${targetdir}" "cannot create Python binding links"
231+ register_python=n
232+ }
233+ fi
234+ 
235+ # 独立卸载入口和共享登记逻辑一起交付。
208 mkdir -p "${targetdir}/${vendordir}/scripts"236 mkdir -p "${targetdir}/${vendordir}/scripts"
209- if [ -f "${TMP_PKG_SCRIPTS_PATH}/uninstall.sh" ]; then237+ for script_name in uninstall.sh python_registration.sh; do
210- cp -f "${TMP_PKG_SCRIPTS_PATH}/uninstall.sh" "${targetdir}/${vendordir}/scripts/uninstall.sh"238+ cp -f "${TMP_PKG_SCRIPTS_PATH}/${script_name}" "${targetdir}/${vendordir}/scripts/${script_name}" \
211- chmod 550 "${targetdir}/${vendordir}/scripts/uninstall.sh"239+ || exit_log 1 "cannot install ${script_name}"
240+ chmod 550 "${targetdir}/${vendordir}/scripts/${script_name}"
241+ done
242+ 
243+ # Freeze permissions only after every vendor-side write is complete, so a
244+ # non-root owner can finish the installation before the tree becomes 550.
245+ chmod -R 550 "${targetdir}/${vendordir}" >/dev/null 2>&1
246+ if [ "${ARG_INSTALL_FOR_ALL}" = "y" ]; then
247+ # multi-user scenario: world-readable vendor tree + config.ini
248+ chmod -R 555 "${targetdir}/${vendordir}" >/dev/null 2>&1
212 fi249 fi
213 250 
214 log "[INFO] install success. vendor: ${VENDOR_NAME} -> ${targetdir}/${vendordir}"251 log "[INFO] install success. vendor: ${VENDOR_NAME} -> ${targetdir}/${vendordir}"
215 log "[INFO] verify: grep load_priority ${config_file}"252 log "[INFO] verify: grep load_priority ${config_file}"
216- log "[INFO] using requirements: source ${targetdir}/${vendordir}/bin/set_env.bash"253+ public_python_dir=$(gym_python_public_dir "${targetdir}")
254+ if [ -n "${public_python_dir}" ] && [ -f "${public_python_dir}/operators.json" ]; then
255+ log "[INFO] Python bindings registered: ${public_python_dir}; no vendor source required with CANN environment loaded"
256+ elif [ "${has_bindings}" = y ]; then
257+ log "[WARN] Python bindings not registered; source ${targetdir}/${vendordir}/bin/set_env.bash to use pypto_gym"
258+ else
259+ log "[INFO] custom-location environment: source ${targetdir}/${vendordir}/bin/set_env.bash"
260+ fi
217 log "[INFO] uninstall: bash ${targetdir}/${vendordir}/scripts/uninstall.sh"261 log "[INFO] uninstall: bash ${targetdir}/${vendordir}/scripts/uninstall.sh"
218}262}
219 263 
220do_uninstall() {264do_uninstall() {
265+ gym_python_remove_links "${targetdir}" || exit_log 1 "cannot remove Python binding registration"
221 if [ ! -d "${targetdir}/${vendordir}" ]; then266 if [ ! -d "${targetdir}/${vendordir}" ]; then
222 log "[INFO] ${targetdir}/${vendordir} not exist, no need to uninstall"267 log "[INFO] ${targetdir}/${vendordir} not exist, no need to uninstall"
223 remove_load_priority268 remove_load_priority
@@ -0,0 +1,101 @@
1+#!/bin/bash
2+# -----------------------------------------------------------------------------------------------------------
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+# Keep the payload vendor-local and expose only its binding entries through the
13+# Python path already set by CANN. Never replace an existing wheel's ops tree.
14+gym_python_public_dir() {
15+ local opp_root cann_root
16+ opp_root=$(readlink -f "$1") || return 1
17+ cann_root=$(dirname "${opp_root}")
18+ if [ "${opp_root}" = "${cann_root}/opp" ] &&
19+ [ -f "${cann_root}/set_env.sh" ] &&
20+ [ -d "${cann_root}/python/site-packages" ]; then
21+ printf '%s\n' "${cann_root}/python/site-packages/pypto_gym"
22+ fi
23+}
24+ 
25+gym_python_link_owned() {
26+ [ -L "$1" ] && [ "$(readlink -m "$1")" = "$(readlink -m "$2")" ]
27+}
28+ 
29+# Return codes:
30+# 0 - registration is possible, or the install is not a standard CANN layout
31+# 1 - an existing entry belongs to another package (fatal: never overwrite)
32+# 2 - the CANN site-packages is not writable (degradable: install vendor only)
33+gym_python_check_links() {
34+ local public_dir vendor_python entry path
35+ public_dir=$(gym_python_public_dir "$1") || return 1
36+ [ -n "${public_dir}" ] || return 0
37+ vendor_python="$1/vendors/pypto_gym/python/pypto_gym"
38+ if [ -L "${public_dir}" ] || { [ -e "${public_dir}" ] && [ ! -d "${public_dir}" ]; }; then
39+ printf 'Python binding path is already occupied: %s\n' "${public_dir}" >&2
40+ return 1
41+ fi
42+ # Ownership is checked before writability: another package must never be
43+ # overwritten even when the current user could technically write the entry.
44+ for entry in __init__.py _loader.py _native _frontends operators.json; do
45+ path="${public_dir}/${entry}"
46+ if { [ -e "${path}" ] || [ -L "${path}" ]; } &&
47+ ! gym_python_link_owned "${path}" "${vendor_python}/${entry}"; then
48+ printf 'Python binding entry is already owned by another package: %s\n' "${path}" >&2
49+ return 1
50+ fi
51+ done
52+ if [ ! -w "$(dirname "${public_dir}")" ] ||
53+ { [ -d "${public_dir}" ] && [ ! -w "${public_dir}" ]; }; then
54+ printf 'Python binding path is not writable: %s\n' "${public_dir}" >&2
55+ return 2
56+ fi
57+ return 0
58+}
59+ 
60+# Non-fatal registration failure: keep the vendor install usable through its own
61+# set_env.bash instead of aborting the whole installation.
62+gym_python_warn_degraded() {
63+ local targetdir="$1" reason="$2"
64+ printf 'warning: %s; Python bindings were not registered\n' "${reason}" >&2
65+ printf 'warning: run "source %s/vendors/pypto_gym/bin/set_env.bash" to use pypto_gym in this shell\n' \
66+ "${targetdir}" >&2
67+}
68+ 
69+gym_python_remove_links() {
70+ local public_dir vendor_python entry path removed_any=n
71+ public_dir=$(gym_python_public_dir "$1") || return 1
72+ [ -n "${public_dir}" ] || return 0
73+ vendor_python="$1/vendors/pypto_gym/python/pypto_gym"
74+ for entry in __init__.py _loader.py _native _frontends operators.json; do
75+ path="${public_dir}/${entry}"
76+ if gym_python_link_owned "${path}" "${vendor_python}/${entry}"; then
77+ rm -f "${path}" || return 1
78+ removed_any=y
79+ case "${entry}" in
80+ __init__.py|_loader.py)
81+ rm -f "${public_dir}/__pycache__/${entry%.py}."*.pyc || return 1
82+ ;;
83+ esac
84+ fi
85+ done
86+ [ "${removed_any}" = y ] || return 0
87+ rmdir "${public_dir}/__pycache__" "${public_dir}" 2>/dev/null || true
88+}
89+ 
90+gym_python_install_links() {
91+ local public_dir vendor_python entry link_target
92+ public_dir=$(gym_python_public_dir "$1") || return 1
93+ [ -n "${public_dir}" ] || return 0
94+ vendor_python="$1/vendors/pypto_gym/python/pypto_gym"
95+ [ -f "${vendor_python}/operators.json" ] || return 0
96+ mkdir -p -m 755 "${public_dir}" || return 1
97+ for entry in __init__.py _loader.py _native _frontends operators.json; do
98+ link_target=$(realpath --relative-to="${public_dir}" "${vendor_python}/${entry}") || return 1
99+ ln -s "${link_target}" "${public_dir}/${entry}" || return 1
100+ done
101+}
@@ -18,6 +18,7 @@ vendor_name=pypto_gym
18# 从本脚本位置反推 vendors 根目录与 config.ini18# 从本脚本位置反推 vendors 根目录与 config.ini
19# 本脚本位于 <opp>/vendors/<vendor>/scripts/uninstall.sh, 向上 2 级 = <opp>/vendors19# 本脚本位于 <opp>/vendors/<vendor>/scripts/uninstall.sh, 向上 2 级 = <opp>/vendors
20curr_path=$(dirname "$(readlink -f "$0")")20curr_path=$(dirname "$(readlink -f "$0")")
21+source "${curr_path}/python_registration.sh"
21vendordir=$(realpath "${curr_path}/../../")22vendordir=$(realpath "${curr_path}/../../")
22config_file="${vendordir}/config.ini"23config_file="${vendordir}/config.ini"
23 24 
@@ -26,6 +27,9 @@ log() {
26 echo "[pypto_gym_uninstall] [$cur_date] $1"27 echo "[pypto_gym_uninstall] [$cur_date] $1"
27}28}
28 29 
30+# 先清理由本包创建的 Python 入口,保留其他 wheel 的 ops 目录。
31+gym_python_remove_links "$(dirname "${vendordir}")" || exit 1
32+ 
29# 删除 vendor 目录33# 删除 vendor 目录
30if [ ! -d "${vendordir}/${vendor_name}" ]; then34if [ ! -d "${vendordir}/${vendor_name}" ]; then
31 log "[INFO] ${vendordir}/${vendor_name} not exist, no need to uninstall"35 log "[INFO] ${vendordir}/${vendor_name} not exist, no need to uninstall"
@@ -10,9 +10,10 @@
10# -----------------------------------------------------------------------------------------------------------10# -----------------------------------------------------------------------------------------------------------
11"""算子调用入口适配(仓级测试公共层).11"""算子调用入口适配(仓级测试公共层).
12 12 
13-按 pytest --mode 选择 jit / aclnn 路径:13+按 pytest --mode 选择 jit / aclnn / torch 路径:
14 jit -> import <op_kernel>/<op>.py 的宿主入口(默认与算子同名)14 jit -> import <op_kernel>/<op>.py 的宿主入口(默认与算子同名)
15 aclnn -> import 预编译桥 aclnn_bridge_<op> 的 <op> 接口(签名与 jit 入口一致)15 aclnn -> import 预编译桥 aclnn_bridge_<op> 的 <op> 接口(签名与 jit 入口一致)
16+ torch -> 已安装 .run 中 pypto_gym.<op> 的正式 Torch 绑定
16 17 
17路径由根 conftest.py / pytest.ini 统一注入, 本模块不做 sys.path 操作.18路径由根 conftest.py / pytest.ini 统一注入, 本模块不做 sys.path 操作.
18算子入口名不合约定时, 用 jit_module/jit_attr 显式指定。19算子入口名不合约定时, 用 jit_module/jit_attr 显式指定。
@@ -124,7 +125,7 @@ def _file_caller(op, path, attribute):
124 125 
125 126 
126def get_mode() -> str:127def get_mode() -> str:
127- """返回当前测试模式(jit/aclnn), 由根 conftest 的 --mode 写入 GYM_TEST_MODE."""128+ """返回当前测试模式(jit/aclnn/torch), 由根 conftest 的 --mode 写入 GYM_TEST_MODE."""
128 return os.environ.get("GYM_TEST_MODE", "jit")129 return os.environ.get("GYM_TEST_MODE", "jit")
129 130 
130 131 
@@ -164,4 +165,6 @@ def get_op_caller(
164 if mode == "aclnn":165 if mode == "aclnn":
165 module = importlib.import_module(aclnn_module or f"aclnn_bridge_{op}")166 module = importlib.import_module(aclnn_module or f"aclnn_bridge_{op}")
166 return getattr(module, aclnn_attr or op)167 return getattr(module, aclnn_attr or op)
167- raise ValueError(f"unsupported test mode: {mode} (expected jit/aclnn)")168+ if mode == "torch":
169+ return getattr(importlib.import_module("pypto_gym"), op)
170+ raise ValueError(f"unsupported test mode: {mode} (expected jit/aclnn/torch)")
@@ -11,11 +11,13 @@
11# 由根 CMakeLists 在 ENABLE_TESTS 时逐级 add_subdirectory 引入;11# 由根 CMakeLists 在 ENABLE_TESTS 时逐级 add_subdirectory 引入;
12# torch 依赖由 cmake/config.cmake 在根作用域统一查找, 此处直接复用其变量与 imported target.12# torch 依赖由 cmake/config.cmake 在根作用域统一查找, 此处直接复用其变量与 imported target.
13 13 
14+find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
14add_library(aclnn_bridge_common INTERFACE)15add_library(aclnn_bridge_common INTERFACE)
15target_include_directories(aclnn_bridge_common16target_include_directories(aclnn_bridge_common
16 INTERFACE17 INTERFACE
17 ${CMAKE_CURRENT_SOURCE_DIR}18 ${CMAKE_CURRENT_SOURCE_DIR}
18 ${TORCH_INCLUDE_DIRS}19 ${TORCH_INCLUDE_DIRS}
20+ ${Python3_INCLUDE_DIRS}
19 ${ASCEND_CANN_PACKAGE_PATH}/include21 ${ASCEND_CANN_PACKAGE_PATH}/include
20)22)
21target_link_libraries(aclnn_bridge_common23target_link_libraries(aclnn_bridge_common
@@ -0,0 +1,47 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+"""Verify the filtered void check used by --ops kernel config generation."""
10+import importlib.util
11+from pathlib import Path
12+import sys
13+import tempfile
14+import unittest
15+ 
16+ROOT = Path(__file__).resolve().parents[2]
17+SCRIPT = ROOT / "cmake/scripts/util/ascendc_ops_config.py"
18+sys.path.insert(0, str(SCRIPT.parent))
19+try:
20+ spec = importlib.util.spec_from_file_location("gym_ops_config", SCRIPT)
21+ ops_config = importlib.util.module_from_spec(spec)
22+ spec.loader.exec_module(ops_config)
23+finally:
24+ sys.path.remove(str(SCRIPT.parent))
25+ 
26+ 
27+class OpsConfigVoidTest(unittest.TestCase):
28+ def test_selected_root_ignores_stale_sibling(self):
29+ with tempfile.TemporaryDirectory(prefix="gym_ops_config_") as temp:
30+ bin_dir = Path(temp) / "ascend950" / "bin"
31+ selected = bin_dir / "selected_op"
32+ selected.mkdir(parents=True)
33+ (selected / "kernel.json").write_text("{}\n")
34+ (bin_dir / "stale_empty_op").mkdir()
35+ 
36+ # A filtered build only validates its own operator directory.
37+ ops_config.check_single_op_is_void(str(selected))
38+ 
39+ # An empty selected directory, or the whole unfiltered tree, still fails.
40+ with self.assertRaisesRegex(RuntimeError, "not any obj compile success"):
41+ ops_config.check_single_op_is_void(str(bin_dir / "stale_empty_op"))
42+ with self.assertRaisesRegex(RuntimeError, "not any obj compile success"):
43+ ops_config.check_single_op_is_void(str(bin_dir))
44+ 
45+ 
46+if __name__ == "__main__":
47+ unittest.main()
@@ -0,0 +1,210 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+"""Release scope checks without compiling kernels or requiring an NPU."""
10+import importlib.util
11+from pathlib import Path
12+import shutil
13+import subprocess
14+import sys
15+import tempfile
16+import time
17+from types import SimpleNamespace
18+import unittest
19+ 
20+ROOT = Path(__file__).resolve().parents[2]
21+SCRIPT = ROOT / "cmake/scripts/select_run_ops.py"
22+spec = importlib.util.spec_from_file_location("gym_run_scope", SCRIPT)
23+scope = importlib.util.module_from_spec(spec)
24+spec.loader.exec_module(scope)
25+ 
26+# Importing the CLI does not build or initialize a device.
27+sys.path.insert(0, str(ROOT))
28+from build_ci import BuildCtrl
29+ 
30+ 
31+class RunBuildScopeTest(unittest.TestCase):
32+ def setUp(self):
33+ self.temp = tempfile.TemporaryDirectory(prefix="gym_run_scope_")
34+ self.addCleanup(self.temp.cleanup)
35+ self.root = Path(self.temp.name) / "repo"
36+ for name in ("example_op", "mega_mhc", "unlisted_op"):
37+ op = self.root / "ops/pro/experimental" / name
38+ (op / "op_host").mkdir(parents=True)
39+ (op / "tests").mkdir()
40+ (op / "CMakeLists.txt").write_text("# binary operator fixture\n")
41+ self.manifest = self.root / "ops/pro/build_ops.yaml"
42+ self.manifest.write_text("- experimental/example_op\n- experimental/mega_mhc\n")
43+ script_dir = self.root / "cmake/scripts"
44+ script_dir.mkdir(parents=True)
45+ shutil.copy2(SCRIPT, script_dir / SCRIPT.name)
46+ 
47+ def test_all_only_includes_uncommented_entries(self):
48+ self.assertEqual(scope.select_run_ops(self.root), ["example_op", "mega_mhc"])
49+ self.manifest.write_text("- experimental/example_op\n# - experimental/mega_mhc\n")
50+ self.assertEqual(scope.select_run_ops(self.root, "all"), ["example_op"])
51+ 
52+ def test_explicit_list_bypasses_manifest(self):
53+ self.manifest.unlink()
54+ self.assertEqual(scope.select_run_ops(self.root, "mega_mhc,example_op,mega_mhc"),
55+ ["example_op", "mega_mhc"])
56+ self.assertEqual(scope.select_run_ops(self.root, "mega_mhc;example_op"),
57+ ["example_op", "mega_mhc"])
58+ 
59+ def test_missing_and_empty_scope_fail_closed(self):
60+ self.manifest.unlink()
61+ with self.assertRaises(ValueError):
62+ scope.select_run_ops(self.root)
63+ for text in ("", "# - experimental/example_op\n# - experimental/mega_mhc\n"):
64+ with self.subTest(text=text):
65+ self.manifest.write_text(text)
66+ with self.assertRaisesRegex(ValueError, "no operators listed"):
67+ scope.select_run_ops(self.root)
68+ 
69+ def test_comments_blank_lines_and_duplicates(self):
70+ self.manifest.write_text("# release scope\n\n- experimental/example_op # included\n"
71+ "# - experimental/mega_mhc\n- experimental/example_op\n")
72+ self.assertEqual(scope.select_run_ops(self.root), ["example_op"])
73+ 
74+ def test_malformed_manifest_is_rejected(self):
75+ for text in ("experimental/example_op\n",
76+ "operators: [experimental/example_op]\n",
77+ "- [broken\n", "- true\n", "- 123\n", "- null\n", "- ''\n",
78+ "- /experimental/example_op\n"):
79+ with self.subTest(text=text):
80+ self.manifest.write_text(text)
81+ with self.assertRaises(ValueError):
82+ scope.select_run_ops(self.root)
83+ 
84+ def test_unknown_and_unready_operators_are_rejected(self):
85+ for name in ("typo_op", "../example_op"):
86+ with self.subTest(name=name):
87+ self.manifest.write_text(f"- {name}\n")
88+ with self.assertRaises(ValueError):
89+ scope.select_run_ops(self.root)
90+ (self.root / "ops/pro/experimental/mega_mhc/CMakeLists.txt").unlink()
91+ with self.assertRaisesRegex(ValueError, "no binary build directory"):
92+ scope.select_run_ops(self.root, "mega_mhc")
93+ 
94+ def test_paths_disambiguate_all_but_explicit_names_must_be_unique(self):
95+ duplicate = self.root / "ops/tensor/experimental/mega_mhc"
96+ (duplicate / "op_host").mkdir(parents=True)
97+ (duplicate / "CMakeLists.txt").write_text("# ambiguous fixture\n")
98+ self.assertEqual(scope.select_run_ops(self.root), ["example_op", "mega_mhc"])
99+ with self.assertRaisesRegex(ValueError, "ambiguous"):
100+ scope.select_run_ops(self.root, "mega_mhc")
101+ 
102+ def test_stest_uses_run_manifest_and_keeps_whl_scope(self):
103+ ctrl = BuildCtrl.__new__(BuildCtrl)
104+ ctrl.src_root = self.root
105+ ctrl.feature = SimpleNamespace(ops="ALL", pkg_type_run=True)
106+ self.manifest.write_text("# - experimental/example_op\n- experimental/mega_mhc\n")
107+ self.assertEqual([p.name for p in ctrl.selected_op_dirs()], ["mega_mhc"])
108+ ctrl.feature.ops = "example_op"
109+ self.assertEqual([p.name for p in ctrl.selected_op_dirs()], ["example_op"])
110+ ctrl.feature = SimpleNamespace(ops="ALL", pkg_type_run=False)
111+ self.assertEqual([p.name for p in ctrl.selected_op_dirs()],
112+ ["example_op", "mega_mhc", "unlisted_op"])
113+ 
114+ def test_default_bindings_fall_back_to_aclnn_when_unsupported(self):
115+ ctrl = BuildCtrl.__new__(BuildCtrl)
116+ ctrl.src_root = self.root
117+ ctrl.feature = SimpleNamespace(ops="example_op", pkg_type_run=True,
118+ torch_bindings=True, torch_bindings_explicit=False)
119+ ctrl.resolve_torch_bindings()
120+ self.assertFalse(ctrl.feature.torch_bindings)
121+ 
122+ binding = self.root / "ops/pro/experimental/example_op/torch_extension"
123+ binding.mkdir()
124+ (binding / "CMakeLists.txt").write_text("# binding fixture\n")
125+ ctrl.feature.torch_bindings = True
126+ ctrl.resolve_torch_bindings()
127+ self.assertTrue(ctrl.feature.torch_bindings)
128+ 
129+ # An explicit --torch-bindings request is still validated by CMake.
130+ ctrl.feature = SimpleNamespace(ops="mega_mhc", pkg_type_run=True,
131+ torch_bindings=True, torch_bindings_explicit=True)
132+ ctrl.resolve_torch_bindings()
133+ self.assertTrue(ctrl.feature.torch_bindings)
134+ 
135+ def test_cmake_ignores_unselected_orphans(self):
136+ cmake = BuildCtrl.which_cmake()
137+ if not cmake:
138+ self.skipTest("CMake is unavailable")
139+ # Sort the selected operator last so the previous discovery loop leaves
140+ # _op_dir pointing at it. The orphan check must use its own directory.
141+ selected = self.root / "ops/pro/experimental/z_selected"
142+ (selected / "op_host").mkdir(parents=True)
143+ (selected / "CMakeLists.txt").write_text("# selected operator\n")
144+ orphan = self.root / "ops/pro/experimental/a_unlisted"
145+ (orphan / "op_host").mkdir(parents=True)
146+ (orphan / "op_host/CMakeLists.txt").write_text("# incomplete operator\n")
147+ self.manifest.write_text("- experimental/z_selected\n")
148+ (self.root / "CMakeLists.txt").write_text(f'''
149+cmake_minimum_required(VERSION 3.18)
150+project(scope_check NONE)
151+set(Python3_EXECUTABLE "{sys.executable}")
152+include("{ROOT / 'cmake/func.cmake'}")
153+gym_op_discovery(OP_LIST OP_DIR_LIST)
154+file(WRITE "${{CMAKE_BINARY_DIR}}/selected.txt" "${{OP_LIST}}")
155+''')
156+ build = Path(self.temp.name) / "orphan_build"
157+ for requested in ("ALL", "z_selected"):
158+ with self.subTest(requested=requested):
159+ result = subprocess.run(
160+ [str(cmake), "-S", str(self.root), "-B", str(build),
161+ f"-DASCEND_OP_NAME={requested}"], capture_output=True, text=True)
162+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
163+ self.assertEqual((build / "selected.txt").read_text(), "z_selected")
164+ 
165+ # Ignoring an unselected directory must not allow publishing it later.
166+ self.manifest.write_text("- experimental/a_unlisted\n")
167+ for requested in ("ALL", "a_unlisted"):
168+ with self.subTest(requested=requested):
169+ result = subprocess.run(
170+ [str(cmake), "-S", str(self.root), "-B", str(build),
171+ f"-DASCEND_OP_NAME={requested}"], capture_output=True, text=True)
172+ self.assertNotEqual(result.returncode, 0)
173+ self.assertIn("no binary build directory",
174+ " ".join((result.stdout + result.stderr).split()))
175+ 
176+ def test_cmake_tracks_manifest_changes(self):
177+ cmake = BuildCtrl.which_cmake()
178+ if not cmake:
179+ self.skipTest("CMake is unavailable")
180+ (self.root / "CMakeLists.txt").write_text(f'''
181+cmake_minimum_required(VERSION 3.18)
182+project(scope_check NONE)
183+set(Python3_EXECUTABLE "{sys.executable}")
184+include("{ROOT / 'cmake/func.cmake'}")
185+gym_op_discovery(OP_LIST OP_DIR_LIST)
186+file(WRITE "${{CMAKE_BINARY_DIR}}/selected.txt" "${{OP_LIST}}")
187+''')
188+ build = Path(self.temp.name) / "build"
189+ subprocess.run([str(cmake), "-S", str(self.root), "-B", str(build)],
190+ check=True, capture_output=True, text=True)
191+ self.assertEqual((build / "selected.txt").read_text(), "example_op;mega_mhc")
192+ # CMake's Makefile timestamp comparison may have one-second resolution.
193+ time.sleep(1.1)
194+ self.manifest.write_text("- experimental/example_op\n# - experimental/mega_mhc\n")
195+ subprocess.run([str(cmake), "--build", str(build)],
196+ check=True, capture_output=True, text=True)
197+ self.assertEqual((build / "selected.txt").read_text(), "example_op")
198+ time.sleep(1.1)
199+ self.manifest.write_text("# - experimental/example_op\n# - experimental/mega_mhc\n")
200+ result = subprocess.run([str(cmake), "--build", str(build)],
201+ capture_output=True, text=True)
202+ self.assertNotEqual(result.returncode, 0)
203+ self.assertIn("no operators listed", " ".join((result.stdout + result.stderr).split()))
204+ subprocess.run([str(cmake), "-S", str(self.root), "-B", str(build),
205+ "-DASCEND_OP_NAME=mega_mhc"], check=True, capture_output=True, text=True)
206+ self.assertEqual((build / "selected.txt").read_text(), "mega_mhc")
207+ 
208+ 
209+if __name__ == "__main__":
210+ unittest.main()
@@ -0,0 +1,165 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+"""Exercise the run installer in temporary CANN and custom directories."""
10+import os
11+from pathlib import Path
12+import shutil
13+import subprocess
14+import sys
15+import tempfile
16+import unittest
17+ 
18+ROOT = Path(__file__).resolve().parents[2]
19+ 
20+ 
21+class RunInstallTest(unittest.TestCase):
22+ def setUp(self):
23+ self.temp = tempfile.TemporaryDirectory(prefix="gym_run_install_")
24+ self.addCleanup(self.temp.cleanup)
25+ self.root = Path(self.temp.name)
26+ self.cann = self.root / "cann"
27+ self.opp = self.cann / "opp"
28+ self.opp.mkdir(parents=True)
29+ (self.cann / "set_env.sh").write_text("# fake CANN environment\n")
30+ self.site = self.cann / "python/site-packages"
31+ self.site.mkdir(parents=True)
32+ self.public = self.site / "pypto_gym"
33+ self.vendor = self.opp / "vendors/pypto_gym"
34+ self.payload = self.root / "payload"
35+ self.scripts = self.payload / "share/info/pypto_gym/scripts"
36+ shutil.copytree(ROOT / "scripts/package/pypto_gym/scripts", self.scripts)
37+ os.chmod(self.scripts / "install.sh", 0o755)
38+ self.binding = self.payload / "packages/vendors/pypto_gym/python/pypto_gym"
39+ self.binding.mkdir(parents=True)
40+ (self.binding / "__init__.py").write_text('VALUE = "installed"\n')
41+ (self.binding / "_loader.py").write_text("# loader fixture\n")
42+ (self.binding / "operators.json").write_text('["example_op"]\n')
43+ (self.binding / "_native").mkdir()
44+ (self.binding / "_frontends").mkdir()
45+ self.env = dict(os.environ, ASCEND_HOME_PATH=str(self.cann))
46+ 
47+ def run_installer(self, *args, success=True):
48+ result = subprocess.run(
49+ [str(self.scripts / "install.sh"), "--fixture.run",
50+ "--" + str(self.root), *args], env=self.env,
51+ capture_output=True, text=True)
52+ if success:
53+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
54+ else:
55+ self.assertNotEqual(result.returncode, 0)
56+ return result
57+ 
58+ def test_standard_cann_import_without_vendor_pythonpath(self):
59+ self.run_installer()
60+ for name in ("__init__.py", "_loader.py", "_native", "_frontends", "operators.json"):
61+ link = self.public / name
62+ self.assertTrue(link.is_symlink(), link)
63+ self.assertFalse(Path(os.readlink(link)).is_absolute())
64+ self.assertEqual(link.resolve(), (self.vendor / "python/pypto_gym" / name).resolve())
65+ result = subprocess.run(
66+ [sys.executable, "-c", "import pypto_gym; print(pypto_gym.VALUE)"],
67+ cwd=self.root, env=dict(self.env, PYTHONPATH=str(self.site)),
68+ check=True, capture_output=True, text=True)
69+ self.assertEqual(result.stdout.strip(), "installed")
70+ self.run_installer("--uninstall")
71+ self.assertFalse(self.public.exists())
72+ self.assertFalse(self.vendor.exists())
73+ 
74+ def test_custom_install_does_not_publish_into_cann(self):
75+ custom = self.root / "custom"
76+ custom.mkdir()
77+ self.run_installer(f"--install-path={custom}")
78+ self.assertFalse(self.public.exists())
79+ vendor = custom / "vendors/pypto_gym"
80+ self.assertTrue((vendor / "python/pypto_gym/operators.json").is_file())
81+ self.assertIn(str(vendor / "python"), (vendor / "bin/set_env.bash").read_text())
82+ self.run_installer("--uninstall", f"--install-path={custom}")
83+ self.assertFalse(vendor.exists())
84+ 
85+ def test_unwritable_cann_degrades_to_vendor_only(self):
86+ # Simulate a non-root install into a root-owned CANN: the vendor tree is
87+ # writable, but python/site-packages is not. Installation must still
88+ # succeed and point the user at the vendor set_env.bash.
89+ setpriv = shutil.which("setpriv")
90+ if os.geteuid() != 0 or not setpriv:
91+ self.skipTest("requires root and setpriv to drop privileges")
92+ os.chmod(self.root, 0o755)
93+ os.chmod(self.cann, 0o755)
94+ os.chmod(self.opp, 0o777)
95+ os.chmod(self.site, 0o555)
96+ self.addCleanup(os.chmod, self.site, 0o755)
97+ result = subprocess.run(
98+ [setpriv, "--reuid=65534", "--regid=65534", "--clear-groups",
99+ str(self.scripts / "install.sh"), "--fixture.run",
100+ "--" + str(self.root)], env=self.env, capture_output=True, text=True)
101+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
102+ self.assertFalse(self.public.exists())
103+ self.assertTrue((self.vendor / "python/pypto_gym/operators.json").is_file())
104+ self.assertIn("not registered", result.stdout + result.stderr)
105+ self.assertIn(str(self.vendor / "python"), (self.vendor / "bin/set_env.bash").read_text())
106+ 
107+ def test_public_registration_is_readable_with_restrictive_umask(self):
108+ previous_umask = os.umask(0o077)
109+ try:
110+ result = subprocess.run(
111+ [str(self.scripts / "install.sh"), "--fixture.run", "--" + str(self.root),
112+ "--install-for-all"], env=self.env, capture_output=True, text=True)
113+ finally:
114+ os.umask(previous_umask)
115+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
116+ self.assertEqual(self.public.stat().st_mode & 0o777, 0o755)
117+ self.run_installer("--uninstall")
118+ 
119+ def test_existing_kernel_namespace_survives_upgrade_and_standalone_uninstall(self):
120+ ops = self.public / "ops"
121+ ops.mkdir(parents=True)
122+ marker = ops / "wheel.py"
123+ marker.write_text("# existing kernel wheel\n")
124+ (self.opp / "vendors").mkdir()
125+ (self.opp / "vendors/config.ini").write_text("load_priority=other_vendor\n")
126+ self.run_installer()
127+ self.run_installer() # Upgrade removes and recreates only owned links.
128+ result = subprocess.run(
129+ [str(self.vendor / "scripts/uninstall.sh")],
130+ env=self.env, capture_output=True, text=True)
131+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
132+ self.assertTrue(marker.is_file())
133+ self.assertFalse((self.public / "__init__.py").is_symlink())
134+ self.assertFalse(self.vendor.exists())
135+ self.assertEqual((self.opp / "vendors/config.ini").read_text(), "load_priority=other_vendor\n")
136+ 
137+ def test_unrelated_python_package_is_not_overwritten(self):
138+ self.public.mkdir()
139+ existing = self.public / "__init__.py"
140+ existing.write_text("# another package\n")
141+ self.vendor.mkdir(parents=True)
142+ old = self.vendor / "old-version"
143+ old.write_text("keep\n")
144+ result = self.run_installer(success=False)
145+ self.assertIn("already owned by another package", result.stderr)
146+ self.assertEqual(existing.read_text(), "# another package\n")
147+ self.assertEqual(old.read_text(), "keep\n")
148+ 
149+ def test_upgrade_without_bindings_removes_old_registration(self):
150+ self.run_installer()
151+ shutil.rmtree(self.binding)
152+ self.run_installer()
153+ self.assertFalse(self.public.exists())
154+ self.assertTrue(self.vendor.is_dir())
155+ 
156+ def test_no_bindings_preserves_unowned_empty_namespace(self):
157+ self.public.mkdir()
158+ shutil.rmtree(self.binding)
159+ self.run_installer()
160+ self.run_installer("--uninstall")
161+ self.assertTrue(self.public.is_dir())
162+ 
163+ 
164+if __name__ == "__main__":
165+ unittest.main()
@@ -0,0 +1,76 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+"""Verify the installed pypto_gym namespace imports without torch."""
10+import json
11+from pathlib import Path
12+import shutil
13+import subprocess
14+import sys
15+import tempfile
16+import unittest
17+ 
18+ROOT = Path(__file__).resolve().parents[2]
19+PACKAGE = ROOT / "torch_extension" / "pypto_gym"
20+ 
21+ 
22+class TorchBindingLazyImportTest(unittest.TestCase):
23+ def setUp(self):
24+ self.temp = tempfile.TemporaryDirectory(prefix="gym_lazy_binding_")
25+ self.addCleanup(self.temp.cleanup)
26+ self.site = Path(self.temp.name) / "site-packages"
27+ self.pkg = self.site / "pypto_gym"
28+ self.pkg.mkdir(parents=True)
29+ for name in ("__init__.py", "_loader.py"):
30+ shutil.copy2(PACKAGE / name, self.pkg / name)
31+ (self.pkg / "operators.json").write_text(json.dumps(["example_op"]) + "\n")
32+ frontends = self.pkg / "_frontends"
33+ frontends.mkdir()
34+ (frontends / "example_op.py").write_text("def example_op(*args, **kwargs):\n"
35+ " return 'loaded'\n")
36+ 
37+ def test_import_without_torch_is_allowed(self):
38+ result = self._run(
39+ "import sys\n"
40+ "class Block:\n"
41+ " def find_spec(self, name, path=None, target=None):\n"
42+ " if name == 'torch' or name.startswith('torch.'):\n"
43+ " raise ImportError('torch is blocked for this test')\n"
44+ " return None\n"
45+ "sys.meta_path.insert(0, Block())\n"
46+ "import pypto_gym\n"
47+ "print('IMPORT_OK', pypto_gym.__all__)\n")
48+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
49+ self.assertIn("IMPORT_OK", result.stdout)
50+ self.assertIn("example_op", result.stdout)
51+ 
52+ def test_lazy_access_reports_missing_torch(self):
53+ result = self._run(
54+ "import sys\n"
55+ "class Block:\n"
56+ " def find_spec(self, name, path=None, target=None):\n"
57+ " if name == 'torch' or name.startswith('torch.'):\n"
58+ " raise ImportError('torch is blocked for this test')\n"
59+ " return None\n"
60+ "sys.meta_path.insert(0, Block())\n"
61+ "import pypto_gym\n"
62+ "try:\n"
63+ " pypto_gym.example_op\n"
64+ "except ImportError as error:\n"
65+ " print('LAZY_IMPORT_ERROR', 'blocked' in str(error))\n")
66+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
67+ self.assertIn("LAZY_IMPORT_ERROR True", result.stdout)
68+ 
69+ def _run(self, body):
70+ return subprocess.run(
71+ [sys.executable, "-c", body], cwd=self.temp.name,
72+ env={"PYTHONPATH": str(self.site)},
73+ capture_output=True, text=True)
74+ 
75+if __name__ == "__main__":
76+ unittest.main()
@@ -0,0 +1,62 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# Licensed under the CANN Open Software License Agreement Version 2.0.
3+ 
4+find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
5+execute_process(
6+ COMMAND ${Python3_EXECUTABLE} -c "import pathlib, torch_npu; print(pathlib.Path(torch_npu.__file__).parent)"
7+ OUTPUT_VARIABLE GYM_TORCH_NPU_ROOT OUTPUT_STRIP_TRAILING_WHITESPACE
8+ RESULT_VARIABLE _torch_npu_rc ERROR_QUIET)
9+if(NOT _torch_npu_rc EQUAL 0)
10+ message(FATAL_ERROR "ENABLE_TORCH_BINDINGS requires torch_npu in ${Python3_EXECUTABLE}")
11+endif()
12+find_library(GYM_TORCH_NPU_LIB torch_npu PATHS "${GYM_TORCH_NPU_ROOT}/lib" NO_DEFAULT_PATH REQUIRED)
13+find_library(GYM_ASCENDCL_LIB ascendcl PATHS "${ASCEND_CANN_PACKAGE_PATH}/lib64" NO_DEFAULT_PATH REQUIRED)
14+ 
15+add_library(gym_torch_common INTERFACE)
16+target_include_directories(gym_torch_common INTERFACE
17+ ${TORCH_INCLUDE_DIRS}
18+ "${CMAKE_CURRENT_SOURCE_DIR}/include"
19+ ${Python3_INCLUDE_DIRS}
20+ "${GYM_TORCH_NPU_ROOT}/include"
21+ "${ASCEND_CANN_PACKAGE_PATH}/include")
22+target_link_libraries(gym_torch_common INTERFACE
23+ ${TORCH_LIBRARIES} ${TORCH_PYTHON_LIB} ${GYM_TORCH_NPU_LIB} ${GYM_ASCENDCL_LIB} dl)
24+separate_arguments(_gym_torch_flags NATIVE_COMMAND "${TORCH_CXX_FLAGS}")
25+target_compile_options(gym_torch_common INTERFACE ${_gym_torch_flags})
26+target_compile_features(gym_torch_common INTERFACE cxx_std_17)
27+ 
28+install(DIRECTORY pypto_gym/
29+ DESTINATION packages/vendors/${VENDOR_NAME}/python/pypto_gym
30+ COMPONENT ${VENDOR_NAME} PATTERN "__pycache__" EXCLUDE)
31+ 
32+# Called from ops/<paradigm>/<network>/<op>/torch_extension/CMakeLists.txt.
33+function(gym_add_torch_binding op_name)
34+ add_library(torch_binding_${op_name} SHARED "${op_name}.cpp")
35+ target_link_libraries(torch_binding_${op_name} PRIVATE gym_torch_common)
36+ set_target_properties(torch_binding_${op_name} PROPERTIES
37+ OUTPUT_NAME pypto_gym_${op_name}
38+ LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/torch_extension"
39+ INSTALL_RPATH "$ORIGIN/../../../op_api/lib"
40+ INSTALL_RPATH_USE_LINK_PATH FALSE)
41+ install(TARGETS torch_binding_${op_name}
42+ LIBRARY DESTINATION packages/vendors/${VENDOR_NAME}/python/pypto_gym/_native
43+ COMPONENT ${VENDOR_NAME})
44+ install(FILES "${op_name}.py"
45+ DESTINATION packages/vendors/${VENDOR_NAME}/python/pypto_gym/_frontends
46+ COMPONENT ${VENDOR_NAME})
47+ set_property(GLOBAL APPEND PROPERTY GYM_TORCH_OPS ${op_name})
48+endfunction()
49+ 
50+function(gym_finalize_torch_bindings)
51+ get_property(_ops GLOBAL PROPERTY GYM_TORCH_OPS)
52+ if(NOT _ops)
53+ message(FATAL_ERROR "None of the selected operators provide a Torch binding")
54+ endif()
55+ list(REMOVE_DUPLICATES _ops)
56+ list(JOIN _ops "\", \"" _ops_json)
57+ file(WRITE "${CMAKE_BINARY_DIR}/torch_extension/operators.json" "[\"${_ops_json}\"]\n")
58+ install(FILES "${CMAKE_BINARY_DIR}/torch_extension/operators.json"
59+ DESTINATION packages/vendors/${VENDOR_NAME}/python/pypto_gym
60+ COMPONENT ${VENDOR_NAME})
61+ message(STATUS "Precompiled Torch bindings: ${_ops}")
62+endfunction()
@@ -0,0 +1,347 @@
1+# PyPTO-Gym Torch 绑定
2+ 
3+Torch 绑定使用已安装的 ACLNN 算子库,在当前 NPU stream 上执行预编译 kernel。
4+C++ 绑定也在构建期编译并随 `.run` 交付;运行时加载 `.so`,无需编译器或
5+PyPTO Python 包。当前已接入 `mega_mhc`。
6+ 
7+## 构建和安装
8+ 
9+构建环境需要 CANN、PyPTO-pro、torch、torch_npu 和 PyYAML(读取发布清单)。执行:
10+ 
11+```bash
12+python3 build_ci.py --pkg-type run --ops mega_mhc --soc ascend950
13+bash build_out/run/ascend950/cann-950-pypto_gym_*.run --install-path="$ASCEND_HOME_PATH/opp"
14+```
15+ 
16+`.run` 默认附带预编译 Torch 绑定,对应 `-DENABLE_TORCH_BINDINGS=ON`,
17+无需额外传入 `--torch-bindings`。仅需 ACLNN 接口时,使用 `--no-torch-bindings`
18+(手工 CMake 使用 `-DENABLE_TORCH_BINDINGS=OFF`)。`whl` 构建不启用此绑定。
19+部署环境需要与构建环境兼容的 Python、torch、torch_npu 和 CANN。
20+在已加载目标 CANN 基础环境的终端中,安装到其 `opp` 后即可直接导入,
21+无需额外 source vendor 的 `set_env.bash`。安装器在 CANN 的 `python/site-packages`
22+中登记指向 vendor 私有文件的相对链接;绑定通过相对运行时库路径加载同一 vendor 的 ACLNN 库。
23+升级、卸载只维护本包创建的链接,保留已有 kernel wheel 的 `ops` 目录;
24+若入口已由其他 Python 包占用,安装会报错而不覆盖。
25+ 
26+安装到非 CANN 的独立目录时,仍可 source `<opp>/vendors/pypto_gym/bin/set_env.bash`
27+配置该自定义位置的搜索路径。新终端需要加载 CANN 基础环境。
28+ 
29+```python
30+import torch
31+import pypto_gym
32+ 
33+# 九个输入 tensor 均位于同一 NPU;形状和类型见算子 README。
34+outputs = pypto_gym.mega_mhc(*inputs)
35+# 直接通过 Torch dispatcher 调用前,先显式加载绑定;batch=0 表示自动配置。
36+pypto_gym.load()
37+outputs = torch.ops.pypto_gym.mega_mhc(*inputs, batch=0)
38+```
39+ 
40+`import pypto_gym` 是惰性的:不会导入 torch/torch_npu,也不会加载绑定库。访问
41+`pypto_gym.mega_mhc` 会在首次调用时加载;直接使用 `torch.ops.pypto_gym.*` 前需先
42+调用 `pypto_gym.load()`(或先访问任一 `pypto_gym.<op>`)。因此缺少 torch 或绑定
43+ABI 不兼容时,`import pypto_gym` 仍然成功。
44+ 
45+`pypto_gym.mega_mhc` 支持 `batch=None/16` 和六个运行时标量,五个输出由绑定
46+内部申请并以返回值形式返回。功能入口注册了 `PrivateUse1` 和 `Meta`,支持 FakeTensor
47+和符号 token 维度的输出推导。当前提供 forward 计算,不提供 autograd backward。
48+ 
49+## 测试
50+ 
51+```bash
52+# 构建、隔离安装到 build_out,并通过正式 Torch 入口运行测试。
53+python3 build_ci.py --pkg-type run --ops mega_mhc --stest
54+# 已安装到当前 CANN 时,无需额外 source vendor 脚本:
55+pytest ops/pro/deepseek_v4_1/mega_mhc/tests -q
56+```
57+ 
58+`mega_mhc` 的 24 项完整算子用例中,12 项直接调用 `pypto_gym.mega_mhc`,
59+12 项直接调用 `torch.ops.pypto_gym.mega_mhc`,每项只执行一次算子,输出由绑定内部申请。
60+测试校验五输出数值精度、只读输入和输入内存 guard;入口不受 `--mode` 参数控制。
61+用例清单见算子 README。
62+ 
63+另有一项存储格式边界用例,验证 NZ 输入会在进入异步队列前被拒绝。
64+绑定读取真实存储格式元数据,不做隐式格式转换或 NPU 同步。
65+ 
66+## 多算子构建到同一个包
67+ 
68+`.run` 的 `ALL`(包括省略 `--ops`)由
69+[ops/pro/build_ops.yaml](../ops/pro/build_ops.yaml) 控制,使用 YAML 列表,路径相对于 `ops/pro`:
70+ 
71+```yaml
72+- deepseek_v4_1/mega_mhc
73+```
74+ 
75+当前清单仅列出 `mega_mhc`。文件中列出的路径参与构建,未列出的路径不参与。
76+空行、以 `#` 开头的注释及行尾 `#` 注释会被忽略。
77+新增算子需要把完整相对路径加入清单;不想构建某个算子时,注释掉对应行即可。
78+例如,接入新算子 `example_op` 后可加入第二行,再按需注释:
79+ 
80+```yaml
81+- deepseek_v4_1/mega_mhc
82+# - experimental/example_op
83+```
84+ 
85+上述清单的 `ALL` 只构建 `deepseek_v4_1/mega_mhc`;取消第二行的注释后包含
86+两个算子。`example_op` 是占位名称,启用前需完成实际算子的二进制接入。
87+ 
88+列出的目录需满足二进制构建约定:位于规定的目录深度内,并同时具备算子级
89+`CMakeLists.txt` 和 `op_host/`。路径按完整目录匹配,实际算子名取目录末级名称,
90+同一个包中的算子名必须唯一。清单需至少列出一个有效目录;文件缺失、路径错误或
91+全部被注释时构建报错。
92+ 
93+显式 `--ops mega_mhc,example_op` 仍按算子目录名选择,绕过此清单,
94+也可显式选择未列入清单的算子。显式选择的候选范围包括 `ops/pro/` 和
95+`ops/tensor/` 下已接入二进制构建的算子;清单的相对路径基准固定为 `ops/pro/`。
96+`whl` 的 `ALL` 保持原有发现范围,不使用这份 `.run` 发布清单。
97+ 
98+CMake 构建和 `--stest` 共用同一份解析逻辑;CMake 会跟踪清单变化并重新配置。
99+`operators.json` 是构建生成的 Torch 绑定名单,不作为发布范围的配置入口。
100+ 
101+`--ops` 支持逗号分隔的算子目录名。同一 SoC、同一次构建选择的所有算子会进入
102+同一个 `.run` 包。例如,完成 `example_op` 接入后,与 `mega_mhc` 一起交付:
103+ 
104+```bash
105+python3 build_ci.py --pkg-type run --soc ascend950 \
106+ --ops mega_mhc,example_op
107+```
108+ 
109+命令中的逗号两侧不要加空格,整个名单作为一个参数传入。名单填写算子目录名,
110+例如 `mega_mhc`,而不是 C++ 类型名 `MegaMhc` 或 ACLNN 函数名。
111+ 
112+| 选择方式 | 构建范围 |
113+| --------------------------------- | ------------------------------------------------------- |
114+| `--ops mega_mhc` | 单个算子 |
115+| `--ops mega_mhc,example_op` | 指定的多个算子,共用一个包 |
116+| `--ops ALL`,或省略 `--ops` | `.run` 仅构建 `ops/pro/build_ops.yaml` 中列出的目录 |
117+ 
118+`.run` 默认附带预编译 Torch 绑定,`--no-torch-bindings` 可显式关闭。
119+算子是否进入包和是否提供 Torch 入口是两件事:
120+ 
121+- 所选算子的 host、ACLNN 和 kernel 产物一起打包。
122+- 其中已接入 `torch_extension/` 的算子,额外打包各自的绑定 `.so` 和 Python 前端。
123+- 当前 `mega_mhc` 已接入绑定,提供 `pypto_gym.mega_mhc` 和对应的 `torch.ops` 入口。
124+ 新增算子仍需完成绑定接入,构建不会从 kernel 源码自动生成 Torch 参数接口。
125+- `run` 默认尝试启用绑定;若所选算子都没有接入绑定,会自动降级为 ACLNN-only 包并打印
126+ WARNING,原有 ACLNN 调用/测试方式不受影响。显式传 `--torch-bindings` 时,所选算子中
127+ 至少要有一个提供绑定,否则 CMake 会报错。也可用 `--no-torch-bindings` 强制 ACLNN-only。
128+ 
129+输出目录为 `build_out/run/ascend950/`。包名按 SoC、vendor、版本和架构生成,
130+不包含算子名单。例如,x86_64 环境下生成
131+`cann-950-pypto_gym_9.2.0_linux-x86_64.run`,它可以同时包含多个算子。
132+要交付一个包含多个算子的包,应在一次命令中指定完整名单;分次构建单算子不会自动
133+把前后两次产物合并,且可能使用相同的包名。
134+ 
135+按发布清单构建并验证当前列出的算子:
136+ 
137+```bash
138+python3 build_ci.py --pkg-type run --soc ascend950 \
139+ --ops ALL --stest --jobs 8
140+```
141+ 
142+`--stest` 可用于构建后验证:构建脚本按 `operators.json` 将已有绑定的算子交给
143+Torch 测试,将其余算子交给 ACLNN 测试桥;后者需要相应的测试桥和用例。
144+`mega_mhc` 的用例已直接固定使用两个正式接口,不再依赖测试入口分发函数。
145+ 
146+## 新算子接入
147+ 
148+本章使用 `outputs = torch.ops.pypto_gym.example_op(*inputs)` 的普通函数接口,
149+输出由 C++ 绑定内部分配。
150+ 
151+以下以 `example_op` 为占位名称;实际接入时替换为真实算子目录名。
152+可对照完整实现 [mega_mhc/torch_extension](../ops/pro/deepseek_v4_1/mega_mhc/torch_extension/)。
153+公共构建逻辑位于 [CMakeLists.txt](CMakeLists.txt),ACLNN 调用辅助代码位于
154+[include/gym_aclnn.h](include/gym_aclnn.h)。
155+ 
156+### 1. 先具备算子的二进制构建能力
157+ 
158+Torch 绑定建立在可独立交付的 ACLNN 算子之上。算子需要先接入仓库的 host、kernel
159+构建流程,能通过 `--pkg-type run --ops example_op --no-torch-bindings` 生成
160+ACLNN 二进制产物;完成下面的 Torch 接入后,构建时使用默认开启的绑定。
161+算子目录至少应有算子级 `CMakeLists.txt` 和 `op_host/`,以便构建系统发现。
162+host、kernel 的基础接入流程见 [构建指南](../docs/build-guide.md)。
163+ 
164+接入前明确以下接口约定,并在算子 README 中写清楚:
165+ 
166+- 输入和输出的顺序、shape、dtype、layout、设备及连续性要求。
167+- 标量参数的类型、默认值、取值范围,以及空输入的行为。
168+- ACLNN 函数名、完整函数签名、输出分配规则和是否支持预分配输出。
169+- 是否提供反向计算;只有 forward 的算子应明确限制需要梯度的调用。
170+ 
171+Torch schema、C++ 函数、Python 前端与 ACLNN 的参数映射必须保持一致。
172+ACLNN 签名以该算子构建生成的头文件为准,不要只替换其他算子的函数名。
173+ 
174+### 2. 增加目录和 CMake 登记
175+ 
176+在算子目录增加以下三个文件:
177+ 
178+```text
179+ops/pro/experimental/example_op/
180+├── CMakeLists.txt
181+├── op_host/
182+├── op_kernel/
183+├── tests/
184+└── torch_extension/
185+ ├── CMakeLists.txt
186+ ├── example_op.cpp
187+ └── example_op.py
188+```
189+ 
190+`torch_extension/CMakeLists.txt` 内容为:
191+ 
192+```cmake
193+if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD)
194+ gym_add_torch_binding(example_op)
195+endif()
196+```
197+ 
198+算子级 `CMakeLists.txt` 必须派发到这个子目录。若像 `mega_mhc` 一样已自动遍历
199+带 `CMakeLists.txt` 的子目录,无需额外添加;若采用显式派发,则在算子级增加:
200+ 
201+```cmake
202+if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD)
203+ add_subdirectory(torch_extension)
204+endif()
205+```
206+ 
207+两种派发方式选一种,避免重复添加子目录。绑定登记放在
208+`torch_extension/CMakeLists.txt` 中,文件名须与 `gym_add_torch_binding()` 的参数一致。
209+ 
210+公共构建函数会自动完成以下工作:
211+ 
212+1. 创建 `torch_binding_example_op` 共享库目标,并链接公共 Torch、torch_npu、CANN 依赖。
213+2. 生成 `libpypto_gym_example_op.so`,安装到包内的 `_native/`。
214+3. 将 `example_op.py` 安装到 `_frontends/`。
215+4. 把 `example_op` 加入本次构建的全局绑定名单。
216+ 
217+根构建流程在所有所选算子登记完成后,统一生成 `operators.json`。
218+新增算子无需修改公共加载器或手动维护这个 JSON。
219+ 
220+### 3. 实现 C++ Torch 注册和 ACLNN 调用
221+ 
222+`example_op.cpp` 负责将 Torch Tensor 转接到该算子的 ACLNN 接口。
223+可参考 [mega_mhc.cpp](../ops/pro/deepseek_v4_1/mega_mhc/torch_extension/mega_mhc.cpp)。
224+ 
225+下面仅展示一个单输入、单输出算子的注册部分;`ExampleOpNpu` 和 `ExampleOpMeta`
226+须在同一文件中按真实计算和输出规则实现:
227+ 
228+```cpp
229+#include "gym_aclnn.h"
230+#include <ATen/ATen.h>
231+#include <torch/library.h>
232+ 
233+// 具体实现略:NPU 函数执行 ACLNN,Meta 函数只推导输出。
234+at::Tensor ExampleOpNpu(const at::Tensor &x);
235+at::Tensor ExampleOpMeta(const at::Tensor &x);
236+ 
237+TORCH_LIBRARY_FRAGMENT(pypto_gym, m) {
238+ m.def("example_op(Tensor x) -> Tensor");
239+}
240+TORCH_LIBRARY_IMPL(pypto_gym, PrivateUse1, m) {
241+ m.impl("example_op", TORCH_FN(ExampleOpNpu));
242+}
243+TORCH_LIBRARY_IMPL(pypto_gym, Meta, m) {
244+ m.impl("example_op", TORCH_FN(ExampleOpMeta));
245+}
246+```
247+ 
248+同一个包中的所有算子共用 `pypto_gym` 命名空间,因此使用
249+`TORCH_LIBRARY_FRAGMENT` 分别声明各自 schema,避免重复定义命名空间。
250+schema 中的 Tensor、标量、默认值和返回值必须与 C++ 函数签名匹配。
251+ 
252+NPU 实现按以下顺序处理:
253+ 
254+1. 校验输入设备、shape、dtype、连续性、真实存储格式和标量范围,设置正确的 device guard。
255+ ND 算子调用 `gym_torch::CheckNDStorage(tensor, name)`;逻辑连续性不足以判断物理格式。
256+2. 在调用线程分配输出;若支持预分配输出,校验输出规格、真实存储格式和输入输出之间的重叠。
257+ 支持空输入时按算子约定返回正确形状的空输出。
258+3. 用 `gym_torch::Symbol<函数指针类型>()` 解析该算子的
259+ `aclnnExampleOpGetWorkspaceSize` 和 `aclnnExampleOp`;函数指针类型与生成头文件一致。
260+4. 将参与计算的输入、输出 Tensor 列表交给 `gym_torch::Enqueue()`。
261+ 回调接收 Tensor 元数据,通过 `gym_torch::Tensor()` 构造 ACL Tensor 描述符。
262+5. 在回调中调用 `GetWorkspaceSize` 获取 workspace 大小和 executor,检查返回码后,
263+ 调用 `gym_torch::ExecuteOp()` 在当前 NPU stream 执行算子。
264+ 
265+复用公共辅助函数的 stream 记录和 workspace 管理。队列回调只捕获标量等 host 数据,
266+不要捕获 `at::Tensor`,也不要在回调中用 `at::empty` 创建 workspace Tensor;
267+这些操作可能在资源释放时重新进入任务队列。算子正常调用保持异步,数值测试需要时
268+再执行 `torch.npu.synchronize()`。
269+ 
270+`Meta` 实现只根据输入元数据和属性创建输出,不分配 NPU workspace、不执行 ACLNN。
271+若需要动态 shape,应使用符号维度推导接口。
272+ 
273+### 4. 导出 Python 便捷入口
274+ 
275+`example_op.py` 中必须提供与算子同名的可调用函数。对于上面的单输入示例:
276+ 
277+```python
278+import torch
279+ 
280+ 
281+def example_op(x):
282+ return torch.ops.pypto_gym.example_op(x)
283+```
284+ 
285+这里可以补充 Python 参数校验、默认值转换和 `out` 参数展开;C++ 入口仍需保留
286+必要校验,因为用户也可以直接调用 `torch.ops`。Python 前端负责参数处理和转发,
287+计算交给预编译绑定;无需导入 `op_kernel` 或使用运行时扩展编译。
288+ 
289+`import pypto_gym` 只读取绑定清单,不加载绑定库;`pypto_gym.example_op` 在首次
290+访问时按需加载对应 `.so` 并完成 Torch 算子注册。两种入口都可使用:
291+ 
292+```python
293+import torch
294+import pypto_gym
295+ 
296+result = pypto_gym.example_op(x) # 首次访问时加载 example_op 绑定。
297+# 直接调用 Torch 算子前,先显式加载(或先访问 pypto_gym.example_op):
298+pypto_gym.load()
299+result = torch.ops.pypto_gym.example_op(x)
300+```
301+ 
302+### 5. 与已有算子一起构建、安装和验收
303+ 
304+完成上述接入后,在一次构建中选择两个算子:
305+ 
306+```bash
307+# example_op 为占位名称,须先完成实现再执行。
308+python3 build_ci.py --pkg-type run --soc ascend950 \
309+ --ops mega_mhc,example_op --stest
310+```
311+ 
312+`--stest` 要求新算子具备可运行的测试。测试可直接使用上述任一正式接口,每个
313+shape 或边界用例选择一个入口,比较完整输出与 golden。需要看护两种入口时,
314+将不同用例分配给两个入口,避免为了切换入口重复执行相同的算子场景。
315+ 
316+在与构建环境 ABI 兼容、已加载 CANN 基础环境的终端中,将本次生成的 `.run`
317+安装到 `$ASCEND_HOME_PATH/opp`,即可直接导入。vendor 内的文件结构如下
318+(省略其他 host、kernel 产物):
319+ 
320+```text
321+<install-path>/vendors/pypto_gym/
322+├── op_api/lib/libcust_opapi.so
323+└── python/pypto_gym/
324+ ├── __init__.py
325+ ├── _loader.py
326+ ├── operators.json # 包含 mega_mhc 和 example_op
327+ ├── _native/
328+ │ ├── libpypto_gym_mega_mhc.so
329+ │ └── libpypto_gym_example_op.so
330+ └── _frontends/
331+ ├── mega_mhc.py
332+ └── example_op.py
333+```
334+ 
335+标准 CANN 安装还会在 `$ASCEND_HOME_PATH/python/site-packages/pypto_gym/` 中
336+创建 `__init__.py`、`_loader.py`、`_native`、`_frontends`、`operators.json`
337+这五个相对链接,目标均指向上述 vendor 私有目录。
338+ 
339+构建期应看到 `Precompiled Torch bindings:` 列出两个算子;安装后可确认:
340+ 
341+```bash
342+cat "$ASCEND_HOME_PATH/opp/vendors/pypto_gym/python/pypto_gym/operators.json"
343+```
344+ 
345+随后在新 Python 进程中 `import pypto_gym`,使用对应输入调用两个算子的正式接口。
346+仅出现在 `--ops` 中还不足以提供 Torch 入口;还必须完成绑定的 CMake 登记、
347+C++ 注册和同名 Python 前端导出。
@@ -0,0 +1,195 @@
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+#pragma once
11+#include <ATen/ATen.h>
12+#include <acl/acl.h>
13+#include <aclnn/acl_meta.h>
14+#include <c10/core/DeviceGuard.h>
15+#include <cstdlib>
16+#include <dlfcn.h>
17+#include <functional>
18+#include <limits>
19+#include <memory>
20+#include <sstream>
21+#include <string>
22+#include <torch_npu/csrc/core/npu/NPUCachingAllocator.h>
23+#include <torch_npu/csrc/core/npu/NPUFormat.h>
24+#include <torch_npu/csrc/core/npu/NPUStream.h>
25+#include <torch_npu/csrc/framework/OpCommand.h>
26+#include <utility>
27+#include <vector>
28+ 
29+namespace gym_torch {
30+// Keep library handles resident: cached function pointers and in-flight kernels
31+// must remain valid. Search every vendor path, not a colon-joined pathname.
32+inline const std::vector<void *> &Libraries() {
33+ static const auto handles = [] {
34+ std::vector<std::string> names;
35+ for (const auto &env :
36+ {std::make_pair("ASCEND_CUSTOM_OPP_PATH", "/op_api/lib/"),
37+ std::make_pair("LD_LIBRARY_PATH", "/")}) {
38+ const char *value = std::getenv(env.first);
39+ if (!value)
40+ continue;
41+ std::istringstream paths(value);
42+ for (std::string path; std::getline(paths, path, ':');) {
43+ if (!path.empty())
44+ names.push_back(path + env.second + "libcust_opapi.so");
45+ }
46+ }
47+ names.insert(names.end(),
48+ {"libcust_opapi.so", "libopapi.so", "libnnopbase.so"});
49+ std::vector<void *> result;
50+ for (const auto &name : names) {
51+ if (void *handle = dlopen(name.c_str(), RTLD_NOW | RTLD_LOCAL))
52+ result.push_back(handle);
53+ }
54+ return result;
55+ }();
56+ return handles;
57+}
58+ 
59+template <typename T> T Symbol(const char *name) {
60+ for (void *library : Libraries()) {
61+ if (void *symbol = dlsym(library, name))
62+ return reinterpret_cast<T>(symbol);
63+ }
64+ TORCH_CHECK(false, "Cannot resolve ", name,
65+ "; install the matching PyPTO-Gym .run in the active CANN "
66+ "environment (custom locations require ASCEND_CUSTOM_OPP_PATH)");
67+}
68+ 
69+// ACL_FORMAT_ND describes existing storage; it does not convert its layout.
70+// Query host metadata before enqueueing: internal formats such as FRACTAL_NZ
71+// can be logically contiguous while their physical elements are reordered.
72+inline void CheckNDStorage(const at::Tensor &tensor, const char *name) {
73+ TORCH_CHECK(tensor.device().is_privateuseone(), name, " must be an NPU tensor");
74+ const auto format = at_npu::native::get_npu_format(tensor);
75+ TORCH_CHECK(format == ACL_FORMAT_ND, name,
76+ " must use ND storage format; got NPU format ", format);
77+}
78+ 
79+inline aclDataType DataType(at::ScalarType type) {
80+ switch (type) {
81+ case at::kBFloat16:
82+ return ACL_BF16;
83+ case at::kHalf:
84+ return ACL_FLOAT16;
85+ case at::kFloat:
86+ return ACL_FLOAT;
87+ case at::kInt:
88+ return ACL_INT32;
89+ case at::kLong:
90+ return ACL_INT64;
91+ case at::kByte:
92+ return ACL_UINT8;
93+ default:
94+ TORCH_CHECK(false, "Unsupported ACL tensor dtype: ", type);
95+ }
96+}
97+ 
98+struct DestroyTensor {
99+ using Function = aclnnStatus (*)(const aclTensor *);
100+ Function destroy;
101+ void operator()(aclTensor *tensor) const noexcept {
102+ if (tensor)
103+ destroy(tensor);
104+ }
105+};
106+using TensorHandle = std::unique_ptr<aclTensor, DestroyTensor>;
107+ 
108+// Copy metadata on the caller thread. Keeping at::Tensor references in a host
109+// task can make their last release re-enter the same task queue from its
110+// worker.
111+struct TensorInfo {
112+ std::vector<int64_t> sizes;
113+ std::vector<int64_t> strides;
114+ int64_t offset;
115+ int64_t storage_elements;
116+ void *data;
117+ aclDataType type;
118+ explicit TensorInfo(const at::Tensor &tensor)
119+ : sizes(tensor.sizes().vec()), strides(tensor.strides().vec()),
120+ offset(tensor.storage_offset()),
121+ storage_elements(tensor.storage().nbytes() / tensor.element_size()),
122+ data(const_cast<void *>(tensor.storage().data())),
123+ type(DataType(tensor.scalar_type())) {}
124+};
125+ 
126+inline TensorHandle Tensor(const TensorInfo &tensor) {
127+ using Create =
128+ aclTensor *(*)(const int64_t *, uint64_t, aclDataType, const int64_t *,
129+ int64_t, aclFormat, const int64_t *, uint64_t, void *);
130+ static const auto create = Symbol<Create>("aclCreateTensor");
131+ static const auto destroy =
132+ Symbol<DestroyTensor::Function>("aclDestroyTensor");
133+ auto *result = create(tensor.sizes.data(), tensor.sizes.size(), tensor.type,
134+ tensor.strides.data(), tensor.offset, ACL_FORMAT_ND,
135+ &tensor.storage_elements, 1, tensor.data);
136+ TORCH_CHECK(result, "aclCreateTensor failed");
137+ return TensorHandle(result, DestroyTensor{destroy});
138+}
139+ 
140+using Execute = aclnnStatus (*)(void *, uint64_t, aclOpExecutor *, aclrtStream);
141+inline void ExecuteOp(Execute execute, uint64_t bytes, aclOpExecutor *executor,
142+ c10_npu::NPUStream stream) {
143+ TORCH_CHECK(bytes <=
144+ static_cast<uint64_t>(std::numeric_limits<int64_t>::max()),
145+ "ACLNN workspace is too large");
146+ const auto raw_stream = stream.stream(false);
147+ // Allocate directly on the launch stream. Constructing/freeing a Tensor on
148+ // the host worker can record an event on its default stream and re-enter the
149+ // same task queue, deadlocking a cold call.
150+ auto release = [](void *ptr) {
151+ c10_npu::NPUCachingAllocator::raw_delete(ptr);
152+ };
153+ std::unique_ptr<void, decltype(release)> workspace(
154+ bytes ? c10_npu::NPUCachingAllocator::raw_alloc_with_stream(bytes,
155+ raw_stream)
156+ : nullptr,
157+ release);
158+ const auto status = execute(workspace.get(), bytes, executor, raw_stream);
159+ TORCH_CHECK(status == 0, "ACLNN execution failed, status=", status, ": ",
160+ aclGetRecentErrMsg());
161+}
162+ 
163+// Record stream use on the caller thread, just as tensor release/event
164+// recording is queued there. Worker tasks contain host metadata and
165+// stream-owned workspace only, matching torch_npu's asynchronous ACLNN dispatch
166+// contract.
167+using Task =
168+ std::function<int(const std::vector<TensorInfo> &, c10_npu::NPUStream)>;
169+inline void Enqueue(const char *name, const std::vector<at::Tensor> &tensors,
170+ Task task) {
171+ const auto stream =
172+ c10_npu::getCurrentNPUStream(tensors.front().device().index());
173+ std::vector<TensorInfo> metadata;
174+ for (const auto &tensor : tensors) {
175+ if (tensor.numel())
176+ c10_npu::NPUCachingAllocator::recordStream(tensor.storage().data_ptr(),
177+ stream);
178+ metadata.emplace_back(tensor);
179+ }
180+ const auto raw_stream = stream.stream(false);
181+ if (c10_npu::check_enqueue_need_use(raw_stream))
182+ TORCH_CHECK(aclrtUseStreamResInCurrentThread(raw_stream) == ACL_SUCCESS,
183+ "Cannot use NPU stream resources in the current thread");
184+ auto callback = [metadata = std::move(metadata), stream,
185+ task = std::move(task)] {
186+ const c10::OptionalDeviceGuard guard(stream.device());
187+ const auto raw_stream = stream.stream(false);
188+ if (c10_npu::check_dequeue_need_use(raw_stream))
189+ TORCH_CHECK(aclrtUseStreamResInCurrentThread(raw_stream) == ACL_SUCCESS,
190+ "Cannot use NPU stream resources in the current thread");
191+ return task(metadata, stream);
192+ };
193+ at_npu::native::OpCommand::RunOpApiV2(name, callback);
194+}
195+} // namespace gym_torch
@@ -0,0 +1,65 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+# -----------------------------------------------------------------------------------------------------------
9+"""Torch interfaces backed by the installed PyPTO-Gym ACLNN binaries.
10+ 
11+Importing this package is cheap and does not require torch. Bindings are loaded
12+on first attribute access, or explicitly through :func:`load`. This keeps the
13+namespace importable from tooling that does not have torch/torch_npu installed.
14+"""
15+import pkgutil
16+ 
17+from ._loader import binding_names as _binding_names
18+ 
19+# Allow the optional kernel wheel's pypto_gym.ops namespace to coexist. The
20+# attribute is updated through globals() because assigning to a dunder name
21+# directly is discouraged by the code checker; the effect is identical.
22+globals()['__path__'] = pkgutil.extend_path(globals()['__path__'], __name__)
23+ 
24+try:
25+ __all__ = list(_binding_names())
26+except ImportError:
27+ # Bindings are not installed (for example an ACLNN-only .run).
28+ __all__ = []
29+ 
30+ 
31+def load(op=None):
32+ """Load installed bindings and return the loaded operator names.
33+ 
34+ Accessing ``pypto_gym.<op>`` loads lazily; call this before using
35+ ``torch.ops.pypto_gym.<op>`` directly.
36+ """
37+ from ._loader import binding_names, load_binding
38+ 
39+ if op is None:
40+ names = list(binding_names())
41+ for name in names:
42+ load_binding(name)
43+ return names
44+ if not isinstance(op, str):
45+ raise TypeError('operator name must be a string')
46+ load_binding(op)
47+ return [op]
48+ 
49+ 
50+def __getattr__(name):
51+ if name.startswith('_'):
52+ raise AttributeError(name)
53+ from ._loader import binding_names, load_binding
54+ 
55+ try:
56+ names = binding_names()
57+ except ImportError as error:
58+ raise AttributeError(str(error)) from error
59+ if name not in names:
60+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
61+ return load_binding(name)
62+ 
63+ 
64+def __dir__():
65+ return sorted(set(globals()) | set(__all__))