| @@ -98,7 +98,7 @@ cannbot-skills/ | |||
| 98 | | 断裂点分析与报告类 | `pypto-benchmark-fracture-aggregator`、`pypto-fracture-point-detector`、`pypto-session-dfx-report` | Session 断裂点聚合/检测/复现取证、Issue 文档产出、DFX 报告 | | 98 | | 断裂点分析与报告类 | `pypto-benchmark-fracture-aggregator`、`pypto-fracture-point-detector`、`pypto-session-dfx-report` | Session 断裂点聚合/检测/复现取证、Issue 文档产出、DFX 报告 | |
| 99 | | Pro 专属类 | `pypto-pro-golden-generate`、`pypto-pro-environment-check`、`pypto-pro-precision-debug`、`pypto-pro-cann-delivery`、`pypto-pro-docs-search` | PyPTO-Pro 需求、开发、调优与调试、CANN 交付与文档检索 | | 99 | | Pro 专属类 | `pypto-pro-golden-generate`、`pypto-pro-environment-check`、`pypto-pro-precision-debug`、`pypto-pro-cann-delivery`、`pypto-pro-docs-search` | PyPTO-Pro 需求、开发、调优与调试、CANN 交付与文档检索 | |
| 100 | | Pro 核心技能 | `pypto-pro-kernel` | 原生 kernel 开发、验证、调试与优化,内含参考资料、检查工具和样例 | | 100 | | Pro 核心技能 | `pypto-pro-kernel` | 原生 kernel 开发、验证、调试与优化,内含参考资料、检查工具和样例 | |
| 101 | -| Pro PANKO 调优 | `pypto-pro-op-perf-panko-manual` | 单文件 JIT 的 NPU 延迟与片上内存优化 | | 101 | +| Pro PANKO 调优 | `pypto-pro-op-perf-panko-manual` | 单文件或多文件 JIT 的 NPU 延迟与片上内存优化 | |
| 102 | 102 | ||
| 103 | ### 模型适配(model/) | 103 | ### 模型适配(model/) |
| 104 | 104 | ||
| @@ -91,7 +91,7 @@ python scripts/check.py | |||
| 91 | | 报告与可视化 | `pypto-session-dfx-report` | Session DFX 报告(端到端耗时、token 消耗、执行轨迹) | | 91 | | 报告与可视化 | `pypto-session-dfx-report` | Session DFX 报告(端到端耗时、token 消耗、执行轨迹) | |
| 92 | | **Pro 专属** | `pypto-pro-golden-generate`、`pypto-pro-environment-check`、`pypto-pro-precision-debug`、`pypto-pro-cann-delivery`、`pypto-pro-docs-search` | PyPTO-Pro 开发、精度诊断、CANN 交付与文档检索 | | 92 | | **Pro 专属** | `pypto-pro-golden-generate`、`pypto-pro-environment-check`、`pypto-pro-precision-debug`、`pypto-pro-cann-delivery`、`pypto-pro-docs-search` | PyPTO-Pro 开发、精度诊断、CANN 交付与文档检索 | |
| 93 | | **Pro 核心技能** | [pypto-pro-kernel](ops/pypto-pro-kernel/SKILL.md) | 原生 kernel 开发、验证、调试与优化,内含参考资料、检查工具和样例 | | 93 | | **Pro 核心技能** | [pypto-pro-kernel](ops/pypto-pro-kernel/SKILL.md) | 原生 kernel 开发、验证、调试与优化,内含参考资料、检查工具和样例 | |
| 94 | -| **Pro PANKO 调优** | [pypto-pro-op-perf-panko-manual](ops/pypto-pro-op-perf-panko-manual/SKILL.md) | 单文件 JIT 的 NPU 延迟与片上内存优化,见 [quickstart](plugins-official/pypto-pro-op-orchestrator/quickstart.md) | | 94 | +| **Pro PANKO 调优** | [pypto-pro-op-perf-panko-manual](ops/pypto-pro-op-perf-panko-manual/SKILL.md) | 单文件或多文件 JIT 的 NPU 延迟与片上内存优化,见 [quickstart](plugins-official/pypto-pro-op-orchestrator/quickstart.md) | |
| 95 | 95 | ||
| 96 | **模型适配**(model/,共 3 个) | 96 | **模型适配**(model/,共 3 个) |
| 97 | 97 | ||
| @@ -87,14 +87,28 @@ def _delivered_check(st, op_dir): | |||
| 87 | on_disk = None | 87 | on_disk = None |
| 88 | if f and os.path.exists(f): | 88 | if f and os.path.exists(f): |
| 89 | on_disk = hashlib.sha256(_read_bytes(f)).hexdigest() | 89 | on_disk = hashlib.sha256(_read_bytes(f)).hexdigest() |
| 90 | + matches = bool(want) and on_disk == want | ||
| 91 | + policy = _classic_verification_policy() | ||
| 92 | + if matches and policy.strict_restore: | ||
| 93 | + matches = policy.matches(op_dir, f, want) | ||
| 90 | out_d = {"best_code_hash": want, "delivered_code_hash": on_disk, | 94 | out_d = {"best_code_hash": want, "delivered_code_hash": on_disk, |
| 91 | - "delivered_is_best": bool(want) and on_disk == want, | 95 | + "delivered_is_best": matches, |
| 92 | "delivery": detail} | 96 | "delivery": detail} |
| 93 | if want and node and want != node: | 97 | if want and node and want != node: |
| 94 | out_d["best_node_code_hash"] = node | 98 | out_d["best_node_code_hash"] = node |
| 95 | return out_d | 99 | return out_d |
| 96 | 100 | ||
| 97 | 101 | ||
| 102 | +def _restore_delivery_point(op_dir, op_file, want): | ||
| 103 | + policy = _classic_verification_policy() | ||
| 104 | + restored = restore(op_dir, op_file, want) | ||
| 105 | + if policy.strict_restore: | ||
| 106 | + if not want or (not restored and os.path.exists(npath(op_dir, want))): | ||
| 107 | + return False | ||
| 108 | + return policy.matches(op_dir, op_file, want) | ||
| 109 | + return restored or file_hash(op_file) == want | ||
| 110 | + | ||
| 111 | + | ||
| 98 | def _deliver_best(st, a): | 112 | def _deliver_best(st, a): |
| 99 | """Put the global best in the working file, or refuse the stop. | 113 | """Put the global best in the working file, or refuse the stop. |
| 100 | 114 | ||
| @@ -115,7 +129,7 @@ def _deliver_best(st, a): | |||
| 115 | "delivered_values": detail.get("values"), | 129 | "delivered_values": detail.get("values"), |
| 116 | "at_eval": st["progress"]["evals_used"]} | 130 | "at_eval": st["progress"]["evals_used"]} |
| 117 | op_f = op_file_path(st, a.op_dir) | 131 | op_f = op_file_path(st, a.op_dir) |
| 118 | - if best_hash and (restore(a.op_dir, op_f, best_hash) or file_hash(op_f) == best_hash): | 132 | + if best_hash and _restore_delivery_point(a.op_dir, op_f, best_hash): |
| 119 | # Frozen, because everything after the stop has to name THIS program: | 133 | # Frozen, because everything after the stop has to name THIS program: |
| 120 | # the verification arm, the file put back between passes, the speedup | 134 | # the verification arm, the file put back between passes, the speedup |
| 121 | # the pass is compared against. `ratchet_best_hash` is `best_node` and | 135 | # the pass is compared against. `ratchet_best_hash` is `best_node` and |
| @@ -257,7 +257,10 @@ def restore(op_dir, op_file, code_hash): | |||
| 257 | try: | 257 | try: |
| 258 | from .backend import current | 258 | from .backend import current |
| 259 | if current() is not None: | 259 | if current() is not None: |
| 260 | - current().write_source(op_file, _read_bytes(snap).decode("utf-8")) | 260 | + data = _read_bytes(snap) |
| 261 | + if hashlib.sha256(data).hexdigest() != code_hash: | ||
| 262 | + return False | ||
| 263 | + current().write_source(op_file, data.decode("utf-8")) | ||
| 261 | return file_hash(op_file) == code_hash | 264 | return file_hash(op_file) == code_hash |
| 262 | else: | 265 | else: |
| 263 | shutil.copyfile(snap, op_file) | 266 | shutil.copyfile(snap, op_file) |
| @@ -1,18 +1,18 @@ | |||
| 1 | --- | 1 | --- |
| 2 | name: pypto-pro-op-perf-panko-manual | 2 | name: pypto-pro-op-perf-panko-manual |
| 3 | -description: Base PANKO latency/on-chip-memory optimization of single-file PyPTO-Pro kernels on NPU, using catalog-guided structural search and TPE for inferred tile domains. | 3 | +description: Base PANKO latency/on-chip-memory optimization of single-file or multi-file PyPTO-Pro kernels on NPU, using catalog-guided structural search and TPE for inferred tile domains. |
| 4 | --- | 4 | --- |
| 5 | 5 | ||
| 6 | # PANKO for PyPTO-Pro | 6 | # PANKO for PyPTO-Pro |
| 7 | 7 | ||
| 8 | -Freeze host wrappers and precision tests. Follow the [workflow](references/workflow.md) for INIT and final verification. | 8 | +Freeze host wrappers and precision tests. Preserve package imports and file layout. Follow the [workflow](references/workflow.md) for INIT and final verification. |
| 9 | On resume, reconcile state, receipts and the pending directive. Keep one writer and the original budget. | 9 | On resume, reconcile state, receipts and the pending directive. Keep one writer and the original budget. |
| 10 | 10 | ||
| 11 | For structural CODE, use the selected action’s `delta` and [profile evidence](references/world_model.md). | 11 | For structural CODE, use the selected action’s `delta` and [profile evidence](references/world_model.md). |
| 12 | Give the coder the action ID, target function, edit, expected effect and correctness constraints. | 12 | Give the coder the action ID, target function, edit, expected effect and correctness constraints. |
| 13 | -Measure staged TPE candidates unchanged. | 13 | +Measure staged TPE candidates unchanged. After package edits, run `python3 "$S/source_analysis/program_bundle.py" refresh --manifest "$D/program.json"`. |
| 14 | 14 | ||
| 15 | -With the installed scripts (`S`), campaign (`D`), staged kernel (`OP`) and frozen test command, run STEP once per stable dispatch ID: | 15 | +With the installed scripts (`S`), campaign (`D`), staged kernel or package view (`OP`) and frozen test command, run STEP once per stable dispatch ID: |
| 16 | 16 | ||
| 17 | ```sh | 17 | ```sh |
| 18 | python3 "$S/panko_harness.py" step --op-dir "$D" --op-file "$OP" --parent "$ACTION_ID" \ | 18 | python3 "$S/panko_harness.py" step --op-dir "$D" --op-file "$OP" --parent "$ACTION_ID" \ |
| @@ -1,13 +1,23 @@ | |||
| 1 | # Base campaign workflow | 1 | # Base campaign workflow |
| 2 | 2 | ||
| 3 | Use the NPU environment’s Python, PyPTO-Pro, Optuna and CANN msprof. Keep device, imports, test inputs, shapes and tolerances fixed. | 3 | Use the NPU environment’s Python, PyPTO-Pro, Optuna and CANN msprof. Keep device, imports, test inputs, shapes and tolerances fixed. |
| 4 | -`S` is the installed scripts directory, `D` the campaign directory and `OP` the staged kernel. | 4 | +`S` is the installed scripts directory, `D` the campaign directory and `OP` the staged kernel or package view. |
| 5 | 5 | ||
| 6 | ## Initialize once | 6 | ## Initialize once |
| 7 | 7 | ||
| 8 | +For a package, prepare a view and use it as `OP`. The test imports the original package. | ||
| 9 | +For a kernel in `outer.inner`, pass the `outer/` directory as `--root` so its | ||
| 10 | +`__init__.py` is hashed and exported with the kernel. | ||
| 11 | + | ||
| 12 | +```sh | ||
| 13 | +python3 "$S/source_analysis/program_bundle.py" prepare --root /absolute/package \ | ||
| 14 | + --view "$D/optimization/program.py" --manifest "$D/program.json" | ||
| 15 | +``` | ||
| 16 | + | ||
| 8 | Use one Python script invocation that fails on precision mismatch (`TEST_COMMAND`) and a JSON list of immutable test, reference and input paths (`TEST_FILES`). | 17 | Use one Python script invocation that fails on precision mismatch (`TEST_COMMAND`) and a JSON list of immutable test, reference and input paths (`TEST_FILES`). |
| 9 | Set `CAPACITY` to the selected target's usable Vec, Mat, Left, Right and Acc budgets in bytes. If its installed tile declaration checker establishes a separate address limit for a space, pass it in bytes via `--address-limits` as a JSON object. Omitted spaces use the usable budget as the limit. Use a fresh receipt path and specify `--op-name` for ambiguous single-file profiles. | 18 | Set `CAPACITY` to the selected target's usable Vec, Mat, Left, Right and Acc budgets in bytes. If its installed tile declaration checker establishes a separate address limit for a space, pass it in bytes via `--address-limits` as a JSON object. Omitted spaces use the usable budget as the limit. Use a fresh receipt path and specify `--op-name` for ambiguous single-file profiles. |
| 10 | The memory objective sums source-derived high-water marks. Treat an incomplete reading as unknown. | 19 | The memory objective sums source-derived high-water marks. Treat an incomplete reading as unknown. |
| 20 | +Multi-file timing includes all AI-Core tasks per invocation. | ||
| 11 | 21 | ||
| 12 | ```sh | 22 | ```sh |
| 13 | python3 "$S/measure.py" --op-file "$OP" --op-dir "$D" --device "$DEVICE" \ | 23 | python3 "$S/measure.py" --op-file "$OP" --op-dir "$D" --device "$DEVICE" \ |
| @@ -22,5 +32,5 @@ python3 "$S/panko_harness.py" select --op-dir "$D" | |||
| 22 | 32 | ||
| 23 | After STOP, run `python3 "$S/panko_harness.py" verify --auto --op-dir "$D"` for the whole Pareto front. | 33 | After STOP, run `python3 "$S/panko_harness.py" verify --auto --op-dir "$D"` for the whole Pareto front. |
| 24 | For manual ABBA, use `verify --op-dir "$D" --acquire` and submit its fresh receipt with `verify --op-dir "$D" --measurement-file <returned-path>` at each stage. | 34 | For manual ABBA, use `verify --op-dir "$D" --acquire` and submit its fresh receipt with `verify --op-dir "$D" --measurement-file <returned-path>` at each stage. |
| 25 | -Run `report --op-dir "$D"`, check the restored source hash and retain the frontier sources. | 35 | +Run `report --op-dir "$D"`, check the restored source hash and retain the frontier views with their runtime packages. |
| 26 | Give the verifier the delivered file and hash, frozen test/reference files, command, environment, tolerances and receipts. Report success only after independent PASS. | 36 | Give the verifier the delivered file and hash, frozen test/reference files, command, environment, tolerances and receipts. Report success only after independent PASS. |
| @@ -228,6 +228,7 @@ def arguments(sub): | |||
| 228 | for name in ("normalize", "init"): | 228 | for name in ("normalize", "init"): |
| 229 | sub.choices[name].add_argument("--case-context", default="") | 229 | sub.choices[name].add_argument("--case-context", default="") |
| 230 | init = sub.choices["init"] | 230 | init = sub.choices["init"] |
| 231 | + init.add_argument("--program-manifest") | ||
| 231 | init.add_argument("--mode", choices=["npu"]) | 232 | init.add_argument("--mode", choices=["npu"]) |
| 232 | for flag in ("--test-command", "--op-name", "--normalization-before", "--normalization-evidence"): | 233 | for flag in ("--test-command", "--op-name", "--normalization-before", "--normalization-evidence"): |
| 233 | init.add_argument(flag) | 234 | init.add_argument(flag) |
| @@ -14,6 +14,7 @@ from __future__ import annotations | |||
| 14 | import csv | 14 | import csv |
| 15 | import glob | 15 | import glob |
| 16 | import hashlib | 16 | import hashlib |
| 17 | +import json | ||
| 17 | import logging | 18 | import logging |
| 18 | import math | 19 | import math |
| 19 | import os | 20 | import os |
| @@ -24,7 +25,9 @@ import subprocess | |||
| 24 | import tempfile | 25 | import tempfile |
| 25 | import time | 26 | import time |
| 26 | from contextlib import contextmanager | 27 | from contextlib import contextmanager |
| 28 | +from collections import Counter | ||
| 27 | from dataclasses import dataclass, replace | 29 | from dataclasses import dataclass, replace |
| 30 | +from importlib.util import resolve_name | ||
| 28 | from pathlib import Path | 31 | from pathlib import Path |
| 29 | from typing import List, Mapping, Optional, Tuple | 32 | from typing import List, Mapping, Optional, Tuple |
| 30 | 33 | ||
| @@ -72,6 +75,7 @@ class Reading: | |||
| 72 | # Each latency sample sums the device rows belonging to one call. | 75 | # Each latency sample sums the device rows belonging to one call. |
| 73 | calls: Optional[int] = None | 76 | calls: Optional[int] = None |
| 74 | rows_per_call: Optional[int] = None | 77 | rows_per_call: Optional[int] = None |
| 78 | + tasks_per_call: Optional[dict] = None | ||
| 75 | 79 | ||
| 76 | 80 | ||
| 77 | def prior_cell(row: Mapping, column: str) -> Optional[float]: | 81 | def prior_cell(row: Mapping, column: str) -> Optional[float]: |
| @@ -141,8 +145,6 @@ def _group_by_call(rows, calls): | |||
| 141 | 145 | ||
| 142 | 146 | ||
| 143 | def _call_durations(groups, chosen): | 147 | def _call_durations(groups, chosen): |
| 144 | - if chosen == "*" and any(sorted(r[NAME] for r in group) != sorted(r[NAME] for r in groups[0]) for group in groups): | ||
| 145 | - raise ValueError("program task composition differs between repeated calls") | ||
| 146 | durations = [[prior_cell(row, DURATION) for row in group] for group in groups] | 148 | durations = [[prior_cell(row, DURATION) for row in group] for group in groups] |
| 147 | if any(None in cells for cells in durations): | 149 | if any(None in cells for cells in durations): |
| 148 | raise ValueError(f"missing or invalid {DURATION} for {chosen!r}") | 150 | raise ValueError(f"missing or invalid {DURATION} for {chosen!r}") |
| @@ -152,6 +154,17 @@ def _call_durations(groups, chosen): | |||
| 152 | return samples | 154 | return samples |
| 153 | 155 | ||
| 154 | 156 | ||
| 157 | +def _program_tasks(groups): | ||
| 158 | + """Count each AI-Core name per call, independent of row order.""" | ||
| 159 | + def counts(group): | ||
| 160 | + return Counter(row[NAME].strip() for row in group) | ||
| 161 | + | ||
| 162 | + first = counts(groups[0]) | ||
| 163 | + if any(counts(group) != first for group in groups[1:]): | ||
| 164 | + raise ValueError("program task composition differs between repeated calls") | ||
| 165 | + return dict(first) | ||
| 166 | + | ||
| 167 | + | ||
| 155 | def _op_summary_in(root: str) -> str: | 168 | def _op_summary_in(root: str) -> str: |
| 156 | """The one op_summary CSV under `root`, or raise `ValueError` naming them.""" | 169 | """The one op_summary CSV under `root`, or raise `ValueError` naming them.""" |
| 157 | found = sorted(glob.glob(os.path.join(root, "**", "op_summary*.csv"), recursive=True)) | 170 | found = sorted(glob.glob(os.path.join(root, "**", "op_summary*.csv"), recursive=True)) |
| @@ -288,7 +301,8 @@ def _summarise_launches(profile, ordered, warmup, calls, block_dim): | |||
| 288 | raise ValueError(disagreement) | 301 | raise ValueError(disagreement) |
| 289 | return Reading(p=round(median, LATENCY_DECIMALS), samples=tuple(warm), warmup=warmup, op_name=chosen, | 302 | return Reading(p=round(median, LATENCY_DECIMALS), samples=tuple(warm), warmup=warmup, op_name=chosen, |
| 290 | sigma_log=log_sample_sigma(warm), block_num=block, rows_considered=profile.core_count, error=None, | 303 | sigma_log=log_sample_sigma(warm), block_num=block, rows_considered=profile.core_count, error=None, |
| 291 | - calls=calls, rows_per_call=len(groups[0])) | 304 | + calls=calls, rows_per_call=len(groups[0]), |
| 305 | + tasks_per_call=_program_tasks(groups) if chosen == "*" else None) | ||
| 292 | 306 | ||
| 293 | 307 | ||
| 294 | _agg = core_profile.aggregate | 308 | _agg = core_profile.aggregate |
| @@ -307,7 +321,8 @@ def reading_to_metrics(reading, workspace, compile_s=None): | |||
| 307 | # Whether `p` is one of the warm readings rather than a synthetic midpoint. | 321 | # Whether `p` is one of the warm readings rather than a synthetic midpoint. |
| 308 | "p_is_sample": bool(samples) and reading.p is not None and statistics.median(samples) in samples, | 322 | "p_is_sample": bool(samples) and reading.p is not None and statistics.median(samples) in samples, |
| 309 | } | 323 | } |
| 310 | - optional = {"calls": reading.calls, "rows_per_call": reading.rows_per_call, "p_error": reading.error or None} | 324 | + optional = {"calls": reading.calls, "rows_per_call": reading.rows_per_call, |
| 325 | + "tasks_per_call": reading.tasks_per_call, "p_error": reading.error or None} | ||
| 311 | out.update({key: value for key, value in optional.items() if value is not None}) | 326 | out.update({key: value for key, value in optional.items() if value is not None}) |
| 312 | out.update(workspace) | 327 | out.update(workspace) |
| 313 | return out | 328 | return out |
| @@ -327,6 +342,11 @@ def imported_impls(output): | |||
| 327 | def impl_mismatch(output, impl_path): | 342 | def impl_mismatch(output, impl_path): |
| 328 | """The reason the test measured a DIFFERENT file, or None.""" | 343 | """The reason the test measured a DIFFERENT file, or None.""" |
| 329 | seen = imported_impls(output) | 344 | seen = imported_impls(output) |
| 345 | + if impl_path: | ||
| 346 | + from source_analysis.program_bundle import runtime_spec | ||
| 347 | + spec = runtime_spec(impl_path) | ||
| 348 | + if spec: | ||
| 349 | + return _program_import_mismatch(spec, seen, impl_path, output) | ||
| 330 | if not impl_path: | 350 | if not impl_path: |
| 331 | return "no staged implementation path" | 351 | return "no staged implementation path" |
| 332 | if not seen: | 352 | if not seen: |
| @@ -428,20 +448,36 @@ def prepare_launch(run_once, options): | |||
| 428 | else: | 448 | else: |
| 429 | looped, why = repeat_runner.looped_argv(run_once, launches, python=options.python, block_dim=options.block_dim, | 449 | looped, why = repeat_runner.looped_argv(run_once, launches, python=options.python, block_dim=options.block_dim, |
| 430 | block_dim_flag=options.block_dim_flag) | 450 | block_dim_flag=options.block_dim_flag) |
| 431 | - if looped is not None: | 451 | + if looped is None: |
| 432 | - child_env = _profile_environment(options.env, options.impl_path) | 452 | + reason = ("the test command cannot be looped in-process, so this " |
| 433 | - return _PreparedProfile(options, workspace, looped, child_env) | 453 | + "acquisition would have measured ONE launch and called it %d: " |
| 434 | - reason = ("the test command cannot be looped in-process, so this " | 454 | + "%s" % (launches, why)) |
| 435 | - "acquisition would have measured ONE launch and called it %d: " | 455 | + else: |
| 436 | - "%s" % (launches, why)) | 456 | + try: |
| 457 | + child_env = _profile_environment(options.env, options.impl_path) | ||
| 458 | + except (OSError, ValueError, KeyError, TypeError, SyntaxError) as exc: | ||
| 459 | + reason = "invalid program runtime identity: %s" % exc | ||
| 460 | + else: | ||
| 461 | + return _PreparedProfile(options, workspace, looped, child_env) | ||
| 437 | return reading_to_metrics(Reading(options.warmup, reason), workspace=workspace) | 462 | return reading_to_metrics(Reading(options.warmup, reason), workspace=workspace) |
| 438 | 463 | ||
| 439 | 464 | ||
| 440 | def _profile_environment(env, impl_path): | 465 | def _profile_environment(env, impl_path): |
| 441 | child_env = dict(os.environ) | 466 | child_env = dict(os.environ) |
| 442 | child_env.update({str(key): str(value) for key, value in (env or {}).items()}) | 467 | child_env.update({str(key): str(value) for key, value in (env or {}).items()}) |
| 468 | + child_env.pop(repeat_runner.EXPORT_PATHS_ENV, None) | ||
| 443 | if impl_path: | 469 | if impl_path: |
| 470 | + from source_analysis.program_bundle import runtime_spec | ||
| 444 | child_env[repeat_runner.IMPL_ENV] = os.path.abspath(impl_path) | 471 | child_env[repeat_runner.IMPL_ENV] = os.path.abspath(impl_path) |
| 472 | + spec = runtime_spec(impl_path) if os.path.isfile(impl_path) else None | ||
| 473 | + child_env.pop(repeat_runner.PROGRAM_IMPL_ENV, None) | ||
| 474 | + if spec: | ||
| 475 | + child_env[repeat_runner.PROGRAM_IMPL_ENV] = json.dumps(sorted(spec["files"])) | ||
| 476 | + export_dir = Path(str(impl_path) + ".program").resolve() | ||
| 477 | + root = Path(spec["root"]) | ||
| 478 | + if root.is_relative_to(export_dir): | ||
| 479 | + child_env[repeat_runner.EXPORT_PATHS_ENV] = json.dumps( | ||
| 480 | + [str(export_dir), str(root)] if root != export_dir else [str(root)]) | ||
| 445 | return child_env | 481 | return child_env |
| 446 | 482 | ||
| 447 | 483 | ||
| @@ -504,7 +540,8 @@ def _profile_once(prepared, out_dir): | |||
| 504 | metrics.update(diagnostics) | 540 | metrics.update(diagnostics) |
| 505 | from panko_core.bayesian_optimization.evaluator import ENV_FAULT_MARKERS | 541 | from panko_core.bayesian_optimization.evaluator import ENV_FAULT_MARKERS |
| 506 | fault = next((marker for marker in ENV_FAULT_MARKERS if marker in output), None) | 542 | fault = next((marker for marker in ENV_FAULT_MARKERS if marker in output), None) |
| 507 | - if fault or (metrics.get("impl_module_mismatch") and metrics.get("impl_modules_seen")): | 543 | + import_observed = metrics.get("impl_modules_seen") or metrics.get("correctness_passed") |
| 544 | + if fault or (metrics.get("impl_module_mismatch") and import_observed): | ||
| 508 | metrics.update(test_failed=False, correctness_passed=False, p=None, samples=[], | 545 | metrics.update(test_failed=False, correctness_passed=False, p=None, samples=[], |
| 509 | p_error="acquisition refused: " + (fault or "wrong implementation imported")) | 546 | p_error="acquisition refused: " + (fault or "wrong implementation imported")) |
| 510 | return metrics, output, rc | 547 | return metrics, output, rc |
| @@ -570,6 +607,50 @@ def campaign_command(command, op_dir, device): | |||
| 570 | return argv, cwd, env | 607 | return argv, cwd, env |
| 571 | 608 | ||
| 572 | 609 | ||
| 610 | +def _program_import_mismatch(spec, seen, impl_path, output): | ||
| 611 | + from source_analysis.program_bundle import package_namespace | ||
| 612 | + from source_analysis.program_view import ProgramView | ||
| 613 | + | ||
| 614 | + for filename in spec["required"]: | ||
| 615 | + if seen.get(filename) != spec["files"][filename]: | ||
| 616 | + return "required program entry was not imported from the staged bundle: %s" % filename | ||
| 617 | + view = ProgramView.from_source(Path(impl_path).read_text(encoding="utf-8")) | ||
| 618 | + origins, packages = {}, {} | ||
| 619 | + for line in (output or "").splitlines(): | ||
| 620 | + if line.startswith(repeat_runner.MODULE_MARKER): | ||
| 621 | + name, package, path = json.loads(line[len(repeat_runner.MODULE_MARKER):]) | ||
| 622 | + origins.setdefault(name, set()).add(path) | ||
| 623 | + packages.setdefault(path, set()).add(package) | ||
| 624 | + root = Path(spec["root"]) | ||
| 625 | + try: | ||
| 626 | + imports = view.acquisition_imports(package_namespace(root)) | ||
| 627 | + except ValueError as exc: | ||
| 628 | + return str(exc) | ||
| 629 | + for filename, expected in spec["files"].items(): | ||
| 630 | + if filename not in seen: | ||
| 631 | + continue | ||
| 632 | + if seen[filename] != expected: | ||
| 633 | + return "imported program member differs from staged bundle: %s" % filename | ||
| 634 | + relative = str(Path(filename).relative_to(root)) | ||
| 635 | + if imports[relative] and filename not in packages: | ||
| 636 | + return "missing module identity for staged importer: %s" % filename | ||
| 637 | + mismatch = _local_import_mismatch(imports[relative], packages.get(filename, ()), | ||
| 638 | + spec, seen, origins, relative) | ||
| 639 | + if mismatch: | ||
| 640 | + return mismatch | ||
| 641 | + return None | ||
| 642 | + | ||
| 643 | + | ||
| 644 | +def _local_import_mismatch(imports, packages, spec, seen, origins, relative): | ||
| 645 | + for package in packages: | ||
| 646 | + for lookup, dependency in imports.items(): | ||
| 647 | + name = resolve_name(lookup, package) | ||
| 648 | + expected_path = str(Path(spec["root"]) / dependency) | ||
| 649 | + if origins.get(name) != {expected_path} or seen.get(expected_path) != spec["files"][expected_path]: | ||
| 650 | + return "local import %s in %s did not resolve to staged %s" % (name, relative, dependency) | ||
| 651 | + return None | ||
| 652 | + | ||
| 653 | + | ||
| 573 | def check_campaign_command(command, op_dir, contract): | 654 | def check_campaign_command(command, op_dir, contract): |
| 574 | """Compare a command with the frozen baseline after applying the campaign device.""" | 655 | """Compare a command with the frozen baseline after applying the campaign device.""" |
| 575 | from panko_core.bayesian_optimization.evaluator import UnsupportedCommand | 656 | from panko_core.bayesian_optimization.evaluator import UnsupportedCommand |
| @@ -19,12 +19,15 @@ if __package__ in (None, ""): | |||
| 19 | 19 | ||
| 20 | import builtins | 20 | import builtins |
| 21 | import hashlib | 21 | import hashlib |
| 22 | +import json | ||
| 22 | import logging | 23 | import logging |
| 23 | import os | 24 | import os |
| 24 | import runpy | 25 | import runpy |
| 25 | import time | 26 | import time |
| 26 | import shutil | 27 | import shutil |
| 27 | import traceback | 28 | import traceback |
| 29 | +from contextlib import contextmanager | ||
| 30 | +from importlib.machinery import SourceFileLoader | ||
| 28 | 31 | ||
| 29 | logger = logging.getLogger(__name__) | 32 | logger = logging.getLogger(__name__) |
| 30 | 33 | ||
| @@ -36,8 +39,11 @@ LAUNCH_MARKER = "[panko-progress] launch %d/%d done" | |||
| 36 | 39 | ||
| 37 | # Bind the measurement to the loaded module path and hash. | 40 | # Bind the measurement to the loaded module path and hash. |
| 38 | IMPL_ENV = "PANKO_IMPL_PATH" | 41 | IMPL_ENV = "PANKO_IMPL_PATH" |
| 42 | +PROGRAM_IMPL_ENV = "PANKO_PROGRAM_IMPL_PATHS" | ||
| 43 | +EXPORT_PATHS_ENV = "PANKO_EXPORT_IMPORT_PATHS" | ||
| 39 | 44 | ||
| 40 | IMPL_MARKER = "[panko-progress] impl %s %s" | 45 | IMPL_MARKER = "[panko-progress] impl %s %s" |
| 46 | +MODULE_MARKER = "[panko-progress] program module " | ||
| 41 | 47 | ||
| 42 | # A frozen test can read its launch grid from this environment variable. | 48 | # A frozen test can read its launch grid from this environment variable. |
| 43 | BLOCK_DIM_ENV = "PANKO_BLOCK_DIM" | 49 | BLOCK_DIM_ENV = "PANKO_BLOCK_DIM" |
| @@ -159,13 +165,16 @@ def run(script, args, launches, block_dim=None, timing=None): | |||
| 159 | here = os.path.dirname(script) | 165 | here = os.path.dirname(script) |
| 160 | if here and here not in sys.path: | 166 | if here and here not in sys.path: |
| 161 | sys.path.insert(0, here) | 167 | sys.path.insert(0, here) |
| 168 | + # Frozen tests can import either the qualified package or its top-level modules. | ||
| 169 | + sys.path[:0] = json.loads(os.environ.pop(EXPORT_PATHS_ENV, "[]")) | ||
| 162 | if block_dim is not None: | 170 | if block_dim is not None: |
| 163 | os.environ[BLOCK_DIM_ENV] = str(int(block_dim)) | 171 | os.environ[BLOCK_DIM_ENV] = str(int(block_dim)) |
| 164 | started = time.perf_counter() if timing is not None else None | 172 | started = time.perf_counter() if timing is not None else None |
| 165 | for i in range(launches): | 173 | for i in range(launches): |
| 166 | sys.argv = [script, *[str(a) for a in args]] | 174 | sys.argv = [script, *[str(a) for a in args]] |
| 167 | try: | 175 | try: |
| 168 | - runpy.run_path(script, run_name="__main__") | 176 | + with capture_impl_imports(i == 0) as imported_paths: |
| 177 | + runpy.run_path(script, run_name="__main__") | ||
| 169 | except builtins.SystemExit as exc: | 178 | except builtins.SystemExit as exc: |
| 170 | # A script exit is a result, including a successful exit(None/0). | 179 | # A script exit is a result, including a successful exit(None/0). |
| 171 | code = exc.code | 180 | code = exc.code |
| @@ -185,26 +194,57 @@ def run(script, args, launches, block_dim=None, timing=None): | |||
| 185 | if i == 0: | 194 | if i == 0: |
| 186 | err.write(FIRST_CALL_MARKER + "\n") | 195 | err.write(FIRST_CALL_MARKER + "\n") |
| 187 | err.flush() | 196 | err.flush() |
| 188 | - report_impl_modules(out) | 197 | + report_impl_modules(out, imported_paths) |
| 189 | out.write((LAUNCH_MARKER % (i + 1, launches)) + "\n") | 198 | out.write((LAUNCH_MARKER % (i + 1, launches)) + "\n") |
| 190 | out.flush() | 199 | out.flush() |
| 191 | return 0 | 200 | return 0 |
| 192 | 201 | ||
| 193 | 202 | ||
| 194 | -def report_impl_modules(out): | 203 | +@contextmanager |
| 204 | +def capture_impl_imports(enabled): | ||
| 205 | + """Observe source loads on the first launch, including modules removed from the import cache.""" | ||
| 206 | + paths = set() | ||
| 207 | + if not enabled or not os.environ.get(PROGRAM_IMPL_ENV): | ||
| 208 | + yield paths | ||
| 209 | + return | ||
| 210 | + original = SourceFileLoader.exec_module | ||
| 211 | + | ||
| 212 | + def observed(loader, module): | ||
| 213 | + result = original(loader, module) | ||
| 214 | + paths.add((loader.name, module.__package__, loader.path)) | ||
| 215 | + return result | ||
| 216 | + | ||
| 217 | + SourceFileLoader.exec_module = observed | ||
| 218 | + try: | ||
| 219 | + yield paths | ||
| 220 | + finally: | ||
| 221 | + SourceFileLoader.exec_module = original | ||
| 222 | + | ||
| 223 | + | ||
| 224 | +def report_impl_modules(out, imported_paths=()): | ||
| 195 | """Report loaded implementation paths and hashes after launch. Diagnostic failures are nonfatal.""" | 225 | """Report loaded implementation paths and hashes after launch. Diagnostic failures are nonfatal.""" |
| 196 | staged = os.environ.get(IMPL_ENV) | 226 | staged = os.environ.get(IMPL_ENV) |
| 197 | if not staged: | 227 | if not staged: |
| 198 | return | 228 | return |
| 199 | try: | 229 | try: |
| 230 | + program_paths = json.loads(os.environ.get(PROGRAM_IMPL_ENV, "[]")) | ||
| 231 | + want = {os.path.basename(p) for p in program_paths} if program_paths else {os.path.basename(staged)} | ||
| 200 | seen = set() | 232 | seen = set() |
| 201 | - paths = [getattr(module, "__file__", None) for module in list(sys.modules.values())] | 233 | + modules = [(name, getattr(module, "__package__", None), getattr(module, "__file__", None)) |
| 202 | - for path in paths: | 234 | + for name, module in list(sys.modules.items())] |
| 203 | - real = os.path.realpath(path) if path and os.path.basename(path) == os.path.basename(staged) else None | 235 | + reported = set() |
| 204 | - if real and real not in seen: | 236 | + for name, package, path in [*modules, *imported_paths]: |
| 205 | - seen.add(real) | 237 | + if not isinstance(path, str) or os.path.basename(path) not in want: |
| 206 | - digest = hashlib.sha256(Path(real).read_bytes()).hexdigest() | 238 | + continue |
| 207 | - out.write((IMPL_MARKER % (digest[:8], real)) + "\n") | 239 | + real = os.path.realpath(path) |
| 240 | + if program_paths and (name, real) not in reported: | ||
| 241 | + out.write(MODULE_MARKER + json.dumps([name, package, real]) + "\n") | ||
| 242 | + reported.add((name, real)) | ||
| 243 | + if real in seen: | ||
| 244 | + continue | ||
| 245 | + seen.add(real) | ||
| 246 | + digest = hashlib.sha256(Path(real).read_bytes()).hexdigest() | ||
| 247 | + out.write((IMPL_MARKER % (digest if program_paths else digest[:8], real)) + "\n") | ||
| 208 | out.flush() | 248 | out.flush() |
| 209 | except Exception: # noqa: BLE001 -- a diagnostic only | 249 | except Exception: # noqa: BLE001 -- a diagnostic only |
| 210 | pass | 250 | pass |
| @@ -19,6 +19,7 @@ from evaluation.measure_latency import campaign_command, measure | |||
| 19 | from evaluation.repeat_runner import loopable | 19 | from evaluation.repeat_runner import loopable |
| 20 | from evaluation.workspace_probe import SPACES, validate_capacity | 20 | from evaluation.workspace_probe import SPACES, validate_capacity |
| 21 | from source_analysis.runtime_files import check_files, file_digest as sha | 21 | from source_analysis.runtime_files import check_files, file_digest as sha |
| 22 | +from source_analysis.program_bundle import runtime_spec | ||
| 22 | import jsonio | 23 | import jsonio |
| 23 | 24 | ||
| 24 | 25 | ||
| @@ -56,20 +57,36 @@ def _profile_files(reading): | |||
| 56 | 57 | ||
| 57 | 58 | ||
| 58 | def bind_timing_target(contract, reading): | 59 | def bind_timing_target(contract, reading): |
| 59 | - if contract["op_name"] is not None: | 60 | + if contract["op_name"] == "*": |
| 61 | + tasks = reading.get("tasks_per_call") | ||
| 62 | + if not tasks or not isinstance(tasks, dict) or any(type(n) is not int or n < 1 for n in tasks.values()): | ||
| 63 | + raise ValueError("package timing target needs the measured task counts per call") | ||
| 64 | + target = {"tasks_per_call": tasks} | ||
| 65 | + elif contract["op_name"] is None: | ||
| 66 | + name, count = reading.get("op_name"), reading.get("rows_per_call") | ||
| 67 | + valid_name = isinstance(name, str) and name.strip() and name != "*" | ||
| 68 | + if not valid_name or type(count) is not int or count < 1: | ||
| 69 | + raise ValueError("auto-detected timing target needs an operator name and a positive task count per call") | ||
| 70 | + target = {"op_name": name, "rows_per_call": count} | ||
| 71 | + else: | ||
| 60 | return contract | 72 | return contract |
| 61 | - name, count = reading.get("op_name"), reading.get("rows_per_call") | ||
| 62 | - valid_name = isinstance(name, str) and name.strip() and name != "*" | ||
| 63 | - if not valid_name or type(count) is not int or count < 1: | ||
| 64 | - raise ValueError("auto-detected timing target needs an operator name and a positive task count per call") | ||
| 65 | - target = {"op_name": name, "rows_per_call": count} | ||
| 66 | if "timed_target" in contract and contract["timed_target"] != target: | 73 | if "timed_target" in contract and contract["timed_target"] != target: |
| 67 | - raise ValueError("auto-detected timing target differs from the frozen measurement") | 74 | + raise ValueError("timing target differs from the frozen measurement") |
| 68 | return dict(contract, timed_target=target) | 75 | return dict(contract, timed_target=target) |
| 69 | 76 | ||
| 70 | 77 | ||
| 71 | def campaign_contract(state): | 78 | def campaign_contract(state): |
| 72 | contract = state["measurement_contract"] | 79 | contract = state["measurement_contract"] |
| 80 | + if contract["op_name"] == "*" and "timed_target" not in contract: | ||
| 81 | + from evaluation.measure_latency import summarise | ||
| 82 | + | ||
| 83 | + baseline = state["nodes"]["closed"][0]["eval"]["m"] | ||
| 84 | + profile = baseline.get("msprof_dir") | ||
| 85 | + runs = contract["runs"] + contract["warmup"] | ||
| 86 | + observed = summarise(profile, "*", contract["warmup"], calls=runs) if profile else None | ||
| 87 | + if not observed or observed.error or observed.rows_per_call != baseline.get("rows_per_call"): | ||
| 88 | + raise ValueError("cannot recover the package timing target from the original baseline profile") | ||
| 89 | + return bind_timing_target(contract, {"tasks_per_call": observed.tasks_per_call}) | ||
| 73 | if contract["op_name"] is None and "timed_target" not in contract: | 90 | if contract["op_name"] is None and "timed_target" not in contract: |
| 74 | # Older campaigns retained both observed fields in the baseline node. | 91 | # Older campaigns retained both observed fields in the baseline node. |
| 75 | return bind_timing_target(contract, state["nodes"]["closed"][0]["eval"]["m"]) | 92 | return bind_timing_target(contract, state["nodes"]["closed"][0]["eval"]["m"]) |
| @@ -104,17 +121,28 @@ def acquire(args): | |||
| 104 | argv, cwd, environment = campaign_command(args.test_command, str(Path(args.op_dir).resolve()), args.device) | 121 | argv, cwd, environment = campaign_command(args.test_command, str(Path(args.op_dir).resolve()), args.device) |
| 105 | manifest = _test_manifest(args, argv, cwd, impl) | 122 | manifest = _test_manifest(args, argv, cwd, impl) |
| 106 | initial_hash = sha(impl) | 123 | initial_hash = sha(impl) |
| 124 | + program = runtime_spec(impl) | ||
| 125 | + if program: | ||
| 126 | + if args.op_name not in (None, "*"): | ||
| 127 | + raise ValueError("multi-file programs must measure all AI-Core task names, not one member") | ||
| 128 | + args.op_name = "*" | ||
| 107 | profile_root = Path(args.op_dir).resolve() / "optimization" / "profiles" | 129 | profile_root = Path(args.op_dir).resolve() / "optimization" / "profiles" |
| 108 | profile_root.mkdir(parents=True, exist_ok=True) | 130 | profile_root.mkdir(parents=True, exist_ok=True) |
| 109 | reading = measure(argv, warmup=2, runs=9, agg="median", op_dir=cwd, op_name=args.op_name, timeout_s=args.timeout, | 131 | reading = measure(argv, warmup=2, runs=9, agg="median", op_dir=cwd, op_name=args.op_name, timeout_s=args.timeout, |
| 110 | impl_path=impl, keep_prof=True, prof_root=str(profile_root), env=environment, | 132 | impl_path=impl, keep_prof=True, prof_root=str(profile_root), env=environment, |
| 111 | joint_correctness=True, budget=capacity, address_limits=address_limits) | 133 | joint_correctness=True, budget=capacity, address_limits=address_limits) |
| 112 | check_files({**manifest, impl: initial_hash}, "source or frozen precision files changed during acquisition") | 134 | check_files({**manifest, impl: initial_hash}, "source or frozen precision files changed during acquisition") |
| 135 | + if runtime_spec(impl) != program: | ||
| 136 | + raise RuntimeError("runtime program changed during acquisition") | ||
| 113 | reading.update(profile_files=_profile_files(reading), schema="panko-pro-npu-v1", code_hash=initial_hash, | 137 | reading.update(profile_files=_profile_files(reading), schema="panko-pro-npu-v1", code_hash=initial_hash, |
| 114 | - program_files={impl: initial_hash}, | 138 | + program_files=program["files"] if program else {impl: initial_hash}, |
| 115 | - contract={"test_files": manifest, "argv": argv, "cwd": cwd, "env": environment, | 139 | + contract={"test_files": manifest, "argv": argv, "cwd": cwd, |
| 116 | - "device": str(args.device), "op_name": args.op_name, "warmup": 2, "runs": 9, | 140 | + "env": environment, "device": str(args.device), |
| 117 | - "memory_capacity": capacity, "program": None, "metric": "msprof Task Duration(us)"}) | 141 | + "op_name": args.op_name, "warmup": 2, "runs": 9, |
| 142 | + "memory_capacity": capacity, | ||
| 143 | + "program": ({k: program[k] for k in ("root", "required")} | { | ||
| 144 | + "files": sorted(program["files"])}) if program else None, | ||
| 145 | + "metric": "msprof Task Duration(us)"}) | ||
| 118 | if address_limits is not None: | 146 | if address_limits is not None: |
| 119 | reading["contract"]["address_limits"] = address_limits | 147 | reading["contract"]["address_limits"] = address_limits |
| 120 | if reading.get("p") is not None: | 148 | if reading.get("p") is not None: |
| @@ -30,6 +30,7 @@ register(pro_backend) | |||
| 30 | from panko.config import out | 30 | from panko.config import out |
| 31 | from panko.state import load, file_hash | 31 | from panko.state import load, file_hash |
| 32 | from source_analysis.runtime_files import check_files | 32 | from source_analysis.runtime_files import check_files |
| 33 | +from source_analysis import program_bundle | ||
| 33 | from evaluation.measure_latency import LATENCY_DECIMALS | 34 | from evaluation.measure_latency import LATENCY_DECIMALS |
| 34 | from evaluation.repeat_runner import split_script_command | 35 | from evaluation.repeat_runner import split_script_command |
| 35 | from evaluation.workspace_probe import profile_workspace, validate_capacity | 36 | from evaluation.workspace_probe import profile_workspace, validate_capacity |
| @@ -122,6 +123,16 @@ def _check_workspace(receipt, impl, contract, allow_partial): | |||
| 122 | raise ValueError("on-chip memory reading is missing or differs from the measured source") | 123 | raise ValueError("on-chip memory reading is missing or differs from the measured source") |
| 123 | 124 | ||
| 124 | 125 | ||
| 126 | +def _bind_recorded_timing(contract, receipt): | ||
| 127 | + profile = _timing_profile(receipt) | ||
| 128 | + if contract["op_name"] == "*": | ||
| 129 | + tasks = profile.tasks_per_call | ||
| 130 | + if receipt.get("tasks_per_call", tasks) != tasks: | ||
| 131 | + raise ValueError("package timing target differs from the timing CSV") | ||
| 132 | + return bind_timing_target(contract, {"tasks_per_call": tasks}) | ||
| 133 | + return bind_timing_target(contract, receipt) | ||
| 134 | + | ||
| 135 | + | ||
| 125 | def _validate_reading(receipt, impl, require_success, *, timing_only=False, runs=9, allow_partial_workspace=False): | 136 | def _validate_reading(receipt, impl, require_success, *, timing_only=False, runs=9, allow_partial_workspace=False): |
| 126 | schema = "panko-pro-verification-v1" if timing_only else "panko-pro-npu-v1" | 137 | schema = "panko-pro-verification-v1" if timing_only else "panko-pro-npu-v1" |
| 127 | if not isinstance(receipt, dict) or receipt.get("schema") != schema: | 138 | if not isinstance(receipt, dict) or receipt.get("schema") != schema: |
| @@ -133,18 +144,20 @@ def _validate_reading(receipt, impl, require_success, *, timing_only=False, runs | |||
| 133 | raise ValueError("measurement has no frozen precision-test manifest") | 144 | raise ValueError("measurement has no frozen precision-test manifest") |
| 134 | check_files(contract["test_files"], "frozen precision input changed or missing") | 145 | check_files(contract["test_files"], "frozen precision input changed or missing") |
| 135 | passed = receipt.get("correctness_passed") is True | 146 | passed = receipt.get("correctness_passed") is True |
| 136 | - expected_files = {str(Path(impl).resolve()): file_hash(impl)} | 147 | + spec = program_bundle.runtime_spec(impl) |
| 148 | + expected_files = spec["files"] if spec else {str(Path(impl).resolve()): file_hash(impl)} | ||
| 137 | if receipt.get("program_files") != expected_files: | 149 | if receipt.get("program_files") != expected_files: |
| 138 | raise ValueError("receipt does not cover the complete runtime program") | 150 | raise ValueError("receipt does not cover the complete runtime program") |
| 151 | + if spec and contract.get("op_name") != "*": | ||
| 152 | + raise ValueError("package measurements must include all AI-Core tasks") | ||
| 139 | if require_success or passed: | 153 | if require_success or passed: |
| 140 | _check_latency(receipt, passed, runs) | 154 | _check_latency(receipt, passed, runs) |
| 141 | - contract = bind_timing_target(contract, receipt) | ||
| 142 | _check_workspace(receipt, impl, contract, timing_only or allow_partial_workspace) | 155 | _check_workspace(receipt, impl, contract, timing_only or allow_partial_workspace) |
| 143 | profiles = receipt.get("profile_files") | 156 | profiles = receipt.get("profile_files") |
| 144 | if not profiles or not any(name.endswith(".csv") for name in profiles): | 157 | if not profiles or not any(name.endswith(".csv") for name in profiles): |
| 145 | raise ValueError("raw profile evidence is required") | 158 | raise ValueError("raw profile evidence is required") |
| 146 | check_files(profiles, "profile evidence changed or missing") | 159 | check_files(profiles, "profile evidence changed or missing") |
| 147 | - _timing_profile(receipt) | 160 | + contract = _bind_recorded_timing(contract, receipt) |
| 148 | elif not receipt.get("test_failed") or receipt.get("p") is not None: | 161 | elif not receipt.get("test_failed") or receipt.get("p") is not None: |
| 149 | raise ValueError("acquisition failure is not an incorrect candidate; keep the evidence and retry later") | 162 | raise ValueError("acquisition failure is not an incorrect candidate; keep the evidence and retry later") |
| 150 | return contract | 163 | return contract |
| @@ -166,6 +179,18 @@ def _bind_repair(args, config): | |||
| 166 | raise Refusal(4) from exc | 179 | raise Refusal(4) from exc |
| 167 | 180 | ||
| 168 | 181 | ||
| 182 | +def _check_manifest(args): | ||
| 183 | + if args.program_manifest: | ||
| 184 | + manifest = json.loads(Path(args.program_manifest).read_text()) | ||
| 185 | + program = pro_backend.ACTIVE_PROGRAM | ||
| 186 | + if not program or any(manifest.get(k) != v for k, v in program.items()): | ||
| 187 | + raise ValueError("program manifest differs from the staged runtime package") | ||
| 188 | + if manifest.get("view_sha256") != file_hash(args.op_file) or any( | ||
| 189 | + manifest.get("sha256", {}).get(rel) != file_hash(Path(program["root"]) / rel) for rel in program["files"] | ||
| 190 | + ): | ||
| 191 | + raise ValueError("program manifest hashes differ from the staged sources") | ||
| 192 | + | ||
| 193 | + | ||
| 169 | def _check_original_command(args, contract): | 194 | def _check_original_command(args, contract): |
| 170 | import pro_init_repair as init_repair | 195 | import pro_init_repair as init_repair |
| 171 | from evaluation.measure_latency import check_campaign_command, test_argv | 196 | from evaluation.measure_latency import check_campaign_command, test_argv |
| @@ -192,8 +217,10 @@ def _before_init(args, receipt): | |||
| 192 | raise ValueError("base-release settings cannot enable deferred features: " + ", ".join(sorted(unsupported))) | 217 | raise ValueError("base-release settings cannot enable deferred features: " + ", ".join(sorted(unsupported))) |
| 193 | args.pro_measurement_contract = _validate_reading(receipt, args.op_file, True) | 218 | args.pro_measurement_contract = _validate_reading(receipt, args.op_file, True) |
| 194 | split_script_command(args.pro_measurement_contract["argv"]) | 219 | split_script_command(args.pro_measurement_contract["argv"]) |
| 220 | + pro_backend.ACTIVE_PROGRAM = program_bundle.attached(args.op_file) | ||
| 195 | capacity = args.pro_measurement_contract["memory_capacity"] | 221 | capacity = args.pro_measurement_contract["memory_capacity"] |
| 196 | contract = args.pro_measurement_contract | 222 | contract = args.pro_measurement_contract |
| 223 | + _check_manifest(args) | ||
| 197 | if args.preopt_s != 1 or args.preopt_p != receipt["p"] or args.preopt_hash != receipt["code_hash"]: | 224 | if args.preopt_s != 1 or args.preopt_p != receipt["p"] or args.preopt_hash != receipt["code_hash"]: |
| 198 | raise ValueError("baseline arguments differ from measurement") | 225 | raise ValueError("baseline arguments differ from measurement") |
| 199 | if args.op_name and args.op_name != contract["op_name"]: | 226 | if args.op_name and args.op_name != contract["op_name"]: |
| @@ -231,6 +258,7 @@ def _timing_profile(receipt): | |||
| 231 | reading = summarise(profile, contract["op_name"], warmup, calls=warmup + contract["runs"]) | 258 | reading = summarise(profile, contract["op_name"], warmup, calls=warmup + contract["runs"]) |
| 232 | if list(reading.samples) != receipt["samples"]: | 259 | if list(reading.samples) != receipt["samples"]: |
| 233 | raise ValueError("measurement samples differ from the timing CSV") | 260 | raise ValueError("measurement samples differ from the timing CSV") |
| 261 | + return reading | ||
| 234 | 262 | ||
| 235 | 263 | ||
| 236 | def _remeasurement_profile(receipt, entry): | 264 | def _remeasurement_profile(receipt, entry): |
| @@ -284,6 +312,9 @@ def _campaign_state(args): | |||
| 284 | state = load(args.op_dir) | 312 | state = load(args.op_dir) |
| 285 | if state.get("backend") != "pypto-pro-base-v2": | 313 | if state.get("backend") != "pypto-pro-base-v2": |
| 286 | raise ValueError("this entrypoint requires a base-release Pro campaign") | 314 | raise ValueError("this entrypoint requires a base-release Pro campaign") |
| 315 | + pro_backend.ACTIVE_PROGRAM = state.get("program") | ||
| 316 | + if pro_backend.ACTIVE_PROGRAM and args.cmd not in ("step", "stop"): | ||
| 317 | + program_bundle.require_current(pro_backend.ACTIVE_PROGRAM) | ||
| 287 | for name, expected in state["measurement_contract"]["test_files"].items(): | 318 | for name, expected in state["measurement_contract"]["test_files"].items(): |
| 288 | if file_hash(name) != expected: | 319 | if file_hash(name) != expected: |
| 289 | raise ValueError("frozen precision input changed: " + name) | 320 | raise ValueError("frozen precision input changed: " + name) |
| @@ -333,7 +364,7 @@ def _before_record(args, state, receipt): | |||
| 333 | if receipt.get("p") is None: | 364 | if receipt.get("p") is None: |
| 334 | expected = {k: v for k, v in expected.items() if k != "timed_target"} | 365 | expected = {k: v for k, v in expected.items() if k != "timed_target"} |
| 335 | if contract.get("timed_target") != expected.get("timed_target"): | 366 | if contract.get("timed_target") != expected.get("timed_target"): |
| 336 | - raise ValueError("auto-detected timing target differs from the baseline") | 367 | + raise ValueError("timing target differs from the baseline") |
| 337 | if contract != expected: | 368 | if contract != expected: |
| 338 | raise ValueError("measurement command, device, profiler settings or precision inputs changed") | 369 | raise ValueError("measurement command, device, profiler settings or precision inputs changed") |
| 339 | if remeasure: | 370 | if remeasure: |
| @@ -46,15 +46,42 @@ def state_metadata(args): | |||
| 46 | source = Path(args.op_file).read_text() | 46 | source = Path(args.op_file).read_text() |
| 47 | return {"wrapper_owned_bindings": discover_owned_bindings(source, args.pro_context), | 47 | return {"wrapper_owned_bindings": discover_owned_bindings(source, args.pro_context), |
| 48 | "wrapper_signature": wrapper_signature(source, args.pro_context), "case_context": args.pro_context, | 48 | "wrapper_signature": wrapper_signature(source, args.pro_context), "case_context": args.pro_context, |
| 49 | - "backend": "pypto-pro-base-v2", "measurement_contract": args.pro_measurement_contract} | 49 | + "backend": "pypto-pro-base-v2", "measurement_contract": args.pro_measurement_contract, |
| 50 | + "program": ACTIVE_PROGRAM} | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +ACTIVE_PROGRAM = None | ||
| 50 | 54 | ||
| 51 | 55 | ||
| 52 | def write_source(path, source): | 56 | def write_source(path, source): |
| 53 | - write_runtime_file(Path(path), source.encode("utf-8")) | 57 | + from source_analysis import program_bundle |
| 58 | + if ACTIVE_PROGRAM: | ||
| 59 | + if Path(path).resolve() != Path(ACTIVE_PROGRAM['view']).resolve(): | ||
| 60 | + raise ValueError('working view differs from the campaign') | ||
| 61 | + program_bundle.write_candidate(ACTIVE_PROGRAM, source) | ||
| 62 | + else: | ||
| 63 | + write_runtime_file(Path(path), source.encode("utf-8")) | ||
| 54 | 64 | ||
| 55 | 65 | ||
| 56 | def export_source(source, destination): | 66 | def export_source(source, destination): |
| 57 | - write_runtime_file(Path(destination), Path(source).read_bytes()) | 67 | + from source_analysis import program_bundle |
| 68 | + from source_analysis.program_view import HEADER | ||
| 69 | + data = Path(source).read_bytes() | ||
| 70 | + if data.startswith(HEADER.encode("utf-8")): | ||
| 71 | + original = ACTIVE_PROGRAM or program_bundle.attached(source) | ||
| 72 | + root = Path(str(destination) + ".program") | ||
| 73 | + if root.is_symlink(): | ||
| 74 | + raise ValueError("export directory cannot be a symlink") | ||
| 75 | + namespace = original.get("package") or program_bundle.package_namespace(Path(original["root"])) | ||
| 76 | + if namespace: | ||
| 77 | + parts = namespace.split(".") | ||
| 78 | + if not all(part.isidentifier() for part in parts): | ||
| 79 | + raise ValueError("invalid export package name") | ||
| 80 | + root = program_bundle.member(root, Path(*parts) / "__init__.py").parent | ||
[P2] Preserve enclosing package initialization in exports What this is: Export must preserve the package needed to run a retained candidate independently of the original source directory. Problem: A nested package root is accepted with namespace Fix: Include and hash the required enclosing-package initialization files, or reject this incomplete root before starting the campaign and require the enclosing package as the root. Add a round-trip test with a nested package that reads a value from its parent initializer, then move the original package away before checking the export. If skipped: A candidate that passes acquisition and reaches STOP can become unusable after export or relocation. Reviewed head: ![]() ![]() | |||
| 81 | + target = dict(original, root=str(root), view=str(destination)) | ||
| 82 | + program_bundle.write_candidate(target, data.decode("utf-8"), exporting=True) | ||
| 83 | + else: | ||
| 84 | + write_runtime_file(Path(destination), data) | ||
| 58 | 85 | ||
| 59 | 86 | ||
| 60 | def verification_policy(): | 87 | def verification_policy(): |
| @@ -18,6 +18,8 @@ from panko import selection, state | |||
| 18 | from panko.config import call_transition, out, Refusal | 18 | from panko.config import call_transition, out, Refusal |
| 19 | from pro_persistence import atomic_write | 19 | from pro_persistence import atomic_write |
| 20 | from panko.stopping import stop_condition | 20 | from panko.stopping import stop_condition |
| 21 | +from source_analysis import program_bundle | ||
| 22 | +import pro_backend | ||
| 21 | 23 | ||
| 22 | 24 | ||
| 23 | def check_command(a, st): | 25 | def check_command(a, st): |
| @@ -128,6 +130,9 @@ def step(a, _before, _receipt_args, configure): | |||
| 128 | ): | 130 | ): |
| 129 | raise ValueError("candidate has no matching selected action") | 131 | raise ValueError("candidate has no matching selected action") |
| 130 | check_command(a, st) | 132 | check_command(a, st) |
| 133 | + if pro_backend.ACTIVE_PROGRAM: | ||
| 134 | + program_bundle.refresh_program(pro_backend.ACTIVE_PROGRAM, preserve_current=True) | ||
| 135 | + program_bundle.require_current(pro_backend.ACTIVE_PROGRAM) | ||
| 131 | root.mkdir(parents=True, exist_ok=True) | 136 | root.mkdir(parents=True, exist_ok=True) |
| 132 | if not saved: | 137 | if not saved: |
| 133 | atomic_write(journal, json.dumps({"request": key})) | 138 | atomic_write(journal, json.dumps({"request": key})) |
| @@ -23,7 +23,8 @@ from panko.config import VERIFY_ALPHA, VERIFY_BOOT, Refusal, out | |||
| 23 | from panko.measurement import bootstrap_speedup as native_interval, median_of as median | 23 | from panko.measurement import bootstrap_speedup as native_interval, median_of as median |
| 24 | from evaluation.measure_latency import measure | 24 | from evaluation.measure_latency import measure |
| 25 | from source_analysis.runtime_files import check_files, file_digest | 25 | from source_analysis.runtime_files import check_files, file_digest |
| 26 | -from measure import bind_timing_target, campaign_contract | 26 | +from source_analysis import program_bundle |
| 27 | +from measure import _profile_files, bind_timing_target, campaign_contract | ||
| 27 | 28 | ||
| 28 | READING_SIGMA_LOG = 0.02 / math.sqrt(2) | 29 | READING_SIGMA_LOG = 0.02 / math.sqrt(2) |
| 29 | 30 | ||
| @@ -36,7 +37,13 @@ def bootstrap_speedup(pre, dele, n_boot, alpha): | |||
| 36 | 37 | ||
| 37 | 38 | ||
| 38 | def matches(directory, filename, wanted): | 39 | def matches(directory, filename, wanted): |
| 40 | + import pro_backend | ||
| 41 | + | ||
| 39 | try: | 42 | try: |
| 43 | + if pro_backend.ACTIVE_PROGRAM: | ||
| 44 | + program_bundle.require_current(pro_backend.ACTIVE_PROGRAM) | ||
| 45 | + else: | ||
| 46 | + program_bundle.runtime_spec(filename) | ||
| 40 | return file_digest(filename) == wanted | 47 | return file_digest(filename) == wanted |
| 41 | except (OSError, KeyError, ValueError): | 48 | except (OSError, KeyError, ValueError): |
| 42 | return False | 49 | return False |
| @@ -67,18 +74,21 @@ def auto(args): | |||
| 67 | out(reply) | 74 | out(reply) |
| 68 | 75 | ||
| 69 | 76 | ||
| 70 | -def _measure_arm(args, st, filename, prompt, root): | 77 | +def _measure_arm(st, prompt, root): |
| 78 | + """Acquire one staged arm and bind its receipt to the verified runtime and profile files.""" | ||
| 79 | + filename = prompt["op_file"] | ||
| 71 | c = campaign_contract(st) | 80 | c = campaign_contract(st) |
| 72 | device = str(c["device"]) | 81 | device = str(c["device"]) |
| 73 | if c["env"].get("TILE_FWK_DEVICE_ID", os.environ.get("TILE_FWK_DEVICE_ID")) != device: | 82 | if c["env"].get("TILE_FWK_DEVICE_ID", os.environ.get("TILE_FWK_DEVICE_ID")) != device: |
| 74 | raise ValueError("activate the frozen campaign device before verification") | 83 | raise ValueError("activate the frozen campaign device before verification") |
| 75 | 84 | ||
| 76 | def check_inputs(): | 85 | def check_inputs(): |
| 77 | - if not matches(args.op_dir, filename, prompt["code_hash"]): | 86 | + if file_digest(filename) != prompt["code_hash"]: |
| 78 | raise ValueError("staged program identity changed") | 87 | raise ValueError("staged program identity changed") |
| 79 | check_files(c["test_files"], "frozen test input changed") | 88 | check_files(c["test_files"], "frozen test input changed") |
| 89 | + return program_bundle.runtime_spec(filename) | ||
| 80 | 90 | ||
| 81 | - check_inputs() | 91 | + program = check_inputs() |
| 82 | metrics = measure( | 92 | metrics = measure( |
| 83 | c["argv"], | 93 | c["argv"], |
| 84 | warmup=c["warmup"], | 94 | warmup=c["warmup"], |
| @@ -94,7 +104,8 @@ def _measure_arm(args, st, filename, prompt, root): | |||
| 94 | prof_root=str(root), | 104 | prof_root=str(root), |
| 95 | joint_correctness=True, | 105 | joint_correctness=True, |
| 96 | ) | 106 | ) |
| 97 | - check_inputs() | 107 | + if check_inputs() != program: |
| 108 | + raise ValueError("runtime program changed during verification acquisition") | ||
| 98 | samples = metrics.get("samples") or [] | 109 | samples = metrics.get("samples") or [] |
| 99 | correct = metrics.get("correctness_passed") is True and bool(metrics.get("impl_modules_seen")) | 110 | correct = metrics.get("correctness_passed") is True and bool(metrics.get("impl_modules_seen")) |
| 100 | latency = not metrics.get("p_error") and metrics.get("p") is not None | 111 | latency = not metrics.get("p_error") and metrics.get("p") is not None |
| @@ -103,7 +114,10 @@ def _measure_arm(args, st, filename, prompt, root): | |||
| 103 | out(dict(error="verification_refused", reason=metrics.get("p_error") or "incomplete acquisition")) | 114 | out(dict(error="verification_refused", reason=metrics.get("p_error") or "incomplete acquisition")) |
| 104 | raise Refusal(3) | 115 | raise Refusal(3) |
| 105 | bind_timing_target(c, metrics) | 116 | bind_timing_target(c, metrics) |
| 106 | - metrics.update(step=prompt["stage"], code_hash=prompt["code_hash"], arm=prompt["arm"]) | 117 | + metrics.update(schema="panko-pro-verification-v1", step=prompt["stage"], arm=prompt["arm"], |
| 118 | + code_hash=prompt["code_hash"], point=st["verification"]["arms"]["delivered"]["code_hash"], | ||
| 119 | + contract=dict(c, runs=prompt["runs"]), profile_files=_profile_files(metrics), | ||
| 120 | + program_files=program["files"] if program else {str(Path(filename).resolve()): prompt["code_hash"]}) | ||
| 107 | return metrics | 121 | return metrics |
| 108 | 122 | ||
| 109 | 123 | ||
| @@ -123,8 +137,6 @@ def _resume_acquisition(op_dir, st): | |||
| 123 | 137 | ||
| 124 | def acquire_stage(args): | 138 | def acquire_stage(args): |
| 125 | """Measure the pending arm now and leave its submission to the caller.""" | 139 | """Measure the pending arm now and leave its submission to the caller.""" |
| 126 | - from measure import _profile_files | ||
| 127 | - | ||
| 128 | st = state.load(args.op_dir) | 140 | st = state.load(args.op_dir) |
| 129 | _resume_acquisition(args.op_dir, st) | 141 | _resume_acquisition(args.op_dir, st) |
| 130 | prompt = transition(args) | 142 | prompt = transition(args) |
| @@ -133,13 +145,8 @@ def acquire_stage(args): | |||
| 133 | return | 145 | return |
| 134 | root = Path(args.op_dir).resolve() / "optimization/verification" | 146 | root = Path(args.op_dir).resolve() / "optimization/verification" |
| 135 | root.mkdir(exist_ok=True) | 147 | root.mkdir(exist_ok=True) |
| 136 | - filename = prompt["op_file"] | 148 | + reading = _measure_arm(st, prompt, root) |
| 137 | - reading = _measure_arm(args, st, filename, prompt, root) | ||
| 138 | v = st["verification"] | 149 | v = st["verification"] |
| 139 | - reading.update(schema="panko-pro-verification-v1", point=v["arms"]["delivered"]["code_hash"], | ||
| 140 | - contract=dict(campaign_contract(st), runs=prompt["runs"]), | ||
| 141 | - program_files={str(Path(filename).resolve()): prompt["code_hash"]}, | ||
| 142 | - profile_files=_profile_files(reading)) | ||
| 143 | path = Path(reading["msprof_dir"]) / "verification-receipt.json" | 150 | path = Path(reading["msprof_dir"]) / "verification-receipt.json" |
| 144 | atomic_write(path, json.dumps(reading)) | 151 | atomic_write(path, json.dumps(reading)) |
| 145 | v["pending_receipt_sha256"] = _receipt_digest(reading) | 152 | v["pending_receipt_sha256"] = _receipt_digest(reading) |
| @@ -197,7 +204,7 @@ def run_auto(args): | |||
| 197 | if "stage" not in prompt: | 204 | if "stage" not in prompt: |
| 198 | out(dict(prompt, points=delivery.verdicts_by_point(state.load(args.op_dir)))) | 205 | out(dict(prompt, points=delivery.verdicts_by_point(state.load(args.op_dir)))) |
| 199 | return | 206 | return |
| 200 | - metrics = _measure_arm(args, st, filename, prompt, root) | 207 | + metrics = _measure_arm(state.load(args.op_dir), prompt, root) |
| 201 | transition(Namespace(op_dir=args.op_dir, samples=",".join(map(str, metrics["samples"])), receipt=metrics)) | 208 | transition(Namespace(op_dir=args.op_dir, samples=",".join(map(str, metrics["samples"])), receipt=metrics)) |
| 202 | finally: | 209 | finally: |
| 203 | try: | 210 | try: |
| @@ -0,0 +1,311 @@ | |||
| 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 | +"""Checkpoint and restore a local Python package as one optimization program.""" | ||
| 10 | +import sys | ||
| 11 | +from pathlib import Path | ||
| 12 | + | ||
| 13 | +if __package__ in (None, ""): | ||
| 14 | + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | ||
| 15 | + | ||
| 16 | +import argparse | ||
| 17 | +import ast | ||
| 18 | +import base64 | ||
| 19 | +import json | ||
| 20 | +import os | ||
| 21 | + | ||
| 22 | +from bootstrap import activate | ||
| 23 | +activate() | ||
| 24 | +import jsonio | ||
| 25 | +from source_analysis.runtime_files import cached_bytecode, check_files, digest, file_digest, stage_bytes | ||
| 26 | +from source_analysis.kernel_boundary import Boundary | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def inventory(root): | ||
| 30 | + files = [] | ||
| 31 | + for path in root.rglob('*.py'): | ||
| 32 | + relative = path.relative_to(root) | ||
| 33 | + if relative.parts[0] == 'optimization' or {'__pycache__', '.git'} & set(relative.parts): | ||
| 34 | + continue | ||
| 35 | + files.append(str(relative)) | ||
| 36 | + return sorted(files) | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def member(root, relative): | ||
| 40 | + rel = Path(relative) | ||
| 41 | + if rel.is_absolute() or '..' in rel.parts or rel.suffix != '.py': | ||
| 42 | + raise ValueError('program member must be a relative Python file: %s' % relative) | ||
| 43 | + path = root / rel | ||
| 44 | + if any(p.is_symlink() for p in [path, *list(path.parents)[:len(rel.parts) - 1]]): | ||
| 45 | + raise ValueError('program members cannot traverse symlinks: %s' % relative) | ||
| 46 | + if not path.resolve().is_relative_to(root.resolve()): | ||
| 47 | + raise ValueError('program member escapes root: %s' % relative) | ||
| 48 | + return path | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def plan(root): | ||
| 52 | + """Scan an existing package directory for Python files and JIT entry points. | ||
| 53 | + | ||
| 54 | + The returned manifest includes relative paths, SHA-256 hashes and target scopes. | ||
| 55 | + Files with syntax or decoding errors remain in the inventory with a diagnostic | ||
| 56 | + and contribute no targets. Unsafe member paths raise ValueError, and errors | ||
| 57 | + resolving the root or reading a file propagate to the caller. | ||
| 58 | + """ | ||
| 59 | + root = Path(root).resolve(strict=True) | ||
| 60 | + files = inventory(root) | ||
| 61 | + targets, diagnostics = [], [] | ||
| 62 | + for relative in files: | ||
| 63 | + path = member(root, relative) | ||
| 64 | + try: | ||
| 65 | + tree = ast.parse(path.read_bytes(), filename=relative) | ||
| 66 | + except (SyntaxError, UnicodeError) as exc: | ||
| 67 | + diagnostics.append({'file': relative, 'reason': str(exc)}) | ||
| 68 | + continue | ||
| 69 | + boundary = Boundary(tree) | ||
| 70 | + for entry in sorted(boundary.entries, key=lambda node: node.lineno): | ||
| 71 | + scope = boundary.scope_paths[entry] | ||
| 72 | + targets.append({'file': relative, 'entry': scope, | ||
| 73 | + 'case_context': {'__panko_active_scopes__': [scope]}}) | ||
| 74 | + return {'version': 1, 'root': str(root), 'files': files, | ||
| 75 | + 'sha256': {rel: file_digest(member(root, rel)) for rel in files}, | ||
| 76 | + 'targets': targets, 'diagnostics': diagnostics} | ||
| 77 | + | ||
| 78 | + | ||
| 79 | +def _view_path(root, path): | ||
| 80 | + path = Path(path).absolute() | ||
| 81 | + if path.is_symlink(): | ||
| 82 | + raise ValueError('analysis view cannot be a symlink') | ||
| 83 | + path = path.resolve() | ||
| 84 | + if path.is_relative_to(root) and path.relative_to(root).parts[:1] != ('optimization',): | ||
| 85 | + raise ValueError('place the analysis view outside the package or under optimization/') | ||
| 86 | + return path | ||
| 87 | + | ||
| 88 | + | ||
| 89 | +def package_namespace(root): | ||
| 90 | + """Return the import prefix at the original root, including enclosing Python packages.""" | ||
| 91 | + if not root.name.isidentifier(): | ||
| 92 | + return None | ||
| 93 | + parts = [root.name] | ||
| 94 | + for parent in root.parents: | ||
| 95 | + if not parent.name.isidentifier() or not (parent / '__init__.py').is_file(): | ||
| 96 | + break | ||
| 97 | + parts.append(parent.name) | ||
| 98 | + return '.'.join(reversed(parts)) | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +def prepare(root, view_path, required=None): | ||
| 102 | + """Build a joint view without changing a byte in any runtime source file.""" | ||
| 103 | + from source_analysis.program_view import ProgramView | ||
| 104 | + manifest = plan(root) | ||
| 105 | + if manifest['diagnostics']: | ||
| 106 | + raise ValueError('program contains unparseable sources: %s' % manifest['diagnostics']) | ||
| 107 | + root = Path(manifest['root']) | ||
| 108 | + path = _view_path(root, view_path) | ||
| 109 | + if path.exists(): | ||
| 110 | + raise ValueError('analysis view already exists; use refresh for an existing campaign') | ||
| 111 | + package = package_namespace(root) | ||
| 112 | + view = ProgramView({rel: member(root, rel).read_bytes().decode('utf-8') for rel in manifest['files']}, package) | ||
| 113 | + for target in manifest['targets']: | ||
| 114 | + head, *tail = target['entry'].split('/') | ||
| 115 | + target['view_entry'] = '/'.join([view.names[target['file']][head], *tail]) | ||
| 116 | + target['case_context'] = {'__panko_active_scopes__': [target['view_entry']]} | ||
| 117 | + required = sorted(set(required or [t['file'] for t in manifest['targets']])) | ||
| 118 | + if not required or not set(required) <= set(manifest['files']): | ||
| 119 | + raise ValueError('required runtime entry files must be present in the program') | ||
| 120 | + manifest.update(version=2, view=str(path), package=package, required=required, symbol_map=view.names, | ||
| 121 | + view_sha256=digest(view.source.encode('utf-8'))) | ||
| 122 | + path.parent.mkdir(parents=True, exist_ok=True) | ||
| 123 | + _write_runtime(_view_writes(manifest, view.source, view.files)) | ||
| 124 | + return manifest | ||
| 125 | + | ||
| 126 | + | ||
| 127 | +def _materialized(program, source): | ||
| 128 | + from source_analysis.program_view import ProgramView | ||
| 129 | + files = ProgramView.from_source(source).materialize(source) | ||
| 130 | + if sorted(files) != sorted(program['files']): | ||
| 131 | + raise ValueError('analysis-view inventory differs from campaign') | ||
| 132 | + return files | ||
| 133 | + | ||
| 134 | + | ||
| 135 | +def _view_writes(program, source, files): | ||
| 136 | + root = Path(program['root']) | ||
| 137 | + spec = {'root': str(root.resolve()), 'view_sha256': digest(source.encode('utf-8')), | ||
| 138 | + 'files': {str(member(root, rel).resolve()): digest(src.encode('utf-8')) for rel, src in files.items()}, | ||
| 139 | + 'required': [str(member(root, rel).resolve()) for rel in program['required']]} | ||
| 140 | + return [(Path(program['view']), source.encode('utf-8')), | ||
| 141 | + (Path(str(program['view']) + '.runtime.json'), json.dumps(spec, sort_keys=True).encode('utf-8'))] | ||
| 142 | + | ||
| 143 | + | ||
| 144 | +def joint_drift(program): | ||
| 145 | + try: | ||
| 146 | + root = Path(program['root']) | ||
| 147 | + if inventory(root) != sorted(program['files']): | ||
| 148 | + return 'program Python file inventory changed' | ||
| 149 | + source = Path(program['view']).read_text(encoding='utf-8') | ||
| 150 | + files = _materialized(program, source) | ||
| 151 | + for rel, src in files.items(): | ||
| 152 | + if member(root, rel).read_bytes() != src.encode('utf-8'): | ||
| 153 | + return 'program view is stale for %s; refresh after structural edits' % rel | ||
| 154 | + runtime_spec(program['view']) | ||
| 155 | + except (OSError, ValueError, KeyError, TypeError, SyntaxError, IndexError) as exc: | ||
| 156 | + return 'program view is invalid: %s' % exc | ||
| 157 | + return '' | ||
| 158 | + | ||
| 159 | + | ||
| 160 | +def _rollback_files(committed, retain, failure): | ||
| 161 | + errors = [] | ||
| 162 | + for path, old in reversed(committed): | ||
| 163 | + try: | ||
| 164 | + if old is None: | ||
| 165 | + path.unlink(missing_ok=True) | ||
| 166 | + else: | ||
| 167 | + os.replace(old, path) | ||
| 168 | + except OSError as exc: | ||
| 169 | + if old: | ||
| 170 | + retain.add(old) | ||
| 171 | + errors.append(f'{path}: {exc}; backup={old}') | ||
| 172 | + if errors: | ||
| 173 | + raise OSError('program rollback failed; ' + '; '.join(errors)) from failure | ||
| 174 | + | ||
| 175 | + | ||
| 176 | +def _cleanup_staged_files(staged, retain): | ||
| 177 | + for _path, new, old in staged: | ||
| 178 | + for temporary in (new, old): | ||
| 179 | + if temporary is not None and temporary not in retain: | ||
| 180 | + temporary.unlink(missing_ok=True) | ||
| 181 | + | ||
| 182 | + | ||
| 183 | +def _replace_files(writes): | ||
| 184 | + """Roll back failed replacements. Runtime hashes detect mixed files after a crash between renames.""" | ||
| 185 | + staged, committed = [], [] | ||
| 186 | + retain = set() | ||
| 187 | + try: | ||
| 188 | + for path, data in writes: | ||
| 189 | + new = stage_bytes(path, data) | ||
| 190 | + staged.append((path, new, None)) | ||
| 191 | + old = stage_bytes(path, path.read_bytes()) if path.exists() else None | ||
| 192 | + staged[-1] = (path, new, old) | ||
| 193 | + for path, new, old in staged: | ||
| 194 | + os.replace(new, path) | ||
| 195 | + committed.append((path, old)) | ||
| 196 | + except BaseException as failure: | ||
| 197 | + _rollback_files(committed, retain, failure) | ||
| 198 | + raise | ||
| 199 | + finally: | ||
| 200 | + _cleanup_staged_files(staged, retain) | ||
| 201 | + | ||
| 202 | + | ||
| 203 | +def _write_runtime(writes): | ||
| 204 | + changed = [(path, data) for path, data in writes if not path.exists() or path.read_bytes() != data] | ||
| 205 | + cached = [item for path, _ in changed for item in cached_bytecode(path)] | ||
| 206 | + for item in cached: | ||
| 207 | + item.unlink(missing_ok=True) | ||
| 208 | + _replace_files(changed) | ||
| 209 | + | ||
| 210 | + | ||
| 211 | +def write_candidate(program, source, *, exporting=False): | ||
| 212 | + """Validate all mappings before writing a TPE candidate to runtime modules.""" | ||
| 213 | + root = Path(program['root']) | ||
| 214 | + existing = set(inventory(root)) | ||
| 215 | + expected = set(program['files']) | ||
| 216 | + if existing - expected or (not exporting and existing != expected): | ||
| 217 | + raise ValueError('program inventory changed') | ||
| 218 | + files = _materialized(program, source) | ||
| 219 | + writes = [(member(root, rel), src.encode('utf-8')) for rel, src in files.items()] | ||
| 220 | + _write_runtime(writes + _view_writes(program, source, files)) | ||
| 221 | + | ||
| 222 | + | ||
| 223 | +def refresh(manifest_path): | ||
| 224 | + """Rebuild analysis after coordinated structural edits to the runtime files.""" | ||
| 225 | + return refresh_program(json.loads(Path(manifest_path).read_text(encoding='utf-8'))) | ||
| 226 | + | ||
| 227 | + | ||
| 228 | +def refresh_program(program, *, preserve_current=False): | ||
| 229 | + from source_analysis.program_view import ProgramView | ||
| 230 | + if program.get('version') != 2: | ||
| 231 | + raise ValueError('refresh requires a joint program manifest') | ||
| 232 | + root = Path(program['root']) | ||
| 233 | + if inventory(root) != sorted(program['files']): | ||
| 234 | + raise ValueError('program inventory changed') | ||
| 235 | + files = {rel: member(root, rel).read_bytes().decode('utf-8') for rel in program['files']} | ||
| 236 | + if preserve_current: | ||
| 237 | + source = Path(program['view']).read_text(encoding='utf-8') | ||
| 238 | + if _materialized(program, source) == files: | ||
| 239 | + return {'view': program['view'], 'code_hash': digest(source.encode('utf-8'))} | ||
| 240 | + view = ProgramView(files, program['package'] if 'package' in program else package_namespace(root)) | ||
| 241 | + _write_runtime(_view_writes(program, view.source, view.files)) | ||
| 242 | + return {'view': program['view'], 'code_hash': digest(view.source.encode('utf-8'))} | ||
| 243 | + | ||
| 244 | + | ||
| 245 | +def runtime_spec(view_path): | ||
| 246 | + """Validate staged runtime identity; a missing/stale manifest is a refusal.""" | ||
| 247 | + path = Path(view_path) | ||
| 248 | + source = path.read_text(encoding='utf-8') | ||
| 249 | + from source_analysis.program_view import HEADER, ProgramView | ||
| 250 | + if not source.startswith(HEADER): | ||
| 251 | + return None | ||
| 252 | + spec = json.loads(Path(str(path) + '.runtime.json').read_text(encoding='utf-8')) | ||
| 253 | + if spec['view_sha256'] != digest(source.encode('utf-8')): | ||
| 254 | + raise ValueError('runtime identity is stale') | ||
| 255 | + if not spec['required'] or not set(spec['required']) <= set(spec['files']): | ||
| 256 | + raise ValueError('invalid runtime entry identity') | ||
| 257 | + # Also bind the sidecar to the source-map payload, not just a self-reported hash. | ||
| 258 | + materialized = ProgramView.from_source(source).materialize(source) | ||
| 259 | + expected_files = {str(member(Path(spec['root']), rel).resolve()): digest( | ||
| 260 | + src.encode('utf-8')) for rel, src in materialized.items()} | ||
| 261 | + if spec['files'] != expected_files: | ||
| 262 | + raise ValueError('runtime identities differ from analysis view') | ||
| 263 | + check_files(spec['files'], 'runtime source changed') | ||
| 264 | + return spec | ||
| 265 | + | ||
| 266 | + | ||
| 267 | +def attached(view_path): | ||
| 268 | + """Recover the joint staging contract for direct evaluator API callers.""" | ||
| 269 | + spec = runtime_spec(view_path) | ||
| 270 | + if not spec: | ||
| 271 | + return None | ||
| 272 | + from source_analysis.program_view import ProgramView | ||
| 273 | + view = ProgramView.from_source(Path(view_path).read_text(encoding='utf-8')) | ||
| 274 | + root = Path(spec['root']) | ||
| 275 | + return {'version': 2, 'root': str(root), 'view': str(Path(view_path).resolve()), | ||
| 276 | + 'package': view.package or package_namespace(root), 'files': sorted(view.files), | ||
| 277 | + 'required': [str(Path(p).relative_to(root)) for p in spec['required']]} | ||
| 278 | + | ||
| 279 | + | ||
| 280 | +def require_current(program): | ||
| 281 | + reason = joint_drift(program) | ||
| 282 | + if reason: | ||
| 283 | + raise ValueError(reason) | ||
| 284 | + | ||
| 285 | + | ||
| 286 | +def main(): | ||
| 287 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 288 | + parser.add_argument('action', choices=['plan', 'prepare', 'refresh']) | ||
| 289 | + parser.add_argument('--root') | ||
| 290 | + parser.add_argument('--view') | ||
| 291 | + parser.add_argument('--manifest') | ||
| 292 | + parser.add_argument('--entry-file', action='append') | ||
| 293 | + args = parser.parse_args() | ||
| 294 | + if args.action == 'refresh': | ||
| 295 | + if not args.manifest: | ||
| 296 | + parser.error('refresh requires --manifest') | ||
| 297 | + result = refresh(args.manifest) | ||
| 298 | + elif args.action == 'prepare': | ||
| 299 | + if not args.root or not args.view or not args.manifest: | ||
| 300 | + parser.error('prepare requires --root, --view and --manifest') | ||
| 301 | + result = prepare(args.root, args.view, args.entry_file) | ||
| 302 | + Path(args.manifest).write_text(json.dumps(result, indent=2), encoding='utf-8') | ||
| 303 | + else: | ||
| 304 | + if not args.root: | ||
| 305 | + parser.error('plan requires --root') | ||
| 306 | + result = plan(args.root) | ||
| 307 | + jsonio.emit(result, indent=2) | ||
| 308 | + | ||
| 309 | + | ||
| 310 | +if __name__ == '__main__': | ||
| 311 | + main() | ||
| @@ -0,0 +1,616 @@ | |||
| 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 | +"""Map edits in a namespaced view to the original bytes. Rebuild the view after structural changes.""" | ||
| 10 | +import ast | ||
| 11 | +import base64 | ||
| 12 | +import json | ||
| 13 | +from functools import lru_cache | ||
| 14 | + | ||
| 15 | +from source_analysis.source_bindings import scope_nodes | ||
| 16 | +from source_analysis.tile_sites import Offsets | ||
| 17 | + | ||
| 18 | +HEADER = '# PANKO-PROGRAM-' | ||
| 19 | +DSL_IMPORTS = {'pl', 'vf', 'pypto', 'pypto_pro', 'torch', 'math', 'os', '_os'} | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def _stores(body): | ||
| 23 | + names = set() | ||
| 24 | + | ||
| 25 | + def visit(node): | ||
| 26 | + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): | ||
| 27 | + names.add(node.name) | ||
| 28 | + return | ||
| 29 | + if isinstance(node, (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp, ast.Lambda)): | ||
| 30 | + # Comprehension targets and lambda arguments have their own scope. | ||
| 31 | + for child in ast.walk(node): | ||
| 32 | + if isinstance(child, ast.NamedExpr): | ||
| 33 | + visit(child.target) | ||
| 34 | + return | ||
| 35 | + if isinstance(node, ast.ExceptHandler) and node.name: | ||
| 36 | + names.add(node.name) | ||
| 37 | + if isinstance(node, ast.Name) and isinstance(node.ctx, (ast.Store, ast.Del)): | ||
| 38 | + names.add(node.id) | ||
| 39 | + if isinstance(node, (ast.Import, ast.ImportFrom)): | ||
| 40 | + names.update(a.asname or (a.name.split('.')[0] if isinstance(node, ast.Import) else a.name) | ||
| 41 | + for a in node.names) | ||
| 42 | + for child in ast.iter_child_nodes(node): | ||
| 43 | + visit(child) | ||
| 44 | + for statement in body: | ||
| 45 | + visit(statement) | ||
| 46 | + return names | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +def _runtime_import_name(node, module, symbol): | ||
| 50 | + if not isinstance(node, ast.ImportFrom) or not node.level: | ||
| 51 | + return module | ||
| 52 | + parts = [node.module] if node.module else [] | ||
| 53 | + if symbol is None: | ||
| 54 | + parts.append(module.rsplit('.', 1)[-1]) | ||
| 55 | + return '.' * node.level + '.'.join(parts) | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +def _prior_package_exports(body, node): | ||
| 59 | + pending = {alias.name for alias in node.names} | ||
| 60 | + exports = set() | ||
| 61 | + for stmt in reversed(body[:body.index(node)]): | ||
| 62 | + if isinstance(stmt, ast.AnnAssign) and stmt.value is None: | ||
| 63 | + continue | ||
| 64 | + bound = pending.intersection(_stores([stmt])) | ||
| 65 | + if not bound: | ||
| 66 | + continue | ||
| 67 | + if isinstance(stmt, (ast.Import, ast.ImportFrom, ast.FunctionDef, ast.AsyncFunctionDef, | ||
| 68 | + ast.ClassDef, ast.Assign, ast.AnnAssign, ast.AugAssign)): | ||
| 69 | + exports.update(bound) | ||
| 70 | + elif not isinstance(stmt, ast.Delete): | ||
| 71 | + raise ValueError('conditional package binding needs explicit initialization: %s' % sorted(bound)) | ||
| 72 | + pending.difference_update(bound) | ||
| 73 | + if not pending: | ||
| 74 | + break | ||
| 75 | + return exports | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def _absolute_import_names(source): | ||
| 79 | + for node in ast.walk(ast.parse(source)): | ||
| 80 | + if isinstance(node, ast.ImportFrom) and not node.level: | ||
| 81 | + yield node.module | ||
| 82 | + for alias in node.names: | ||
| 83 | + yield node.module + '.' + alias.name | ||
| 84 | + elif isinstance(node, ast.Import): | ||
| 85 | + for alias in node.names: | ||
| 86 | + yield alias.name | ||
| 87 | + | ||
| 88 | + | ||
| 89 | +class _Rename(ast.NodeTransformer): | ||
| 90 | + def __init__(self, view, filename): | ||
| 91 | + self.view = view | ||
| 92 | + self.filename = filename | ||
| 93 | + self.mapping = view.names[filename] | ||
| 94 | + self.aliases = view.module_aliases[filename] | ||
| 95 | + self.scopes = [] | ||
| 96 | + | ||
| 97 | + def global_name(self, name): | ||
| 98 | + for local, declared_global in reversed(self.scopes): | ||
| 99 | + if name in declared_global: | ||
| 100 | + return True | ||
| @@ -14,8 +14,12 @@ import tempfile | |||
| 14 | from pathlib import Path | 14 | from pathlib import Path |
| 15 | 15 | ||
| 16 | 16 | ||
| 17 | +def digest(data): | ||
| 18 | + return hashlib.sha256(data).hexdigest() | ||
| 19 | + | ||
| 20 | + | ||
| 17 | def file_digest(path): | 21 | def file_digest(path): |
| 18 | - return hashlib.sha256(Path(path).read_bytes()).hexdigest() | 22 | + return digest(Path(path).read_bytes()) |
| 19 | 23 | ||
| 20 | 24 | ||
| 21 | def check_files(manifest, reason): | 25 | def check_files(manifest, reason): |
| @@ -14,7 +14,7 @@ permission: | |||
| 14 | 14 | ||
| 15 | 用户明确选择 PANKO 时,由主代理串行派工。将实际 campaign 目录、输入、测量合同和用户授权交 `pypto-pro-op-auto-tuner-panko`。新任务执行 INIT,续跑传 `resume:true`。 | 15 | 用户明确选择 PANKO 时,由主代理串行派工。将实际 campaign 目录、输入、测量合同和用户授权交 `pypto-pro-op-auto-tuner-panko`。新任务执行 INIT,续跑传 `resume:true`。 |
| 16 | - 收到 `ask_user` 时转交原问题和选项,等待回答并交回 autotuner。 | 16 | - 收到 `ask_user` 时转交原问题和选项,等待回答并交回 autotuner。 |
| 17 | -- 收到 CODE 时,若 `coder:false` 则直接回 autotuner;否则将编辑目标和约束交 `pypto-pro-op-coder`,把完整结果、原 CODE 元数据和 action ID 交回 autotuner。JIT 函数须在同一源码文件中。 | 17 | +- 收到 CODE 时,若 `coder:false` 则直接回 autotuner;否则将编辑目标和约束交 `pypto-pro-op-coder`,把完整结果、原 CODE 元数据和 action ID 交回 autotuner。保留包的导入与布局。 |
| 18 | - 重复或无效应答由 autotuner 核对磁盘状态;暂停或阻断时保留预算和进度。各 case 使用独立 campaign 和基线。 | 18 | - 重复或无效应答由 autotuner 核对磁盘状态;暂停或阻断时保留预算和进度。各 case 使用独立 campaign 和基线。 |
| 19 | - 真实 harness STOP 后,将 `verification_request` 交 `pypto-pro-op-verifier`;请求缺失或检查失败则交回 autotuner,独立 PASS 后才报告完成。 | 19 | - 真实 harness STOP 后,将 `verification_request` 交 `pypto-pro-op-verifier`;请求缺失或检查失败则交回 autotuner,独立 PASS 后才报告完成。 |
| 20 | 20 | ||
| @@ -1,6 +1,6 @@ | |||
| 1 | --- | 1 | --- |
| 2 | name: pypto-pro-op-auto-tuner-panko | 2 | name: pypto-pro-op-auto-tuner-panko |
| 3 | -description: PANKO base-release world model and evaluator for single-file PyPTO-Pro kernels with latency/on-chip-memory objectives on NPU. Runs one persisted search transition per dispatch. | 3 | +description: PANKO base-release world model and evaluator for single-file or multi-file PyPTO-Pro kernels with latency/on-chip-memory objectives on NPU. Runs one persisted search transition per dispatch. |
| 4 | mode: subagent | 4 | mode: subagent |
| 5 | permission: | 5 | permission: |
| 6 | read: allow | 6 | read: allow |
| @@ -116,7 +116,7 @@ opencode --agent pypto-pro-op-orchestrator | |||
| 116 | ### PANKO 基础版优化 | 116 | ### PANKO 基础版优化 |
| 117 | 117 | ||
| 118 | 例如:“用 PANKO 优化 ./custom/softmax/,沿用 ./ENVIRONMENT.md 和 test_softmax.py,在 NPU 上优化延迟和片上内存,预算 100 次评估。” | 118 | 例如:“用 PANKO 优化 ./custom/softmax/,沿用 ./ENVIRONMENT.md 和 test_softmax.py,在 NPU 上优化延迟和片上内存,预算 100 次评估。” |
| 119 | -支持单文件 JIT。续跑时指定原 campaign 目录以保留预算和测量记录。派工与验收见 [AGENTS.md](AGENTS.md)。 | 119 | +支持单文件或多文件 JIT。续跑时指定原 campaign 目录以保留预算和测量记录。派工与验收见 [AGENTS.md](AGENTS.md)。 |
| 120 | 120 | ||
| 121 | ### 验收与交付 | 121 | ### 验收与交付 |
| 122 | 122 | ||
| @@ -5,7 +5,8 @@ | |||
| 5 | # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | 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. | 6 | # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. |
| 7 | # See LICENSE in the root of the software repository for the full text of the License. | 7 | # See LICENSE in the root of the software repository for the full text of the License. |
| 8 | -"""Host regressions for Pro acquisition and single-file delivery contracts.""" | 8 | +"""Host regressions for Pro acquisition and multi-file delivery contracts.""" |
| 9 | +import ast | ||
| 9 | import hashlib | 10 | import hashlib |
| 10 | import json | 11 | import json |
| 11 | import os | 12 | import os |
| @@ -47,17 +48,42 @@ class ProContractsTest(unittest.TestCase): | |||
| 47 | self.assertEqual(result.returncode, status, result.stdout + result.stderr) | 48 | self.assertEqual(result.returncode, status, result.stdout + result.stderr) |
| 48 | return json.loads(result.stdout) | 49 | return json.loads(result.stdout) |
| 49 | 50 | ||
| 51 | + def prepare_package(self, scripts): | ||
| 52 | + self.package = self.root / "mypkg" | ||
| 53 | + inner = self.package / "inner" | ||
| 54 | + inner.mkdir(parents=True) | ||
| 55 | + (self.package / "__init__.py").write_text("BIAS = 5\n") | ||
| 56 | + (inner / "__init__.py").touch() | ||
| 57 | + (inner / "kernel.py").write_text("from .helper import compute\n" + KERNEL) | ||
| 58 | + (inner / "helper.py").write_text( | ||
| 59 | + "import pypto_pro.language as pl\nfrom mypkg import BIAS\n" | ||
| 60 | + "@pl.jit(auto_mutex=False)\ndef compute(x):\n return x + BIAS\n") | ||
| 61 | + (self.root / "precision.py").write_text("from mypkg.inner import kernel\nassert kernel.compute(7) == 12\n") | ||
| 62 | + view = self.root / "view.py" | ||
| 63 | + prepare = [scripts / "source_analysis/program_bundle.py", "prepare", "--view", view, | ||
| 64 | + "--manifest", "manifest.json", "--root"] | ||
| 65 | + rejected = subprocess.run([sys.executable, *prepare, inner], cwd=self.root, env=self.env, | ||
| 66 | + capture_output=True, text=True) | ||
| 67 | + self.assertNotEqual(rejected.returncode, 0) | ||
| 68 | + self.assertIn("Prepare the outermost package 'mypkg' as --root", rejected.stderr) | ||
| 69 | + self.assertFalse(view.exists()) | ||
| 70 | + self.assertFalse(Path(str(view) + ".runtime.json").exists()) | ||
| 71 | + self.assertFalse((self.root / "manifest.json").exists()) | ||
| 72 | + self.run_cli(*prepare, self.package) | ||
| 73 | + return view | ||
| 74 | + | ||
| 50 | def baseline_receipt(self): | 75 | def baseline_receipt(self): |
| 51 | view = self.root / "kernel.py" | 76 | view = self.root / "kernel.py" |
| 52 | view.write_text(KERNEL) | 77 | view.write_text(KERNEL) |
| 53 | precision = self.root / "precision.py" | 78 | precision = self.root / "precision.py" |
| 54 | precision.touch() | 79 | precision.touch() |
| 55 | self.template = dict( | 80 | self.template = dict( |
| 56 | - schema="panko-pro-npu-v1", code_hash=sha(view), program_files={str(view): sha(view)}, | 81 | + schema="panko-pro-npu-v1", code_hash=sha(view), |
| 57 | - contract=dict(test_files={str(precision): sha(precision)}, device="0", op_name="kernel", warmup=2, runs=9, | 82 | + program_files={str(view): sha(view)}, |
| 83 | + contract=dict(test_files={str(precision): sha(precision)}, device="0", op_name="kernel", | ||
| 84 | + warmup=2, runs=9, | ||
| 58 | argv=["python3", "precision.py"], cwd=str(self.root), env={"TILE_FWK_DEVICE_ID": "0"}, | 85 | argv=["python3", "precision.py"], cwd=str(self.root), env={"TILE_FWK_DEVICE_ID": "0"}, |
| 59 | - program=None, | 86 | + program=None, memory_capacity=CAPACITY), |
| 60 | - memory_capacity=CAPACITY), | ||
| 61 | correctness_passed=True, workspace_b=4096, workspace_by_space={"Vec": 4096}, workspace_state="measured") | 87 | correctness_passed=True, workspace_b=4096, workspace_by_space={"Vec": 4096}, workspace_state="measured") |
| 62 | return view, self.reading("baseline", 100) | 88 | return view, self.reading("baseline", 100) |
| 63 | 89 | ||
| @@ -133,15 +159,35 @@ latency = Path("latency.txt").read_text() if Path("latency.txt").exists() else " | |||
| 133 | profiler.chmod(0o755) | 159 | profiler.chmod(0o755) |
| 134 | return kernel | 160 | return kernel |
| 135 | 161 | ||
| 162 | + def prepare_profiled_package(self, kernel): | ||
| 163 | + package = self.root / "package" | ||
| 164 | + package.mkdir() | ||
| 165 | + runtime = package / kernel.name | ||
| 166 | + kernel.rename(runtime) | ||
| 167 | + source = runtime.read_text().replace("return a", "return compute(a)") | ||
| 168 | + runtime.write_text("from helper import compute\n" + source) | ||
| 169 | + (package / "helper.py").write_text("def compute(x):\n return x + 1\n") | ||
| 170 | + (package / "unused.py").write_text("unused = True\n") | ||
| 171 | + precision = self.root / "precision.py" | ||
| 172 | + precision.write_text(f"import sys\nsys.path.insert(0, {str(package)!r})\n" + precision.read_text()) | ||
| 173 | + view = self.root / "view.py" | ||
| 174 | + self.run_cli(SCRIPTS / "source_analysis/program_bundle.py", "prepare", "--root", package, | ||
| 175 | + "--view", view, "--manifest", "manifest.json") | ||
| 176 | + return view | ||
| 177 | + | ||
| 136 | def start_profiled_campaign(self, *, tile_search=False, precision_check="", capacity=None, source=KERNEL, | 178 | def start_profiled_campaign(self, *, tile_search=False, precision_check="", capacity=None, source=KERNEL, |
| 137 | - catalog=None, command="python3 precision.py", **config): | 179 | + catalog=None, command="python3 precision.py", package=False, |
| 180 | + address_limits=None, **config): | ||
| 138 | capacity = CAPACITY if capacity is None else capacity | 181 | capacity = CAPACITY if capacity is None else capacity |
| 139 | kernel = self.prepare_profiled_kernel(source, precision_check) | 182 | kernel = self.prepare_profiled_kernel(source, precision_check) |
| 183 | + if package: | ||
| 184 | + kernel = self.prepare_profiled_package(kernel) | ||
| 140 | harness = SCRIPTS / "panko_harness.py" | 185 | harness = SCRIPTS / "panko_harness.py" |
| 141 | target = ["--op-dir", self.root, "--op-file", kernel] | 186 | target = ["--op-dir", self.root, "--op-file", kernel] |
| 142 | baseline = self.run_cli(SCRIPTS / "measure.py", *target, "--device", "0", "--test-command", command, | 187 | baseline = self.run_cli(SCRIPTS / "measure.py", *target, "--device", "0", "--test-command", command, |
| 143 | "--test-files", '["precision.py"]', "--out", "baseline.json", | 188 | "--test-files", '["precision.py"]', "--out", "baseline.json", |
| 144 | - "--memory-capacity", json.dumps(capacity)) | 189 | + "--memory-capacity", json.dumps(capacity), |
| 190 | + *(["--address-limits", json.dumps(address_limits)] if address_limits else [])) | ||
| 145 | self.run_cli(harness, "init", *target, "--device", "0", "--op", "kernel", "--test-command", command, | 191 | self.run_cli(harness, "init", *target, "--device", "0", "--op", "kernel", "--test-command", command, |
| 146 | "--measurement-file", "baseline.json", "--chip-envelope", json.dumps(ENVELOPE), | 192 | "--measurement-file", "baseline.json", "--chip-envelope", json.dumps(ENVELOPE), |
| 147 | *(["--catalog", catalog] if catalog else []), | 193 | *(["--catalog", catalog] if catalog else []), |
| @@ -210,6 +256,41 @@ latency = Path("latency.txt").read_text() if Path("latency.txt").exists() else " | |||
| 210 | self.assertIn("timing target", reply["error"]) | 256 | self.assertIn("timing target", reply["error"]) |
| 211 | self.assertEqual(state.read_bytes(), original) | 257 | self.assertEqual(state.read_bytes(), original) |
| 212 | 258 | ||
| 259 | + def test_package_remeasurement_requires_baseline_tasks_per_call(self): | ||
| 260 | + view, baseline = self.start_profiled_campaign(package=True) | ||
| 261 | + profiler = self.root / "msprof" | ||
| 262 | + script = profiler.read_text() | ||
| 263 | + record = [SCRIPTS / "panko_harness.py", "record", "--op-dir", self.root, | ||
| 264 | + "--parent", "root", "--remeasure"] | ||
| 265 | + state = self.root / "optimization/search_state.json" | ||
| 266 | + original = state.read_bytes() | ||
| 267 | + self.assertEqual(json.loads(original)["measurement_contract"]["timed_target"], | ||
| 268 | + {"tasks_per_call": {"kernel": 1}}) | ||
| 269 | + for name, count in (("kernel", 2), ("other", 1), ("kernel", 1)): | ||
| 270 | + if name == "other": | ||
| 271 | + legacy = json.loads(original) | ||
| 272 | + del legacy["measurement_contract"]["timed_target"] | ||
| 273 | + state.write_text(json.dumps(legacy)) | ||
| 274 | + original = state.read_bytes() | ||
| 275 | + profiler.write_text(script.replace("kernel,AI_CORE,", f"{name},AI_CORE,") | ||
| 276 | + .replace("* launches)", f"* (launches * {count}))")) | ||
| 277 | + path = f"{name}-{count}.json" | ||
| 278 | + self.run_cli(SCRIPTS / "measure.py", "--op-file", view, "--op-dir", self.root, | ||
| 279 | + "--test-command", "python3 precision.py", "--device", "0", "--test-files", | ||
| 280 | + '["precision.py"]', "--memory-capacity", json.dumps(CAPACITY), "--out", path) | ||
| 281 | + same = (name, count) == ("kernel", 1) | ||
| 282 | + reply = self.run_cli(*record, "--measurement-file", path, status=0 if same else 3) | ||
| 283 | + if not same: | ||
| 284 | + self.assertIn("timing target", reply["error"]) | ||
| 285 | + self.assertEqual(state.read_bytes(), original) | ||
| 286 | + path = self.root / path | ||
| 287 | + edited = json.loads(path.read_bytes()) | ||
| 288 | + edited["tasks_per_call"] = {"kernel": 1} | ||
| 289 | + edited["contract"]["timed_target"] = {"tasks_per_call": {"kernel": 1}} | ||
| 290 | + path.write_text(json.dumps(edited)) | ||
| 291 | + self.assertIn("timing CSV", self.run_cli(*record, "--measurement-file", path, status=3)["error"]) | ||
| 292 | + self.assertEqual(len(json.loads(state.read_bytes())["eval_cache"][baseline["code_hash"]]["samples"]), 18) | ||
| 293 | + | ||
| 213 | def test_address_gap_reaches_measurement_and_pareto_record(self): | 294 | def test_address_gap_reaches_measurement_and_pareto_record(self): |
| 214 | source = """import pypto_pro.language as pl | 295 | source = """import pypto_pro.language as pl |
| 215 | @pl.jit(auto_mutex=False) | 296 | @pl.jit(auto_mutex=False) |
| @@ -355,6 +436,21 @@ def kernel(a): | |||
| 355 | self.assertEqual(state["measurement_contract"]["address_limits"], {"Vec": 256 * 1024}) | 436 | self.assertEqual(state["measurement_contract"]["address_limits"], {"Vec": 256 * 1024}) |
| 356 | self.assertEqual(state["measurement_contract"]["memory_capacity"], capacity) | 437 | self.assertEqual(state["measurement_contract"]["memory_capacity"], capacity) |
| 357 | 438 | ||
| 439 | + def test_vec_budget_alone_does_not_authorize_a_reserved_tail(self): | ||
| 440 | + kernel = self.root / "kernel.py" | ||
| 441 | + probe = ("import json; from evaluation.workspace_probe import profile_workspace; " | ||
| 442 | + "print(json.dumps(profile_workspace('kernel.py', {'Vec': 248 * 1024})))") | ||
| 443 | + kernel.write_text(KERNEL.replace("addrs=0", "addrs=249856")) | ||
| 444 | + at_limit = self.run_cli("-c", probe) | ||
| 445 | + self.assertEqual((at_limit["workspace_state"], at_limit["workspace_b"]), ("measured", 253952)) | ||
| 446 | + self.assertEqual(at_limit["workspace_headroom"]["Vec"], 0) | ||
| 447 | + | ||
| 448 | + kernel.write_text(KERNEL.replace("addrs=0", "addrs=256000")) | ||
| 449 | + over_limit = self.run_cli("-c", probe) | ||
| 450 | + self.assertEqual(over_limit["workspace_state"], "unavailable") | ||
| 451 | + self.assertIsNone(over_limit["workspace_b"]) | ||
| 452 | + self.assertIn("Vec needs 260096 bytes, budget is 253952", over_limit["workspace_error"]) | ||
| 453 | + | ||
| 358 | def test_depth_slots_use_declared_addresses(self): | 454 | def test_depth_slots_use_declared_addresses(self): |
| 359 | kernel = self.root / "kernel.py" | 455 | kernel = self.root / "kernel.py" |
| 360 | probe = ("import json; from evaluation.workspace_probe import profile_workspace; " | 456 | probe = ("import json; from evaluation.workspace_probe import profile_workspace; " |
| @@ -478,6 +574,43 @@ def kernel(a): | |||
| 478 | self.assertIn("timing target", self.run_cli(*verify, mode, status=3)["error"]) | 574 | self.assertIn("timing target", self.run_cli(*verify, mode, status=3)["error"]) |
| 479 | self.assertEqual(self.run_cli(*verify)["stage"], stage) | 575 | self.assertEqual(self.run_cli(*verify)["stage"], stage) |
| 480 | 576 | ||
| 577 | + def test_auto_verification_binds_each_arm_to_its_runtime_package(self): | ||
| 578 | + limits = {"Vec": 4096} | ||
| 579 | + view, _ = self.start_profiled_campaign(package=True, capacity=dict(CAPACITY, Vec=2048), | ||
| 580 | + address_limits=limits, precision_check=( | ||
| 581 | + "from pathlib import Path\n" | ||
| 582 | + "Path('latency.txt').write_text('10' if 'shape=[16, 16]' in inspect.getsource(kernel.kernel) else '20')\n")) | ||
| 583 | + package = self.root / "package" | ||
| 584 | + files = [package / name for name in ("kernel.py", "helper.py", "unused.py")] | ||
| 585 | + baseline = {str(path): sha(path) for path in files} | ||
| 586 | + cli = SCRIPTS / "panko_harness.py" | ||
| 587 | + target = ["--op-dir", self.root] | ||
| 588 | + parent = self.run_cli(cli, "select", *target)["selected"]["id"] | ||
| 589 | + kernel = package / "kernel.py" | ||
| 590 | + kernel.write_text(kernel.read_text().replace("shape=[16, 32]", "shape=[16, 16]")) | ||
| 591 | + candidate = {str(path): sha(path) for path in files} | ||
| 592 | + self.assertNotEqual(baseline, candidate) | ||
| 593 | + profiler = self.root / "msprof" | ||
| 594 | + original = profiler.read_text() | ||
| 595 | + step = [cli, "step", *target, "--op-file", view, "--parent", parent, "--test-command", "python3 precision.py"] | ||
| 596 | + profiler.write_text(original.replace("kernel,AI_CORE,", "other,AI_CORE,")) | ||
| 597 | + self.assertIn("timing target", self.run_cli(*step, "--dispatch-id", "drift", status=3)["error"]) | ||
| 598 | + profiler.write_text(original) | ||
| 599 | + self.run_cli(*step, "--dispatch-id", "smaller") | ||
| 600 | + profiler.write_text(original.replace("kernel,AI_CORE,", "other,AI_CORE,")) | ||
| 601 | + for mode in ("--auto", "--acquire"): | ||
| 602 | + self.assertIn("timing target", self.run_cli(cli, "verify", *target, mode, status=3)["error"]) | ||
| 603 | + self.assertEqual(self.run_cli(cli, "verify", *target)["stage"], 0) | ||
| 604 | + profiler.write_text(original) | ||
| 605 | + self.assertEqual(self.run_cli(cli, "verify", *target, "--auto")["status"], "confirmed") | ||
| 606 | + verification = json.loads((self.root / "optimization/search_state.json").read_bytes())["verification"] | ||
| 607 | + self.assertEqual([r["program_files"] for r in verification["receipts"]], | ||
| 608 | + [baseline, candidate, candidate, baseline]) | ||
| 609 | + for receipt in verification["receipts"]: | ||
| 610 | + self.assertEqual(receipt["contract"]["address_limits"], limits) | ||
| 611 | + self.assertEqual(receipt["workspace_state"], "measured") | ||
| 612 | + self.assertEqual(receipt["workspace_b"], 4096 if receipt["arm"] == "preopt" else 2048) | ||
| 613 | + | ||
| 481 | def test_manual_verification_requires_one_new_acquisition_per_stage(self): | 614 | def test_manual_verification_requires_one_new_acquisition_per_stage(self): |
| 482 | kernel, baseline, candidate, search = self.stopped_verification_campaign() | 615 | kernel, baseline, candidate, search = self.stopped_verification_campaign() |
| 483 | harness = SCRIPTS / "panko_harness.py" | 616 | harness = SCRIPTS / "panko_harness.py" |
| @@ -616,6 +749,7 @@ print(json.dumps([ | |||
| 616 | campaign = json.loads((self.root / "optimization/search_state.json").read_text()) | 749 | campaign = json.loads((self.root / "optimization/search_state.json").read_text()) |
| 617 | for check in [*campaign.get("verifications", []), campaign["verification"]]: | 750 | for check in [*campaign.get("verifications", []), campaign["verification"]]: |
| 618 | point = check["arms"]["delivered"]["code_hash"] | 751 | point = check["arms"]["delivered"]["code_hash"] |
| 752 | + self.assertTrue(all(r["point"] == point for r in check["receipts"])) | ||
| 619 | self.assertEqual([r["code_hash"] for r in check["receipts"]], | 753 | self.assertEqual([r["code_hash"] for r in check["receipts"]], |
| 620 | [baseline["code_hash"], point, point, baseline["code_hash"]]) | 754 | [baseline["code_hash"], point, point, baseline["code_hash"]]) |
| 621 | self.assertEqual(sha(kernel), frontier["impl_code_hash"]) | 755 | self.assertEqual(sha(kernel), frontier["impl_code_hash"]) |
| @@ -682,10 +816,16 @@ print(json.dumps([ | |||
| 682 | return kernel, baseline, step | 816 | return kernel, baseline, step |
| 683 | 817 | ||
| 684 | def test_step_measures_the_pending_f2_trial_once(self): | 818 | def test_step_measures_the_pending_f2_trial_once(self): |
| 819 | + self.check_pending_f2_trial(package=False) | ||
| 820 | + | ||
| 821 | + def test_package_step_replay_preserves_pending_f2_trial(self): | ||
| 822 | + self.check_pending_f2_trial(package=True) | ||
| 823 | + | ||
| 824 | + def check_pending_f2_trial(self, package): | ||
| 685 | catalog = self.root / "actions.json" | 825 | catalog = self.root / "actions.json" |
| 686 | actions = json.loads((SCRIPTS.parent / "references/action_catalog.json").read_text()) | 826 | actions = json.loads((SCRIPTS.parent / "references/action_catalog.json").read_text()) |
| 687 | catalog.write_text(json.dumps([a for a in actions if a["id"] == "F-2"])) | 827 | catalog.write_text(json.dumps([a for a in actions if a["id"] == "F-2"])) |
| 688 | - kernel, _ = self.start_profiled_campaign(tile_search=True, catalog=catalog, | 828 | + kernel, _ = self.start_profiled_campaign(tile_search=True, catalog=catalog, package=package, |
| 689 | capacity=dict(CAPACITY, Vec=248 * 1024), eval_budget=8) | 829 | capacity=dict(CAPACITY, Vec=248 * 1024), eval_budget=8) |
| 690 | harness = SCRIPTS / "panko_harness.py" | 830 | harness = SCRIPTS / "panko_harness.py" |
| 691 | target = ["--op-dir", self.root] | 831 | target = ["--op-dir", self.root] |
| @@ -702,10 +842,23 @@ print(json.dumps([ | |||
| 702 | self.assertEqual(sha(kernel), proposal["code_hash"]) | 842 | self.assertEqual(sha(kernel), proposal["code_hash"]) |
| 703 | self.assertEqual((reply["next"], reply["parent"]), ("evaluate", parent)) | 843 | self.assertEqual((reply["next"], reply["parent"]), ("evaluate", parent)) |
| 704 | self.assertNotIn("selection", reply) | 844 | self.assertNotIn("selection", reply) |
| 845 | + staged = [kernel] | ||
| 846 | + if package: | ||
| 847 | + staged.extend([self.root / "view.py.runtime.json", *(self.root / "package").glob("*.py")]) | ||
| 848 | + hashes = [sha(path) for path in staged] | ||
| 705 | again = self.run_cli(*step, "trial") | 849 | again = self.run_cli(*step, "trial") |
| 706 | self.assertEqual(again, reply) | 850 | self.assertEqual(again, reply) |
| 851 | + self.assertEqual([sha(path) for path in staged], hashes) | ||
| 707 | self.assertEqual(choices.read_bytes(), before) | 852 | self.assertEqual(choices.read_bytes(), before) |
| 708 | self.assertEqual(sha(kernel), proposal["code_hash"]) | 853 | self.assertEqual(sha(kernel), proposal["code_hash"]) |
| 854 | + if package: | ||
| 855 | + helper = self.root / "package/helper.py" | ||
| 856 | + original = helper.read_bytes() | ||
| 857 | + helper.write_bytes(original + b"\n# pending coder edit\n") | ||
| 858 | + edited = [sha(path) for path in staged] | ||
| 859 | + self.assertEqual(self.run_cli(*step, "trial"), reply) | ||
| 860 | + self.assertEqual([sha(path) for path in staged], edited) | ||
| 861 | + helper.write_bytes(original) | ||
| 709 | following = self.run_cli(*step, "next") | 862 | following = self.run_cli(*step, "next") |
| 710 | reading = json.loads(Path(following["measurement_file"]).read_text()) | 863 | reading = json.loads(Path(following["measurement_file"]).read_text()) |
| 711 | self.assertEqual(reading["code_hash"], proposal["code_hash"]) | 864 | self.assertEqual(reading["code_hash"], proposal["code_hash"]) |
| @@ -761,6 +914,52 @@ print(json.dumps([ | |||
| 761 | self.assertEqual(campaign["progress"]["evals_used"], 1) | 914 | self.assertEqual(campaign["progress"]["evals_used"], 1) |
| 762 | self.assertEqual(campaign["progress"].get("block_evals", 0), 0) | 915 | self.assertEqual(campaign["progress"].get("block_evals", 0), 0) |
| 763 | 916 | ||
| 917 | + def test_single_file_init_requires_csv_samples(self): | ||
| 918 | + kernel, baseline = self.baseline_receipt() | ||
| 919 | + baseline.write_text(json.dumps(dict(json.loads(baseline.read_bytes()), samples=[99] + [100] * 8))) | ||
| 920 | + reply = self.run_cli(SCRIPTS / "panko_harness.py", "init", "--op-dir", self.root, | ||
| 921 | + "--op", "kernel", "--op-file", kernel, "--device", "0", | ||
| 922 | + "--chip-envelope", json.dumps(ENVELOPE), | ||
| 923 | + "--config", '{"bayesian_optimization_tile_search":false}', | ||
| 924 | + "--measurement-file", baseline, status=3) | ||
| 925 | + self.assertIn("samples differ from the timing CSV", reply["error"]) | ||
| 926 | + self.assertFalse((self.root / "optimization/search_state.json").exists()) | ||
| 927 | + | ||
| 928 | + def test_single_file_record_checks_each_original_csv(self): | ||
| 929 | + kernel, _ = self.start_profiled_campaign() | ||
| 930 | + harness = SCRIPTS / "panko_harness.py" | ||
| 931 | + parent = self.run_cli(harness, "select", "--op-dir", self.root)["selected"]["id"] | ||
| 932 | + kernel.write_text(kernel.read_text().replace("[16, 32]", "[16, 16]", 1)) | ||
| 933 | + measure = [SCRIPTS / "measure.py", "--op-dir", self.root, "--op-file", kernel, "--device", "0", | ||
| 934 | + "--test-command", "python3 precision.py", "--test-files", '["precision.py"]', | ||
| 935 | + "--memory-capacity", json.dumps(CAPACITY)] | ||
| 936 | + first, last = (self.root / name for name in ("first.json", "last.json")) | ||
| 937 | + original = self.run_cli(*measure, "--out", first) | ||
| 938 | + (self.root / "latency.txt").write_text("10") | ||
| 939 | + self.run_cli(*measure, "--out", last) | ||
| 940 | + envelope = self.root / "winner.json" | ||
| 941 | + | ||
| 942 | + def write_confirmation(): | ||
| 943 | + readings = [{"path": str(path), "sha256": sha(path)} for path in (first, last)] | ||
| 944 | + envelope.write_text(json.dumps(dict(schema="panko-confirmed-winner-v1", op_file=str(kernel), | ||
| 945 | + readings=readings))) | ||
| 946 | + | ||
| 947 | + record = [harness, "record", "--op-dir", self.root, "--parent", parent, "--measurement-file"] | ||
| 948 | + state = self.root / "optimization/search_state.json" | ||
| 949 | + before = state.read_bytes() | ||
| 950 | + first.write_text(json.dumps(dict(original, p=1, samples=[1] * 9))) | ||
| 951 | + write_confirmation() | ||
| 952 | + for receipt in (first, envelope): | ||
| 953 | + with self.subTest(receipt=receipt.name): | ||
| 954 | + reply = self.run_cli(*record, receipt, status=3) | ||
| 955 | + self.assertIn("samples differ from the timing CSV", reply["error"]) | ||
| 956 | + self.assertEqual(state.read_bytes(), before) | ||
| 957 | + | ||
| 958 | + first.write_text(json.dumps(original)) | ||
| 959 | + write_confirmation() | ||
| 960 | + self.run_cli(*record, envelope) | ||
| 961 | + self.assertEqual(json.loads(state.read_bytes())["eval_cache"][sha(kernel)]["p"], 11) | ||
| 962 | + | ||
| 764 | def test_init_checks_baseline_samples_against_csv(self): | 963 | def test_init_checks_baseline_samples_against_csv(self): |
| 765 | kernel, baseline = self.baseline_receipt() | 964 | kernel, baseline = self.baseline_receipt() |
| 766 | raw = json.loads(baseline.read_bytes()) | 965 | raw = json.loads(baseline.read_bytes()) |
| @@ -870,3 +1069,194 @@ print(json.dumps([ | |||
| 870 | self.assertEqual(stopped["frontier"]["points"], 1) | 1069 | self.assertEqual(stopped["frontier"]["points"], 1) |
| 871 | view, = (self.root / "optimization/frontier").glob("*.py") | 1070 | view, = (self.root / "optimization/frontier").glob("*.py") |
| 872 | self.assertEqual(view.read_bytes(), source.read_bytes()) | 1071 | self.assertEqual(view.read_bytes(), source.read_bytes()) |
| 1072 | + | ||
| 1073 | + def test_package_factory_width_survives_nested_global(self): | ||
| 1074 | + package = self.root / "package" | ||
| 1075 | + package.mkdir() | ||
| 1076 | + (package / "factory.py").write_text("""import pypto_pro.language as pl | ||
| 1077 | +WIDTH = 16 | ||
| 1078 | + | ||
| 1079 | +def make(WIDTH): | ||
| 1080 | + def reset(): | ||
| 1081 | + global WIDTH | ||
| 1082 | + WIDTH += 1 | ||
| 1083 | + | ||
| 1084 | + @pl.jit(auto_mutex=False) | ||
| 1085 | + def kernel(a): | ||
| 1086 | + tile = pl.make_tile_group(type=pl.TileType(shape=[16, WIDTH], dtype=pl.DT_FP32, | ||
| 1087 | + target_memory=pl.MemorySpace.Vec), addrs=0, mutex_ids=[0]) | ||
| 1088 | + return a | ||
| 1089 | + return kernel | ||
| 1090 | +""") | ||
| 1091 | + (package / "entry.py").write_text("import factory\nkernel = factory.make(64)\n") | ||
| 1092 | + view = self.root / "view.py" | ||
| 1093 | + self.run_cli(SCRIPTS / "source_analysis/program_bundle.py", "prepare", "--root", package, | ||
| 1094 | + "--view", view, "--manifest", "manifest.json") | ||
| 1095 | + probe = ("import json; from evaluation.workspace_probe import profile_workspace; " | ||
| 1096 | + "print(json.dumps(profile_workspace('view.py', {'Vec': 8192})))") | ||
| 1097 | + self.assertEqual(self.run_cli("-c", probe)["workspace_by_space"], {"Vec": 4096}) | ||
| 1098 | + functions = (node for node in ast.walk(ast.parse(view.read_text())) if isinstance(node, ast.FunctionDef)) | ||
| 1099 | + reset = next(node for node in functions if node.name == "reset") | ||
| 1100 | + declaration, increment = reset.body | ||
| 1101 | + self.assertEqual(declaration.names, [increment.target.id]) | ||
| 1102 | + self.assertNotEqual(increment.target.id, "WIDTH") | ||
| 1103 | + | ||
| 1104 | + def test_prepare_resolves_initializer_reexports_in_source_order(self): | ||
| 1105 | + package = self.root / "package" | ||
| 1106 | + package.mkdir() | ||
| 1107 | + (package / "__init__.py").write_text( | ||
| 1108 | + "width = 7\nfrom . import helper, width as initial\nfrom . import helper as public\n" | ||
| 1109 | + "result = helper.value + initial\nhelper = 11\nfrom . import helper as after\n") | ||
| 1110 | + (package / "helper.py").write_text("value = 35\n") | ||
| 1111 | + (package / "width.py").write_text("value = 999\n") | ||
| 1112 | + (package / "consumer.py").write_text("from . import public as h, after\nresult = h.value + after\n") | ||
| 1113 | + expected = self.run_cli("-c", "from package import consumer, result; print([result, consumer.result])") | ||
| 1114 | + self.assertEqual(expected, [42, 46]) | ||
| 1115 | + view = self.root / "view.py" | ||
| 1116 | + manifest = self.run_cli(SCRIPTS / "source_analysis/program_bundle.py", "prepare", "--root", package, | ||
| 1117 | + "--view", view, "--manifest", "manifest.json", "--entry-file", "consumer.py") | ||
| 1118 | + symbols = manifest["symbol_map"] | ||
| 1119 | + actual = self.run_cli("-c", f"import view; print([view.{symbols['__init__.py']['result']}, " | ||
| 1120 | + f"view.{symbols['consumer.py']['result']}])") | ||
| 1121 | + self.assertEqual(actual, expected) | ||
| 1122 | + | ||
| 1123 | + def test_stop_restores_package_after_interrupted_helper_edit(self): | ||
| 1124 | + view, baseline = self.start_profiled_campaign(package=True, eval_budget=2) | ||
| 1125 | + helper = self.root / "package/helper.py" | ||
| 1126 | + helper.write_text("def compute(") | ||
| 1127 | + stop = [SCRIPTS / "panko_harness.py", "stop", "--op-dir", self.root] | ||
| 1128 | + poll = self.run_cli(*stop) | ||
| 1129 | + self.assertFalse(poll["stop"]) | ||
| 1130 | + self.assertFalse(poll["delivered_is_best"]) | ||
| 1131 | + self.assertEqual(helper.read_text(), "def compute(") | ||
| 1132 | + stop.extend(["--force", "interrupted"]) | ||
| 1133 | + nodes = self.root / "optimization/nodes" | ||
| 1134 | + snapshot = nodes / (baseline["code_hash"] + ".py") | ||
| 1135 | + original = snapshot.read_bytes() | ||
| 1136 | + snapshot.write_bytes(original + b"# corrupt\n") | ||
| 1137 | + self.assertEqual(self.run_cli(*stop, status=3)["error"], "restore_failed") | ||
| 1138 | + self.assertEqual(helper.read_text(), "def compute(") | ||
| 1139 | + snapshot.write_bytes(original) | ||
| 1140 | + extra = helper.with_name("unexpected.py") | ||
| 1141 | + extra.touch() | ||
| 1142 | + self.assertEqual(self.run_cli(*stop, status=3)["error"], "restore_failed") | ||
| 1143 | + self.assertFalse((self.root / "optimization/frontier/frontier.json").exists()) | ||
| 1144 | + extra.unlink() | ||
| 1145 | + self.assertTrue(self.run_cli(*stop)["stop"]) | ||
| 1146 | + self.assertEqual(sha(view), baseline["code_hash"]) | ||
| 1147 | + self.assertEqual({str(f): sha(f) for f in helper.parent.glob("*.py")}, baseline["program_files"]) | ||
| 1148 | + exported, = (self.root / "optimization/frontier").glob("*.py") | ||
| 1149 | + self.assertEqual(sha(exported), sha(view)) | ||
| 1150 | + spec = json.loads(Path(str(exported) + ".runtime.json").read_bytes()) | ||
| 1151 | + self.assertEqual({Path(f).name: sha(Path(f)) for f in spec["files"]}, | ||
| 1152 | + {Path(f).name: h for f, h in baseline["program_files"].items()}) | ||
| 1153 | + | ||
| 1154 | + def test_package_block_refuses_host_edit_after_refresh(self): | ||
| 1155 | + self.start_profiled_campaign(tile_search=True, package=True) | ||
| 1156 | + harness = SCRIPTS / "panko_harness.py" | ||
| 1157 | + parent = self.run_cli(harness, "select", "--op-dir", self.root)["selected"]["id"] | ||
| 1158 | + helper = self.root / "package/helper.py" | ||
| 1159 | + helper.write_text(helper.read_text() + "\nHOST_SIDE_CHANGE = 123\n") | ||
| 1160 | + self.run_cli(SCRIPTS / "source_analysis/program_bundle.py", "refresh", "--manifest", "manifest.json") | ||
| 1161 | + state = self.root / "optimization/search_state.json" | ||
| 1162 | + before = sha(state) | ||
| 1163 | + reply = self.run_cli(harness, "block", "--op-dir", self.root, "--parent", parent, | ||
| 1164 | + "--test-command", "python3 precision.py", status=3) | ||
| 1165 | + self.assertIn("host wrapper", reply["error"]) | ||
| 1166 | + self.assertEqual(sha(state), before) | ||
| 1167 | + self.assertFalse((self.root / "optimization/blocks/0").exists()) | ||
| 1168 | + | ||
| 1169 | + def test_measure_rejects_shadowed_package_helper(self): | ||
| 1170 | + view = self.prepare_profiled_package(self.prepare_profiled_kernel(KERNEL)) | ||
| 1171 | + measure = [SCRIPTS / "measure.py", "--op-file", view, "--op-dir", self.root, "--device", "0", | ||
| 1172 | + "--test-command", "python3 precision.py", "--test-files", '["precision.py"]', | ||
| 1173 | + "--memory-capacity", json.dumps(CAPACITY), "--out"] | ||
| 1174 | + good = self.run_cli(*measure, "good.json") | ||
| 1175 | + self.assertTrue(good["correctness_passed"]) | ||
| 1176 | + self.assertEqual(good["p"], 12) | ||
| 1177 | + other = self.root / "other" | ||
| 1178 | + other.mkdir() | ||
| 1179 | + (other / "helper.py").write_text("def compute(x):\n return x - 1\n") | ||
| 1180 | + precision = self.root / "precision.py" | ||
| 1181 | + precision.write_text(f"import sys\nsys.path.insert(0, {str(other)!r})\nimport helper\n" | ||
| 1182 | + + precision.read_text() + "\nassert kernel.compute(3) == 2\n" | ||
| 1183 | + + "import package.helper\nassert package.helper.compute(3) == 4\n") | ||
| 1184 | + bad = self.run_cli(*measure, "wrong.json") | ||
| 1185 | + self.assertTrue(bad.get("impl_module_mismatch"), bad) | ||
| 1186 | + self.assertFalse(bad["correctness_passed"]) | ||
| 1187 | + self.assertIsNone(bad["p"]) | ||
| 1188 | + # A relative import can coexist with an unrelated top-level module named helper. | ||
| 1189 | + kernel = self.root / "package/kernel.py" | ||
| 1190 | + kernel.write_text(kernel.read_text().replace("from helper import", "from .helper import")) | ||
| 1191 | + self.run_cli(SCRIPTS / "source_analysis/program_bundle.py", "refresh", "--manifest", "manifest.json") | ||
| 1192 | + precision.write_text(f"import sys\nsys.path.insert(0, {str(other)!r})\nimport helper\n" | ||
| 1193 | + "from package import kernel\nassert kernel.compute(3) == 4 and helper.compute(3) == 2\n") | ||
| 1194 | + relative = self.run_cli(*measure, "relative.json") | ||
| 1195 | + self.assertTrue(relative["correctness_passed"], relative) | ||
| 1196 | + self.assertEqual(relative["p"], 12) | ||
| 1197 | + | ||
| 1198 | + def test_acquisition_binds_qualified_package_helper(self): | ||
| 1199 | + view = self.prepare_profiled_package(self.prepare_profiled_kernel(KERNEL)) | ||
| 1200 | + package = self.root / "package" | ||
| 1201 | + kernel = package / "kernel.py" | ||
| 1202 | + kernel.write_text(kernel.read_text().replace("from helper import", "from package.helper import")) | ||
| 1203 | + self.run_cli(SCRIPTS / "source_analysis/program_bundle.py", "refresh", "--manifest", "manifest.json") | ||
| 1204 | + measure = [SCRIPTS / "measure.py", "--op-file", view, "--op-dir", self.root, "--device", "0", | ||
| 1205 | + "--test-command", "python3 precision.py", "--test-files", '["precision.py"]', | ||
| 1206 | + "--memory-capacity", json.dumps(CAPACITY), "--out"] | ||
| 1207 | + receipt = self.run_cli(*measure, "measurement.json") | ||
| 1208 | + self.assertTrue(receipt["correctness_passed"], receipt) | ||
| 1209 | + self.assertEqual(receipt["p"], 12) | ||
| 1210 | + helper = package / "helper.py" | ||
| 1211 | + log = (Path(receipt["msprof_dir"]) / "command.log").read_text() | ||
| 1212 | + check = ("import json; from pathlib import Path; from evaluation.measure_latency import impl_mismatch; " | ||
| 1213 | + "print(json.dumps(impl_mismatch(Path('report.txt').read_text(), 'view.py')))") | ||
| 1214 | + for old, new in ((str(helper), str(self.root / "elsewhere/helper.py")), (sha(helper), "0" * 64)): | ||
| 1215 | + with self.subTest(report_field=old): | ||
| 1216 | + self.assertIn(old, log) | ||
| 1217 | + (self.root / "report.txt").write_text(log.replace(old, new)) | ||
| 1218 | + self.assertIn("staged", self.run_cli("-c", check)) | ||
| 1219 | + # Model a collector that completed the launches but omitted this helper's import evidence. | ||
| 1220 | + profiler = self.root / "msprof" | ||
| 1221 | + profiler.write_text(profiler.read_text().replace( | ||
| 1222 | + "subprocess.run([python, *args], check=True)", | ||
| 1223 | + "log = subprocess.check_output([python, *args], text=True)\n" | ||
| 1224 | + "print('\\n'.join(line for line in log.splitlines() if '/helper.py' not in line))")) | ||
| 1225 | + incomplete = self.run_cli(*measure, "incomplete.json") | ||
| 1226 | + self.assertTrue(incomplete["impl_module_mismatch"]) | ||
| 1227 | + self.assertFalse(incomplete["correctness_passed"]) | ||
| 1228 | + self.assertIsNone(incomplete["p"]) | ||
| 1229 | + | ||
| 1230 | + def test_exported_package_passes_runtime_check(self): | ||
| 1231 | + installer = Path(__file__).resolve().parents[1] / "scripts/install_opencode.py" | ||
| 1232 | + runpy.run_path(str(installer))["install"](self.root) | ||
| 1233 | + scripts = self.root / ".opencode/skills/pypto-pro-op-perf-panko-manual/scripts" | ||
| 1234 | + self.env["PYTHONPATH"] = str(scripts) | ||
| 1235 | + self.prepare_profiled_kernel(KERNEL) | ||
| 1236 | + original = self.prepare_package(scripts) | ||
| 1237 | + measure = [scripts / "measure.py", "--op-dir", self.root, "--test-command", "python3 precision.py", | ||
| 1238 | + "--device", "0", "--test-files", '["precision.py"]', "--memory-capacity", json.dumps(CAPACITY)] | ||
| 1239 | + before = self.run_cli(*measure, "--op-file", original, "--out", "original.json") | ||
| 1240 | + self.assertTrue(before["correctness_passed"], before) | ||
| 1241 | + self.run_cli(scripts / "panko_harness.py", "init", "--op-dir", self.root, "--op", "kernel", | ||
| 1242 | + "--op-file", original, "--device", "0", "--chip-envelope", json.dumps(ENVELOPE), | ||
| 1243 | + "--config", '{"bayesian_optimization_tile_search":false,"eval_budget":1}', | ||
| 1244 | + "--measurement-file", "original.json") | ||
| 1245 | + stopped = self.run_cli(scripts / "panko_harness.py", "stop", "--op-dir", self.root) | ||
| 1246 | + self.assertTrue(stopped["stop"]) | ||
| 1247 | + self.assertEqual(stopped["frontier"]["points"], 1) | ||
| 1248 | + view, = (self.root / "optimization/frontier").glob("*.py") | ||
| 1249 | + self.package.rename(self.root / "old-package") | ||
| 1250 | + check = ("import json, sys; from source_analysis.program_bundle import runtime_spec; " | ||
| 1251 | + "print(json.dumps(runtime_spec(sys.argv[1])))") | ||
| 1252 | + spec = self.run_cli("-c", check, view) | ||
| 1253 | + receipt = self.run_cli(*measure, "--op-file", view, "--out", "exported.json") | ||
| 1254 | + self.assertTrue(receipt["correctness_passed"], receipt.get("p_error")) | ||
| 1255 | + self.assertEqual(receipt["contract"]["test_files"], before["contract"]["test_files"]) | ||
| 1256 | + self.assertEqual(receipt["program_files"], spec["files"]) | ||
| 1257 | + self.assertEqual(receipt["p"], 12) | ||
| 1258 | + root = Path(str(view) + ".program") / "mypkg" | ||
| 1259 | + self.assertEqual(spec["root"], str(root)) | ||
| 1260 | + self.assertEqual(set(spec["required"]), {str(root / "inner/kernel.py"), str(root / "inner/helper.py")}) | ||
| 1261 | + members = ("__init__.py", "inner/__init__.py", "inner/kernel.py", "inner/helper.py") | ||
| 1262 | + self.assertEqual(spec["files"], {str(root / name): sha(self.root / "old-package" / name) for name in members}) | ||


[P1] Freeze the per-call AI-Core task composition for package measurements
Package acquisition sets
op_name="*", andbind_timing_target()returns early for an explicit name. Profile parsing checks task composition within an acquisition, so two acquisitions with different task names or counts can still have identical campaign contracts.With the host profiler fixture, I recorded a baseline with one AI-Core task per call and a remeasurement of the same source with two.
record --remeasureaccepted the second receipt and pooled all 18 samples. Freeze the observed task names and their counts per call at baseline, and use that signature when admitting candidate, remeasurement and ABBA readings.