Merged
fix(cake): 修复构建目录、pybind 调用与失败反馈 #301
fix(cake): 修复构建目录、pybind 调用与失败反馈 #301
Merged
liyinlongAdd on 23 days ago
Total: 3 files changed+142-23
@@ -42,9 +42,9 @@ import argparse
42 42 
43def _extract_wheel_so(wheel_file: Path, pybind_lib_dir: Path) -> None:43def _extract_wheel_so(wheel_file: Path, pybind_lib_dir: Path) -> None:
44 """Extract .so from wheel (it's a zip) into pybind_lib/, flattened to its root."""44 """Extract .so from wheel (it's a zip) into pybind_lib/, flattened to its root."""
45- with zipfile.ZipFile(str(wheel_file), 'r') as whl:45+ with zipfile.ZipFile(str(wheel_file), "r") as whl:
46 for name in whl.namelist():46 for name in whl.namelist():
47- if not (name.endswith('.so') or name.endswith('.pyd')):47+ if not (name.endswith(".so") or name.endswith(".pyd")):
48 continue48 continue
49 whl.extract(name, str(pybind_lib_dir))49 whl.extract(name, str(pybind_lib_dir))
50 # Move from nested dir to pybind_lib root50 # Move from nested dir to pybind_lib root
@@ -74,11 +74,11 @@ def _isolate_built_wheels(extension_dir: Path, work_dir: Path) -> None:
74def _run_pybind_build(extension_dir: Path) -> None:74def _run_pybind_build(extension_dir: Path) -> None:
75 """运行 setup.py build bdist_wheel,非零退出码时抛 CalledProcessError。"""75 """运行 setup.py build bdist_wheel,非零退出码时抛 CalledProcessError。"""
76 result = subprocess.run(76 result = subprocess.run(
77- [sys.executable, 'setup.py', 'build', 'bdist_wheel'],77+ [sys.executable, "setup.py", "build", "bdist_wheel"],
78 cwd=str(extension_dir),78 cwd=str(extension_dir),
79 capture_output=True,79 capture_output=True,
80 text=True,80 text=True,
81- timeout=30081+ timeout=300,
82 )82 )
83 if result.returncode != 0:83 if result.returncode != 0:
84 error_msg = (84 error_msg = (
@@ -88,7 +88,9 @@ def _run_pybind_build(extension_dir: Path) -> None:
88 f"Stderr:\n{result.stderr}"88 f"Stderr:\n{result.stderr}"
89 )89 )
90 logging.error(error_msg)90 logging.error(error_msg)
91- raise subprocess.CalledProcessError(result.returncode, result.args, result.stdout, result.stderr)91+ raise subprocess.CalledProcessError(
92+ result.returncode, result.args, result.stdout, result.stderr
93+ )
92 logging.info("编译 wheel 包成功")94 logging.info("编译 wheel 包成功")
93 95 
94 96 
@@ -160,11 +162,17 @@ def generate_pybind_bindings(work_dir: Path, op_cpp: Path) -> None:
160 162 
161 163 
162if __name__ == "__main__":164if __name__ == "__main__":
163- logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')165+ logging.basicConfig(level=logging.INFO, format="%(levelname)s - %(message)s")
164- parser = argparse.ArgumentParser(description="Generate PyBind bindings for AscendC operators")166+ parser = argparse.ArgumentParser(
167+ description="Generate PyBind bindings for AscendC operators"
168+ )
165 parser.add_argument("op_name", type=str, help="Operator name")169 parser.add_argument("op_name", type=str, help="Operator name")
166- parser.add_argument("--work-dir", type=str, default=None,170+ parser.add_argument(
167- help="Work directory containing op_name.cpp (default: output/<op_name>)")171+ "--work-dir",
172+ type=str,
173+ default=None,
174+ help="Work directory containing op_name.cpp (default: output/<op_name>)",
175+ )
168 176 
169 args = parser.parse_args()177 args = parser.parse_args()
170 178 
@@ -178,3 +186,4 @@ if __name__ == "__main__":
178 logging.info("PyBind bindings generated successfully")186 logging.info("PyBind bindings generated successfully")
179 except Exception as e:187 except Exception as e:
180 logging.error(e)188 logging.error(e)
189+ sys.exit(1)
@@ -12,7 +12,7 @@
12"""AscendC operator build bridge: compile, install .run, and rebuild pybind.12"""AscendC operator build bridge: compile, install .run, and rebuild pybind.
13 13 
14This script bridges the gap between code-performance-advisor (which modifies14This script bridges the gap between code-performance-advisor (which modifies
15-AscendC .cpp source) and ascendc_evaluation (which needs compiled .run +15+AscendC .cpp source) and ascendc-evaluation (which needs compiled .run +
16pybind to run tests).16pybind to run tests).
17 17 
18Pipeline:18Pipeline:
@@ -42,12 +42,10 @@ logger = logging.getLogger(__name__)
42 42 
43 43 
44ROOT = Path(__file__).resolve().parents[2]44ROOT = Path(__file__).resolve().parents[2]
45-CAKE_ROOT = ROOT.parents[2] # skills/code-performance-advisor -> CAKE245+CAKE_ROOT = ROOT.parents[1] # skills/code-performance-advisor -> plugin root
46OUTPUT_DIR = CAKE_ROOT / "output"46OUTPUT_DIR = CAKE_ROOT / "output"
47 47 
48-EVALUATION_SCRIPTS = (48+EVALUATION_SCRIPTS = ROOT.parent / "ascendc-evaluation" / "scripts"
49- CAKE_ROOT / ".claude" / "skills" / "ascendc_evaluation" / "scripts"
50-)
51GENERATE_PYBIND = EVALUATION_SCRIPTS / "generate_pybind.py"49GENERATE_PYBIND = EVALUATION_SCRIPTS / "generate_pybind.py"
52 50 
53WORKSPACE = ROOT / "workspace"51WORKSPACE = ROOT / "workspace"
@@ -208,7 +206,7 @@ def _rebuild_pybind(op: str) -> tuple[bool, str]:
208 206 
209 try:207 try:
210 result = subprocess.run(208 result = subprocess.run(
211- [sys.executable, str(GENERATE_PYBIND), "--op", op],209+ [sys.executable, str(GENERATE_PYBIND), op],
212 cwd=str(CAKE_ROOT),210 cwd=str(CAKE_ROOT),
213 capture_output=True,211 capture_output=True,
214 text=True,212 text=True,
@@ -255,7 +253,7 @@ def cmd_build(args: argparse.Namespace) -> int:
255 if count == 0:253 if count == 0:
256 logger.info(f"[WARN] No source files found in {source_dir}/op_host/ or op_kernel/")254 logger.info(f"[WARN] No source files found in {source_dir}/op_host/ or op_kernel/")
257 else:255 else:
258- logger.info(f"\n[STEP 1] No source-dir specified, building with existing files")256+ logger.info("\n[STEP 1] No source-dir specified, building with existing files")
259 257 
260 # Step 2: Build258 # Step 2: Build
261 logger.info(f"\n[STEP 2] Running build.sh (timeout={timeout}s)")259 logger.info(f"\n[STEP 2] Running build.sh (timeout={timeout}s)")
@@ -272,18 +270,18 @@ def cmd_build(args: argparse.Namespace) -> int:
272 if not install_ok:270 if not install_ok:
273 logger.info(f"[FAIL] {install_msg}")271 logger.info(f"[FAIL] {install_msg}")
274 return 3272 return 3
275- logger.info(f" Install successful")273+ logger.info(" Install successful")
276 else:274 else:
277- logger.info(f"\n[STEP 3] No .run package found, skipping install")275+ logger.info("\n[STEP 3] No .run package found, skipping install")
278 276 
279 # Step 4: Rebuild pybind277 # Step 4: Rebuild pybind
280- logger.info(f"\n[STEP 4] Rebuilding pybind")278+ logger.info("\n[STEP 4] Rebuilding pybind")
281 pybind_ok, pybind_msg = _rebuild_pybind(op)279 pybind_ok, pybind_msg = _rebuild_pybind(op)
282 if not pybind_ok:280 if not pybind_ok:
283 logger.info(f"[WARN] {pybind_msg}")281 logger.info(f"[WARN] {pybind_msg}")
284- logger.info(f" Pybind rebuild is not critical; evaluation may still work.")282+ logger.info(" Pybind rebuild is not critical; evaluation may still work.")
285 else:283 else:
286- logger.info(f" Pybind rebuild successful")284+ logger.info(" Pybind rebuild successful")
287 285 
288 logger.info(f"\n[DONE] Build pipeline completed for '{op}'")286 logger.info(f"\n[DONE] Build pipeline completed for '{op}'")
289 return 0287 return 0
@@ -307,7 +305,7 @@ def cmd_rollback(args: argparse.Namespace) -> int:
307 count = _copy_source(baseline_code, build_dir)305 count = _copy_source(baseline_code, build_dir)
308 logger.info(f" Restored {count} files")306 logger.info(f" Restored {count} files")
309 307 
310- logger.info(f"\n[ROLLBACK] Rebuilding with baseline code")308+ logger.info("\n[ROLLBACK] Rebuilding with baseline code")
311 build_ok, build_msg = _run_build(build_dir, timeout=args.timeout)309 build_ok, build_msg = _run_build(build_dir, timeout=args.timeout)
312 if not build_ok:310 if not build_ok:
313 logger.info(f"[FAIL] Rollback build failed: {build_msg}")311 logger.info(f"[FAIL] Rollback build failed: {build_msg}")
@@ -330,7 +328,7 @@ def build_parser() -> argparse.ArgumentParser:
330 parser = argparse.ArgumentParser(328 parser = argparse.ArgumentParser(
331 description="AscendC operator build bridge: compile + install + pybind"329 description="AscendC operator build bridge: compile + install + pybind"
332 )330 )
333- sub = parser.add_subparsers(dest="command")331+ parser.add_subparsers(dest="command")
334 332 
335 # The following arguments apply to the default (build) command.333 # The following arguments apply to the default (build) command.
336 parser.add_argument("--op", required=True, help="Operator name (e.g., fastgelu)")334 parser.add_argument("--op", required=True, help="Operator name (e.g., fastgelu)")
@@ -0,0 +1,112 @@
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+"""Exercise both build CLIs in a relocated CAKE plugin directory."""
12+ 
13+from pathlib import Path
14+import shutil
15+import subprocess
16+import sys
17+ 
18+import pytest
19+ 
20+ 
21+_PLUGIN = Path(__file__).resolve().parents[1]
22+_BRIDGE = Path(
23+ "skills/code-performance-advisor/scripts/analysis_engine/build_operator.py"
24+)
25+_EVALUATION = Path("skills/ascendc-evaluation/scripts")
26+_BUILD_SCRIPT = "#!/bin/sh\n: > operator_build_requested\n"
27+ 
28+ 
29+@pytest.fixture
30+def relocated_bridge(tmp_path):
31+ root = tmp_path / "CAKE plugin"
32+ bridge_file = root / _BRIDGE
33+ bridge_file.parent.mkdir(parents=True)
34+ shutil.copy2(_PLUGIN / _BRIDGE, bridge_file)
35+ return root, bridge_file
36+ 
37+ 
38+def _run_bridge(root, script, op):
39+ result = subprocess.run(
40+ [sys.executable, str(script), "--op", op],
41+ cwd=root.parent,
42+ capture_output=True,
43+ text=True,
44+ check=False,
45+ timeout=30,
46+ )
47+ return result.returncode, result.stdout + result.stderr
48+ 
49+ 
50+def test_find_build_directory_in_plugin_output(relocated_bridge):
51+ root, bridge = relocated_bridge
52+ build_dir = root / "output" / "add" / "AddCustom"
53+ build_dir.mkdir(parents=True)
54+ (build_dir / "build.sh").write_text(_BUILD_SCRIPT, encoding="utf-8")
55+ 
56+ status, log = _run_bridge(root, bridge, "add")
57+ 
58+ assert status == 0, log
59+ assert (build_dir / "operator_build_requested").is_file()
60+ 
61+ 
62+def _prepare_pybind(root, build_script, with_source=True):
63+ evaluation = root / _EVALUATION
64+ template = evaluation / "template" / "CppExtension"
65+ template.mkdir(parents=True)
66+ shutil.copy2(_PLUGIN / _EVALUATION / "generate_pybind.py", evaluation)
67+ (template / "setup.py").write_text(build_script, encoding="utf-8")
68+ output = root / "output" / "Add"
69+ output.mkdir(parents=True)
70+ (output / "build.sh").write_text(_BUILD_SCRIPT, encoding="utf-8")
71+ if with_source:
72+ (output / "Add.cpp").write_text(
73+ "// operator binding source\n", encoding="utf-8"
74+ )
75+ return output
76+ 
77+ 
78+def test_rebuild_pybind_uses_bundled_cli_and_plugin_output(relocated_bridge):
79+ root, bridge = relocated_bridge
80+ output = _prepare_pybind(
81+ root,
82+ "from pathlib import Path\n"
83+ "Path('build_requested').write_text('ok', encoding='utf-8')\n",
84+ )
85+ 
86+ status, log = _run_bridge(root, bridge, "Add")
87+ 
88+ assert status == 0, log
89+ extension = output / "ascend_op_pybind" / "CppExtension"
90+ assert (extension / "csrc" / "op.cpp").read_text(encoding="utf-8") == (
91+ "// operator binding source\n"
92+ )
93+ assert (extension / "build_requested").read_text(encoding="utf-8") == "ok"
94+ assert "Pybind rebuild successful" in log
95+ 
96+ 
97+@pytest.mark.parametrize(
98+ ("with_source", "build_script", "expected"),
99+ [(False, "", "Add.cpp"), (True, "raise SystemExit(7)\n", "Exit Code: 7")],
100+ ids=["missing-source", "failed-build"],
101+)
102+def test_rebuild_pybind_reports_failures(
103+ relocated_bridge, with_source, build_script, expected
104+):
105+ root, bridge = relocated_bridge
106+ _prepare_pybind(root, build_script, with_source)
107+ 
108+ status, log = _run_bridge(root, bridge, "Add")
109+ 
110+ assert status == 0, log
111+ assert "Pybind rebuild warning (exit 1)" in log
112+ assert expected in log