Merged
feat(PANKO-Pro): Add latency and on-chip memory tuning for single-file PyPTO-Pro JIT kernels #1077
feat(PANKO-Pro): Add latency and on-chip memory tuning for single-file PyPTO-Pro JIT kernels #1077
Merged
Tomomasa YamasakiAdd on 13 days ago
Total: 60 files changed+11491-36
@@ -98,6 +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 102 
102### 模型适配(model/)103### 模型适配(model/)
103 104 
@@ -91,6 +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 95 
95**模型适配**(model/,共 3 个)96**模型适配**(model/,共 3 个)
96 97 
@@ -547,7 +547,7 @@ def _draw_site(trial, site, r, ctx):
547 return _draw_vec(trial, r, a, ctx)547 return _draw_vec(trial, r, a, ctx)
548 548 
549 549 
550-def _apply_tie(cfg, tie, fields_of=vec_fields):550+def apply_tie(cfg, tie, fields_of=vec_fields):
551 """Write the shared leading value back over every member of a tied group.551 """Write the shared leading value back over every member of a tied group.
552 552 
553 A tied site is drawn independently (it is its own `rep`), so without this the553 A tied site is drawn independently (it is its own `rep`), so without this the
@@ -588,7 +588,7 @@ def suggest(trial, sites, opts=None):
588 "lead_dom": tied_lead_domain(opts.tie, sites, opts.anchor, opts.domain),588 "lead_dom": tied_lead_domain(opts.tie, sites, opts.anchor, opts.domain),
589 }589 }
590 cfg = draw_grouped(trial, sites, rep, ctx, _draw_site)590 cfg = draw_grouped(trial, sites, rep, ctx, _draw_site)
591- _apply_tie(cfg, opts.tie)591+ apply_tie(cfg, opts.tie)
592 return cfg592 return cfg
593 593 
594 594 
@@ -23,7 +23,7 @@ import mo_hv
23 23 
24from .config import (DEFAULT_CONFIG, FrontContext, J_OBJECTIVE, OBJECTIVE_ALIASES, Refusal, VERIFY_ALPHA, VERIFY_BOOT,24from .config import (DEFAULT_CONFIG, FrontContext, J_OBJECTIVE, OBJECTIVE_ALIASES, Refusal, VERIFY_ALPHA, VERIFY_BOOT,
25 VERIFY_SEED, out)25 VERIFY_SEED, out)
26-from .state import (_base_hash, _wrapper_drift, file_hash, live_frontier, npath, op_file_path,26+from .state import (_base_hash, wrapper_drift, file_hash, live_frontier, npath, op_file_path,
27 open_node, preopt_code_hash)27 open_node, preopt_code_hash)
28from .measurement import (bootstrap_speedup, compute_j, is_bytes, median_of, objective_values, objectives_of,28from .measurement import (bootstrap_speedup, compute_j, is_bytes, median_of, objective_values, objectives_of,
29 preopt_values)29 preopt_values)
@@ -264,7 +264,7 @@ def delivery_point(st, op_dir):
264 path = op_file_path(st, op_dir)264 path = op_file_path(st, op_dir)
265 if h != best_hash or file_hash(path) != h:265 if h != best_hash or file_hash(path) != h:
266 continue266 continue
267- if _wrapper_drift(st, path):267+ if wrapper_drift(st, path):
268 continue268 continue
269 key = tuple(-vals[o["name"]] if o["direction"] == "max" else vals[o["name"]] for o in objs)269 key = tuple(-vals[o["name"]] if o["direction"] == "max" else vals[o["name"]] for o in objs)
270 rank.append((key, h, vals))270 rank.append((key, h, vals))
@@ -24,7 +24,7 @@ from .backend import current
24from .config import (CATALOG_PRIOR_DEFAULT, CandidateRow, MeasurementVerdict, RatchetMeasurement, Refusal,24from .config import (CATALOG_PRIOR_DEFAULT, CandidateRow, MeasurementVerdict, RatchetMeasurement, Refusal,
25 SEARCH_PROTOCOL, STAGE_ORDER, SelectionContext, _bound, clamp_belief, clamp_prior, clamp_stage,25 SEARCH_PROTOCOL, STAGE_ORDER, SelectionContext, _bound, clamp_belief, clamp_prior, clamp_stage,
26 feasibility, out)26 feasibility, out)
27-from .state import (_base_hash, _domain_state, _gstag, _refine_base, _semantic_noop, _structure, _wrapper_drift,27+from .state import (_base_hash, _domain_state, _gstag, _refine_base, _semantic_noop, _structure, wrapper_drift,
28 accumulate_wall_clock, chip_envelope, file_hash, live_frontier, load, next_id, npath,28 accumulate_wall_clock, chip_envelope, file_hash, live_frontier, load, next_id, npath,
29 op_file_path, preopt_code_hash, ratchet_best_hash, restore, rollback, save, snapshot)29 op_file_path, preopt_code_hash, ratchet_best_hash, restore, rollback, save, snapshot)
30from .measurement import (block_samples, cli_samples, compute_j, median_of, objective_values, objectives_of,30from .measurement import (block_samples, cli_samples, compute_j, median_of, objective_values, objectives_of,
@@ -245,7 +245,7 @@ def _record_wrapper_drift(a, st, pr):
245 """`feasible` is the cheap gate and it is not mandatory, so the ratchet checks245 """`feasible` is the cheap gate and it is not mandatory, so the ratchet checks
246 too. A measurement taken on a changed wrapper is not comparable with the rest246 too. A measurement taken on a changed wrapper is not comparable with the rest
247 of the campaign and must not be allowed to set the best. Emits and raises."""247 of the campaign and must not be allowed to set the best. Emits and raises."""
248- drift = _wrapper_drift(st, op_file_path(st, a.op_dir))248+ drift = wrapper_drift(st, op_file_path(st, a.op_dir))
249 if not drift:249 if not drift:
250 return250 return
251 pr["wrapper_drift_rejected"] = pr.get("wrapper_drift_rejected", 0) + 1251 pr["wrapper_drift_rejected"] = pr.get("wrapper_drift_rejected", 0) + 1
@@ -394,7 +394,6 @@ def cmd_record(a):
394 return394 return
395 _record_wrapper_drift(a, st, pr)395 _record_wrapper_drift(a, st, pr)
396 396 
397- pr["evals_used"] += 1
398 # A block winner is promoted through this path deliberately (so the ratchet397 # A block winner is promoted through this path deliberately (so the ratchet
399 # runs in exactly one place), but the block measured it and the CLI call398 # runs in exactly one place), but the block measured it and the CLI call
400 # that promotes it carries no reading. Recover it from the block record399 # that promotes it carries no reading. Recover it from the block record
@@ -539,7 +538,7 @@ def _reject_wrapper_drift(a, st, pr, op_f, retune):
539 538 
540 Returns True when it has emitted a rejection and the caller must stop.539 Returns True when it has emitted a rejection and the caller must stop.
541 """540 """
542- drift = _wrapper_drift(st, op_f)541+ drift = wrapper_drift(st, op_f)
543 if not drift:542 if not drift:
544 return False543 return False
545 pr["wrapper_drift_rejected"] = pr.get("wrapper_drift_rejected", 0) + 1544 pr["wrapper_drift_rejected"] = pr.get("wrapper_drift_rejected", 0) + 1
@@ -1222,7 +1221,9 @@ def _refuse_unmeasured_objectives(a, st, pr, m_rec):
1222 1221 
1223 1222 
1224def _record_cache_entry(a, st, cache):1223def _record_cache_entry(a, st, cache):
1225- """Memoize the candidate's measurement and whatever readings came with it."""1224+ """Cache the measurement and charge it unless its tile trial already paid for it."""
1225+ if not getattr(a, "evaluation_already_charged", False):
1226+ st["progress"]["evals_used"] += 1
1226 # The further objectives ride on every measured candidate -- kept AND1227 # The further objectives ride on every measured candidate -- kept AND
1227 # reverted, since `eval_cache` keeps both.1228 # reverted, since `eval_cache` keeps both.
1228 m_eval = record_metrics(a, st)1229 m_eval = record_metrics(a, st)
@@ -499,7 +499,7 @@ def decorated_jit(node):
499 return False499 return False
500 500 
501 501 
502-def _wrapper_drift(st, path):502+def wrapper_drift(st, path):
503 """"" if the wrapper still matches the baseline, else why it does not."""503 """"" if the wrapper still matches the baseline, else why it does not."""
504 if not st.get("wrapper_signature"):504 if not st.get("wrapper_signature"):
505 return ""505 return ""
@@ -180,12 +180,14 @@ def task_pipe_statistics(path, *, repeats, tasks_per_call):
180 return result180 return result
181 181 
182 182 
183+def call_duration_sums(calls):
184+ """Sum the ordered native task durations belonging to each kernel call."""
185+ return tuple(sum(call) for call in calls)
186+ 
187+ 
183def task_samples(path, *, repeats, tasks_per_call):188def task_samples(path, *, repeats, tasks_per_call):
184 """Parse one capture strictly; missing/extra tasks never become zero cost."""189 """Parse one capture strictly; missing/extra tasks never become zero cost."""
185- return tuple(190+ return call_duration_sums(_task_calls(path, repeats=repeats, tasks_per_call=tasks_per_call))
186- sum(call)
187- for call in _task_calls(path, repeats=repeats, tasks_per_call=tasks_per_call)
188- )
189 191 
190 192 
191def task_statistics(path, *, repeats, tasks_per_call):193def task_statistics(path, *, repeats, tasks_per_call):
@@ -201,7 +203,7 @@ def task_statistics(path, *, repeats, tasks_per_call):
201 203 
202def _statistics(calls):204def _statistics(calls):
203 repeats, tasks_per_call = len(calls), len(calls[0])205 repeats, tasks_per_call = len(calls), len(calls[0])
204- samples = tuple(sum(call) for call in calls)206+ samples = call_duration_sums(calls)
205 per_task = []207 per_task = []
206 for position in range(tasks_per_call):208 for position in range(tasks_per_call):
207 durations = tuple(call[position] for call in calls)209 durations = tuple(call[position] for call in calls)
@@ -0,0 +1,25 @@
1+---
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.
4+---
5+ 
6+# PANKO for PyPTO-Pro
7+ 
8+Freeze host wrappers and precision tests. 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.
10+ 
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.
13+Measure staged TPE candidates unchanged.
14+ 
15+With the installed scripts (`S`), campaign (`D`), staged kernel (`OP`) and frozen test command, run STEP once per stable dispatch ID:
16+ 
17+```sh
18+python3 "$S/panko_harness.py" step --op-dir "$D" --op-file "$OP" --parent "$ACTION_ID" \
19+ --dispatch-id "$DISPATCH_ID" --test-command "$TEST_COMMAND"
20+```
21+ 
22+On STOP, finish ABBA and return `verification_request` for independent verification.
23+For `next=evaluate`, measure the staged tile with the same parent and a new dispatch ID. For `next=code`, request code for that parent.
24+For `next=close`, run `close --action "$ACTION_ID"` and check STOP before selecting again. Otherwise follow the returned `selection`.
25+On acquisition failure, preserve state and receipts and return ASK_USER if blocked.
@@ -0,0 +1,492 @@
1+[
2+ {
3+ "id": "F-1",
4+ "stage": "frontend",
5+ "requires": ["has_cube_op"],
6+ "delta": "Vary the Cube tile shapes: the `shape=` of every `pl.make_tile_group(type=pl.TileType(...))` at a Mat / Left / Right / Acc site. Applies when the kernel has Cube sites whose shape the search may set; Vec tiles are not touched under this action. Equivalent only if the shape stays expressible -- `M > 128` is forbidden by the L0C `mad` column pitch (`ceil16(m)`), so stacking the M axis is not expensive but inexpressible, and windowing N is the supported direction.",
7+ "prior_gain": 0.5
8+ },
9+ {
10+ "id": "F-2",
11+ "stage": "frontend",
12+ "delta": "Vary the Vector tile shapes: the `shape=` of every `pl.make_tile_group(type=pl.TileType(...))` at a Vec site. Applies when the kernel has Vec sites whose shape the search may set. Equivalent only if a site that declares `valid_shape=` keeps its window inside the tile: that declaration is a floor on each axis, not a hint.",
13+ "prior_gain": 0.5
14+ },
15+ {
16+ "id": "F-3",
17+ "stage": "frontend",
18+ "conversion": true,
19+ "requires": ["has_nested_pypto_loop"],
20+ "prior_gain": 0.9,
21+ "delta": "Interleave N iterations of an outer `pl.range` into the inner loop so N independent chains can overlap. Use a source rewrite with separate accumulators and tile lifetimes for each chain. Applies when the outer iterations are independent and the grouping preserves loop bounds; handle any remainder explicitly. Preserve loop-carried dependencies, initialization, synchronization and output ownership, then validate accuracy and measure the rewritten kernel. Check the added live tiles against each on-chip memory limit."
22+ },
23+ {
24+ "id": "F-4",
25+ "stage": "frontend",
26+ "requires": ["has_nested_pypto_loop"],
27+ "bound": ["MTE2", "MAC"],
28+ "delta": "Guard an iteration that the program's own validity predicate already proves contributes nothing. Applies when the kernel computes a count or mask that reaches zero for some iterations of a loop whose body runs regardless, so the result is multiplied by zero or discarded after the work is done. Equivalent only if the guard covers exactly the provably-empty case and the skipped iteration leaves the running accumulation untouched -- a skip that suppresses only the store leaves stale state feeding the total.",
29+ "prior_gain": 0.9
30+ },
31+ {
32+ "id": "F-5",
33+ "stage": "frontend",
34+ "prior_gain": 0.5,
35+ "delta": "Give each segment of a tile its own aligned start instead of letting segments begin at unaligned offsets. Applies when a segment's start is off the transfer unit's alignment boundary and the on-chip budget can hold the separate tiles together with their padding.",
36+ "bound": ["MTE2", "MTE3"]
37+ },
38+ {
39+ "id": "F-6",
40+ "stage": "frontend",
41+ "prior_gain": 0.5,
42+ "delta": "Have the epilogue write its result directly in the layout its consumer expects, instead of producing a compact internal layout and repacking it in a second pass. Applies when the internal layout differs from the downstream contract's padding or grouping, the reorder is currently done element by element, and the computing stage is free to choose its output stride and order.",
43+ "moves": ["workspace"],
44+ "bound": ["MTE3"]
45+ },
46+ {
47+ "id": "F-7",
48+ "stage": "frontend",
49+ "prior_gain": 0.9,
50+ "delta": "Keep the smaller matmul operand resident on-chip for the whole of the other side's loop instead of re-reading it each iteration. Applies when one side fits in the on-chip budget beside the streaming side's buffers, and the other side loops more than once.",
51+ "requires": ["has_cube_op"],
52+ "bound": ["MTE2"]
53+ },
54+ {
55+ "id": "F-8",
56+ "stage": "frontend",
57+ "prior_gain": 0.5,
58+ "delta": "Have a constant operand arrive already in the layout the hardware wants, so its transfer does no conversion, instead of converting it on every call. Applies when the operand does not change between invocations, its transfer is a large share of the work, and the conversion is otherwise paid on the critical path -- more so when its innermost axis is unaligned.",
59+ "requires": ["has_cube_op"],
60+ "bound": ["MTE2"]
61+ },
62+ {
63+ "id": "F-9",
64+ "stage": "frontend",
65+ "prior_gain": 0.5,
66+ "delta": "Serve two differently laid out reads of the same data from one on-chip copy instead of staging it twice. Applies when the same data feeds two inputs of one compute unit, one in its original layout and one transposed, and both can be transferred without reshaping.",
67+ "requires": ["has_cube_op"],
68+ "bound": ["MTE1"]
69+ },
70+ {
71+ "id": "F-10",
72+ "stage": "frontend",
73+ "prior_gain": 0.5,
74+ "delta": "Split the loop into an aligned main region with static shapes and a separate tail, instead of sending every tile through the dynamic conservative path. Applies when one kernel covers both aligned and unaligned shapes, every tile currently takes that path, and the main region can be cut into whole aligned tiles.",
75+ "bound": ["MTE2", "MTE3"]
76+ },
77+ {
78+ "id": "F-11",
79+ "stage": "frontend",
80+ "prior_gain": 0.5,
81+ "delta": "Transfer several rows per operation instead of one row at a time. Applies when the loop moves single rows or small tensors repeatedly, those rows are contiguous in memory, their consumers are in the same stage, and the on-chip budget holds a multi-row tile.",
82+ "bound": ["MTE2", "MTE3"]
83+ },
84+ {
85+ "id": "F-12",
86+ "stage": "frontend",
87+ "prior_gain": 0.5,
88+ "delta": "Mark data that is read once as non-cacheable, so it stops evicting data that is reused. Applies when a large operand is consumed exactly once, no later reuse is possible by shape or schedule, and reused data is losing cache residency to those streaming reads.",
89+ "bound": ["MTE2"]
90+ },
91+ {
92+ "id": "F-13",
93+ "stage": "frontend",
94+ "prior_gain": 0.5,
95+ "delta": "Write a result out in one transfer instead of row by row. Applies when the result already sits contiguously on-chip in output order, nothing transforms it afterwards, and it has to reach one contiguous destination range.",
96+ "moves": ["workspace"],
97+ "bound": ["MTE3"]
98+ },
99+ {
100+ "id": "F-14",
101+ "stage": "frontend",
102+ "prior_gain": 0.5,
103+ "delta": "Route a degenerate case to a plain copy instead of running the general transform. Applies when the operator's parameters can make the transform an identity -- a reshape that moves nothing, a single-segment split -- and that condition is fully provable from shape and layout before the work is planned.",
104+ "bound": ["SCALAR"]
105+ },
106+ {
107+ "id": "F-15",
108+ "stage": "frontend",
109+ "prior_gain": 0.5,
110+ "delta": "Hand a result from one compute unit to the next on-chip instead of writing it out and reading it back. Applies when the producer's result is consumed immediately by the other unit and that round trip is on the critical path.",
111+ "requires": ["has_cube_op"],
112+ "moves": ["workspace"],
113+ "bound": ["VEC", "MTE2", "MTE3"]
114+ },
115+ {
116+ "id": "F-16",
117+ "stage": "frontend",
118+ "prior_gain": 0.9,
119+ "delta": "Keep only the K candidates each block can contribute and truncate again at every merge level, instead of fully ordering all N elements. Applies when the consumer uses only K values or indices while the code orders the whole input, or a merge level keeps more than K candidates, and an element outside a block's local top K provably cannot enter the global one. Equivalent only if the comparison key encodes the whole ordering semantics -- direction, stability, tie-break and special values -- so truncating cannot change which elements win.",
120+ "bound": ["算法", "VEC", "Scalar", "访存"]
121+ },
122+ {
123+ "id": "F-17",
124+ "stage": "frontend",
125+ "prior_gain": 0.5,
126+ "delta": "Count occurrences over a small exact domain and locate the answer from the counts, instead of ordering the input. Applies when the frozen contract proves the input lies in a finite domain small enough to hold a counter table, that domain is far smaller than the input, and prefix counts recover the required value, index and tie result exactly. Equivalent only if the domain is exact rather than bucketed, the counters cannot overflow, and a stable index is recoverable from the counts alone.",
127+ "bound": ["算法", "VEC", "访存"]
128+ },
129+ {
130+ "id": "F-18",
131+ "stage": "frontend",
132+ "prior_gain": 0.5,
133+ "delta": "Delete a production chain that reaches no observable output, together with the transfers and descriptors only it uses. Applies when a full def-use and reachability argument shows its initialisation, updates and stores cannot reach any output, and the generated code still carries the work. Equivalent only if no rare, tail, empty-input, all-invalid or fallback path consumes it, and no value in it serves as an identity, a padding value or a safe address.",
134+ "bound": ["算法", "VEC", "Scalar", "访存"]
135+ },
136+ {
137+ "id": "F-19",
138+ "stage": "frontend",
139+ "prior_gain": 0.5,
140+ "delta": "Compute a repeated production once and share it with every consumer, instead of rebuilding it per consumer. Applies when two chains run the same scan, reduction or intermediate construction over the same input, range, type, layout and masking, and the first consumer does not overwrite the result. Equivalent only if every ordering and rounding semantic agrees between the two, and sharing does not force a spill or exceed the on-chip budget.",
141+ "bound": ["算法", "VEC", "Scalar", "访存"]
142+ },
143+ {
144+ "id": "F-20",
145+ "stage": "frontend",
146+ "prior_gain": 0.5,
147+ "delta": "Widen the tile or strip so one logical item is cut into fewer pieces, instead of paying the per-piece fixed cost many times over. Applies when an item is split into many small tiles that each repeat descriptor, mask and setup work, so the fixed cost grows with the tile count and dominates, and adjacent pieces can be merged while the budget still holds the rotating slots and live roles. Equivalent only if the valid shape, the tail's neutral values, the offset unit and every load, store and reduction are recomputed for the new width.",
148+ "bound": ["Scalar", "调度", "访存", "流水"]
149+ },
150+ {
151+ "id": "F-21",
152+ "stage": "frontend",
153+ "prior_gain": 0.5,
154+ "delta": "Compute only the part of the domain the consumer needs, instead of the whole sort, scan or reduction. Applies when the contract and a full def-use argument show the consumer needs a strict subset -- proved there, never inferred from the inputs that have been seen -- and the omitted part cannot affect any observable output.",
155+ "bound": ["算法", "VEC", "Scalar", "访存"]
156+ },
157+ {
158+ "id": "F-22",
159+ "stage": "frontend",
160+ "prior_gain": 0.5,
161+ "delta": "Connect a producer to its consumer directly, instead of writing the intermediate out and reading it back. Applies when the intermediate is still consumed, but the two sides' live ranges, types, owners, synchronisation and capacity allow the hand-off to stay on-chip. Equivalent only if the intermediate is not itself an output and the contract does not require it to be materialised.",
162+ "moves": ["workspace"],
163+ "bound": ["访存", "流水", "同步"]
164+ },
165+ {
166+ "id": "F-23",
167+ "stage": "frontend",
168+ "prior_gain": 0.5,
169+ "delta": "Specialise the resource allocation and the hot path at build time for each of a small number of metadata classes, instead of carrying one configuration that has to suit them all. Applies when the classification depends only on metadata the contract permits, the classes are finitely many, and it stays one build and one launch. Equivalent only if every class keeps the same public contract.",
170+ "bound": ["Scalar", "资源", "调度"]
171+ },
172+ {
173+ "id": "F-24",
174+ "stage": "frontend",
175+ "prior_gain": 0.5,
176+ "delta": "Let mutually exclusive stages reuse one physical on-chip arena instead of giving each its own. Applies when the live intervals of the differently typed tile groups are genuinely disjoint, and the addresses, capacity, alignment and mutual-exclusion ids are each valid and do not conflict. Equivalent only if every launched lane reaches the hard barrier unconditionally, so no lane is still holding the arena when the next stage claims it.",
177+ "moves": ["workspace"],
178+ "bound": ["片上容量", "搬运"]
179+ },
180+ {
181+ "id": "F-25",
182+ "stage": "frontend",
183+ "delta": "Move a computation that is a contraction in shape onto the matrix unit, instead of carrying it out as vector operations. Applies when the kernel computes a product-and-sum over a shared axis in the vector unit, and the matrix unit can take its operand shapes -- the move introduces new tile sites for the operands and the accumulator. Equivalent only if the accumulator's precision matches the rounding of the vector path it replaces, so nothing is spent from the accuracy budget.",
184+ "prior_gain": 0.9,
185+ "bound": ["VEC"],
186+ "conversion": true
187+ },
188+ {
189+ "id": "S-1",
190+ "stage": "swimlane",
191+ "requires": ["has_cube_op"],
192+ "delta": "Deep-tune the Cube tile shapes against the pipeline, trading reloads of the on-chip operand against a split of the reduction axis. Applies when the structure has moved since the Cube shapes were last searched, or they were never searched on this structure. Equivalent only if the shape stays expressible -- `M > 128` is forbidden by the L0C `mad` column pitch (`ceil16(m)`), so windowing N is the supported direction.",
193+ "prior_gain": 0.5
194+ },
195+ {
196+ "id": "S-2",
197+ "stage": "swimlane",
198+ "delta": "Deep-tune the Vector tile shapes against the hand-off to the stages on either side. Applies when the structure has moved since the Vector shapes were last searched, or they were never searched on this structure. TPE searches only the Vector tile shapes; buffering depth and the pipeline's preload VALUE remain agent-owned choices under a separate concrete edit. There is no `vec_nbuffer_setting` on this arm.",
199+ "prior_gain": 0.5
200+ },
201+ {
202+ "id": "S-3",
203+ "stage": "swimlane",
204+ "delta": "Set the pipeline knobs on the kernel's entry point: how far ahead the pipeline preloads, and whether mutual exclusion is inferred. ENUMERATE, do not search -- the space is small enough to walk, and walking it is cheaper than modelling it. A larger preload hides more transfer latency and pays for it in a longer fill and drain, so the useful value is per kernel. Applies when the kernel has `@pl.pipeline.stage` functions; without them `pipeline=` is refused after the build has already been paid for, and only the mutual-exclusion knob remains.",
205+ "prior_gain": 0.5
206+ },
207+ {
208+ "id": "S-4",
209+ "stage": "swimlane",
210+ "prior_gain": 0.5,
211+ "delta": "Overlap the accumulator's write-out with the next multiply at a finer granularity than the whole output block. Applies when the accumulator is written straight out with no post-processing stage, the write-out and the multiply are serialised end to end, and the accumulator space is too full to hold a second buffer.",
212+ "requires": ["has_cube_op"],
213+ "bound": ["MAC", "FIXPIPE"]
214+ },
215+ {
216+ "id": "S-5",
217+ "stage": "swimlane",
218+ "prior_gain": 0.5,
219+ "delta": "Place the two alternating operand buffers in different banks of the on-chip space instead of letting them collide. Applies when the inner loop holds two or more operand buffers and each one fits in half the space.",
220+ "requires": ["has_cube_op"],
221+ "bound": ["MTE1"]
222+ },
223+ {
224+ "id": "S-6",
225+ "stage": "swimlane",
226+ "prior_gain": 0.5,
227+ "delta": "Split the reduction axis across cores and accumulate the partial results atomically, instead of giving each core a whole output tile. Applies when there are fewer output tiles than cores, the reduction axis is long, and the output type supports atomic accumulation. Equivalent only if the precision budget allows the partial sums to be combined in an order that is not fixed.",
228+ "requires": ["has_cube_op"],
229+ "bound": ["MAC"]
230+ },
231+ {
232+ "id": "S-7",
233+ "stage": "swimlane",
234+ "prior_gain": 0.5,
235+ "delta": "Issue the next operand's transfer before the current one is consumed, instead of waiting for the dependence to clear. Applies when double buffering is already in place but the pipeline still shows transfer gaps, and the inner loop runs at least twice.",
236+ "requires": ["has_cube_op"],
237+ "bound": ["MTE2"]
238+ },
239+ {
240+ "id": "S-8",
241+ "stage": "swimlane",
242+ "prior_gain": 0.5,
243+ "delta": "Assign cores over one flat tile space spanning all groups instead of group by group. Applies when a single kernel carries many groups of the same operation and no group's tile count divides the core count, so each group leaves cores idle at its boundary.",
244+ "requires": ["has_cube_op"],
245+ "bound": ["MAC"]
246+ },
247+ {
248+ "id": "S-9",
249+ "stage": "swimlane",
250+ "prior_gain": 0.5,
251+ "delta": "Increase the overlap between transfer and compute when no single unit is the bottleneck. Applies when every unit's utilisation is low, the trace shows pipeline bubbles and waiting intervals, and no one stage can be named as the limit.",
252+ "bound": ["PIPELINE"]
253+ },
254+ {
255+ "id": "S-10",
256+ "stage": "swimlane",
257+ "prior_gain": 0.5,
258+ "delta": "Reorder the stages so compute issues ahead of the previous iteration's write-out, delaying the write by one step. Applies when double buffering is on but load, compute and store still run in sequence, and each core has enough tiles for the pipeline to fill.",
259+ "bound": ["PIPELINE"]
260+ },
261+ {
262+ "id": "S-11",
263+ "stage": "swimlane",
264+ "prior_gain": 0.5,
265+ "delta": "Interleave the two compute units' work from adjacent iterations instead of running each unit's whole stage in turn. Applies when the two have independent work in neighbouring iterations and the pipeline currently serialises them.",
266+ "bound": ["PIPELINE"]
267+ },
268+ {
269+ "id": "S-12",
270+ "stage": "swimlane",
271+ "prior_gain": 0.5,
272+ "delta": "Track the buffer index of an address space shared by several tile groups with one explicit shared counter, instead of letting each group advance its own. Applies when several tile groups share the same addresses and mutual-exclusion ids, and different phases call the groups an unequal number of times. Equivalent only if every phase advances the shared counter, including a phase that skips its body.",
273+ "bound": ["PIPELINE"]
274+ },
275+ {
276+ "id": "S-13",
277+ "stage": "swimlane",
278+ "prior_gain": 0.5,
279+ "delta": "Give the short-lived input slot and the long-lived accumulation state separate roles, so the next load can overlap the fold before it. Applies when the rotating input slots are held by in-place accumulation state, serialising a load against that fold, and the live ranges show both roles must exist at once. Equivalent only if the separation comes from a real slot rather than from overlapping addresses or a reused mutual-exclusion id, and it does not add a copy to buy the independence.",
280+ "bound": ["VEC", "访存", "流水"]
281+ },
282+ {
283+ "id": "S-14",
284+ "stage": "swimlane",
285+ "prior_gain": 0.9,
286+ "delta": "Tune the core count, the owner granularity and the tail policy as one candidate instead of one at a time. Applies when idle cores, a long tail or a wide per-core spread appears, and changing the core count alone neither explains nor reproduces the result. Equivalent only if every candidate covers each work item exactly once with disjoint owners -- or, where they overlap, the overlap is a reduction the contract allows.",
287+ "bound": ["Launch", "调度", "Scalar", "访存"]
288+ },
289+ {
290+ "id": "S-15",
291+ "stage": "swimlane",
292+ "prior_gain": 0.9,
293+ "delta": "Remove a synchronisation whose protected resource has no later consumer. Applies when a wait or barrier on the hot path can be mapped to a specific producer, consumer, resource and retirement point, and that consumer does not exist. Equivalent only if the two sides share no resource the data flow does not show -- a reused on-chip address, a scratch value read back later, or a wrap-around that overwrites.",
294+ "bound": ["同步", "Scalar", "流水"]
295+ },
296+ {
297+ "id": "S-16",
298+ "stage": "swimlane",
299+ "prior_gain": 0.5,
300+ "delta": "Process several independent work items in one task, instead of building a task, descriptor and setup for each. Applies when each item's real work is small beside its fixed cost, the items are independent and layout-compatible, one owner can group them, and grouping does not worsen the access pattern. Equivalent only if no prefix, recurrence, cross-item reduction or visible ordering runs between them, and the last group's real item count, each item's tail and each offset stay separately correct.",
301+ "bound": ["Launch", "Scalar", "调度", "访存"]
302+ },
303+ {
304+ "id": "S-17",
305+ "stage": "swimlane",
306+ "prior_gain": 0.5,
307+ "delta": "Reuse one copy of a shared operand across several outputs of the same partition, instead of re-staging it per output. Applies when at least two outputs take exactly the same operand, each partition's chain opens and closes independently, and the accumulator and operand budgets hold the extra outputs. Equivalent only if each output keeps its own reduction order and its single writer.",
308+ "requires": ["has_cube_op"],
309+ "bound": ["Cube", "搬运", "流水"]
310+ },
311+ {
312+ "id": "S-18",
313+ "stage": "swimlane",
314+ "prior_gain": 0.5,
315+ "delta": "Reuse one set of shared operand residuals across an adjacent pair of outputs, instead of loading them once per output. Applies when complete adjacent pairs exist whose residuals are identical, and the accumulator and operand budgets hold both outputs at once. Equivalent only if the per-output accumulation order, the odd tail and the single writer are unchanged.",
316+ "requires": ["has_cube_op"],
317+ "bound": ["Cube", "搬运"]
318+ },
319+ {
320+ "id": "S-19",
321+ "stage": "swimlane",
322+ "prior_gain": 0.5,
323+ "delta": "Flatten a multi-stage logical task onto the physical cores, so fewer cores idle and the scheduling tail shortens. Applies when a single kernel already has several stages, the task mapping can be changed, and each section can recover its physical id independently under its target engine's semantics. Equivalent only if each stage is covered exactly once, every launched core reaches the barrier in the same order and the same number of times, and the tail, the dataflow and the reduction order are unchanged.",
324+ "requires": ["module_count >= 2"],
325+ "bound": ["调度", "Scalar", "流水"]
326+ },
327+ {
328+ "id": "I-1",
329+ "stage": "incore",
330+ "prior_gain": 0.5,
331+ "delta": "Fuse adjacent element-wise chains so their intermediate never leaves the unit. Applies when the intermediate has no consumer outside the chain, the generated code still writes it out and reads it back, and the on-chip budget holds the fused live set.",
332+ "moves": ["workspace"],
333+ "bound": ["VEC", "MTE2", "MTE3"]
334+ },
335+ {
336+ "id": "I-2",
337+ "stage": "incore",
338+ "prior_gain": 0.5,
339+ "delta": "Remove a type conversion, batch several into one pass, or move one to where its result is used. Applies when a conversion is redundant, several can share a pass, or one materialises a staging tile of its own. Equivalent only if the type, the rounding and the value range make the rewritten conversion exact.",
340+ "bound": ["VEC"]
341+ },
342+ {
343+ "id": "I-3",
344+ "stage": "incore",
345+ "prior_gain": 0.5,
346+ "delta": "Fuse a multiply and the add that consumes it into one operation. Applies when the two appear together, the compiler has not fused them already, and the intermediate product has no other consumer.",
347+ "bound": ["VEC"]
348+ },
349+ {
350+ "id": "I-4",
351+ "stage": "incore",
352+ "prior_gain": 0.5,
353+ "delta": "Broadcast a reduced value in registers instead of storing it and reading it back as a scalar. Applies when a per-row reduction is followed by a scalar round trip, or by a store and reload of a tile, and the consumer can read the value within the same vector pass.",
354+ "bound": ["VEC", "SCALAR"]
355+ },
356+ {
357+ "id": "I-5",
358+ "stage": "incore",
359+ "prior_gain": 0.5,
360+ "delta": "Keep an intermediate in registers instead of materialising it on-chip. Applies when it serves only the step immediately after it, has no role across iterations and is not an output, and the generated code stores and reloads it.",
361+ "moves": ["workspace"],
362+ "bound": ["VEC", "MTE2", "MTE3"]
363+ },
364+ {
365+ "id": "I-6",
366+ "stage": "incore",
367+ "prior_gain": 0.5,
368+ "delta": "Broadcast a loop-invariant once outside the loop, and merge several rows into one vector operation. Applies when the value does not change across the reusing loop, and the rows to be merged agree in layout, tiling and masking.",
369+ "bound": ["VEC", "MTE2"]
370+ },
371+ {
372+ "id": "I-7",
373+ "stage": "incore",
374+ "prior_gain": 0.5,
375+ "delta": "Replace a reduction written as a scalar loop or a linear dependence chain with the hardware's tree reduction. Applies when the result is a single value, or one that can be broadcast, and the element type and masking fit the reduction primitive.",
376+ "bound": ["VEC"]
377+ },
378+ {
379+ "id": "I-8",
380+ "stage": "incore",
381+ "prior_gain": 0.5,
382+ "delta": "Accumulate into several independent registers and combine them at the end, instead of into one. Applies when a single accumulator's read-after-write chain is the limit rather than register pressure, and the reduction is long enough to pay for the final combine. Equivalent only if the reduction's order may change.",
383+ "bound": ["VEC"]
384+ },
385+ {
386+ "id": "I-9",
387+ "stage": "incore",
388+ "prior_gain": 0.5,
389+ "delta": "Move a loop that repeats the same vector body inside that body. Applies when the iterations are independent of each other, their setup does not change between them, and the merged body's register and tile lifetimes fit.",
390+ "bound": ["VEC", "SCALAR"]
391+ },
392+ {
393+ "id": "I-10",
394+ "stage": "incore",
395+ "prior_gain": 0.5,
396+ "delta": "Unroll a loop whose trip count is known when the kernel is built. Applies when that count is small, and the unrolled offsets and masks are the same work as the loop's.",
397+ "bound": ["VEC"]
398+ },
399+ {
400+ "id": "I-11",
401+ "stage": "incore",
402+ "prior_gain": 0.5,
403+ "delta": "Reduce how much transcendental arithmetic runs. Applies when it dominates the hot path and one of three openings exists: a repeated call whose result can be reused, a fused form the language offers, or a table or approximation whose accuracy can be shown to fit the precision budget.",
404+ "bound": ["VEC"]
405+ },
406+ {
407+ "id": "I-12",
408+ "stage": "incore",
409+ "prior_gain": 0.5,
410+ "delta": "Split one vector body into specialised bodies along a provable condition, so each holds fewer live values. Applies when the generated code spills and reloads, the condition can be proved where the split is made, and each specialised body genuinely drops logic rather than branching around it.",
411+ "bound": ["VEC"]
412+ },
413+ {
414+ "id": "I-13",
415+ "stage": "incore",
416+ "prior_gain": 0.5,
417+ "delta": "Handle the full and the tail iterations with one masked body instead of two copies. Applies when the two bodies do the same work, the active count per step can be recomputed exactly from the total and the offset, and both use the same element granularity.",
418+ "bound": ["VEC", "SCALAR"]
419+ },
420+ {
421+ "id": "I-14",
422+ "stage": "incore",
423+ "prior_gain": 0.5,
424+ "delta": "Flip the layout so the reduction axis lies along the vector lanes, removing cross-lane reductions and scalar packing. Applies when the hot body reduces along an axis the layout places across lanes, the producer can be rewritten to emit the transposed form, and the flipped live set fits on-chip. Equivalent only if no reduced result is consumed across the axis that was flipped.",
425+ "bound": ["VEC"]
426+ },
427+ {
428+ "id": "I-15",
429+ "stage": "incore",
430+ "prior_gain": 0.5,
431+ "delta": "Hoist redundant scalar computation out of the loop. Applies when the scalar lane is busy while the vector lane idles, or the shape is small enough that address arithmetic dominates, and the loop recomputes divisions, remainders or offsets that do not change.",
432+ "bound": ["SCALAR"]
433+ },
434+ {
435+ "id": "I-16",
436+ "stage": "incore",
437+ "prior_gain": 0.5,
438+ "delta": "Take a faster association of the arithmetic only where the value range proves it stays inside the precision budget, keeping the original order elsewhere. Applies when regrouping, tree folding or cross-row merging changes the order of floating-point operations, and the error depends on the input range. Equivalent only if the range is established by the frozen contract -- a shape, a type tier or a sample of inputs is not a proof.",
439+ "bound": ["VEC", "精度", "算法"]
440+ },
441+ {
442+ "id": "I-17",
443+ "stage": "incore",
444+ "prior_gain": 0.5,
445+ "delta": "Cut the downstream work and transfers to the lanes that are actually valid, instead of carrying padding lanes through compare, scan, merge and movement. Applies when the physical tile is wider than the real extent, the padding lanes still take part in that work after being neutralised, and the real valid domain is expressible. Equivalent only if the identity values, predicates and safe addresses that correctness rests on stay in place, and invalid lanes are masked before an address is formed rather than only at the final store.",
446+ "bound": ["算法", "VEC", "访存"]
447+ },
448+ {
449+ "id": "I-18",
450+ "stage": "incore",
451+ "prior_gain": 0.5,
452+ "delta": "Classify once on metadata and branch to a small number of specialised paths, so the inner loop stops evaluating the condition. Applies when a condition tested per row, per rank or per tile is constant over the whole owner, stage or a finite shape class, and the generated code still carries the branch and its unused path in the hot region. Equivalent only if the condition carries no state between iterations.",
453+ "bound": ["Scalar", "调度", "VEC", "Cube"]
454+ },
455+ {
456+ "id": "I-19",
457+ "stage": "incore",
458+ "prior_gain": 0.5,
459+ "delta": "Hoist the invariant parts of address and descriptor construction out of the loop, leaving only the fields that really change inside it. Applies when shape products, axis normalisation, base addresses, strides or descriptor parameters are constant across a batch of work items but rebuilt every iteration, and that cost is visible in the generated code. Equivalent only if the per-item valid shape, tail and offset are not treated as invariant.",
460+ "bound": ["Scalar", "调度", "访存"]
461+ },
462+ {
463+ "id": "I-20",
464+ "stage": "incore",
465+ "prior_gain": 0.5,
466+ "delta": "Keep a data-parallel computation in the vector path, instead of routing it through scalar reads and broadcasts or a per-element loop. Applies when a compare, select, reduce or merge could run data-parallel but the generated code still moves the value out to the scalar side and back, or walks it element by element. Equivalent only if no real serial dependence exists, and where parallelising changes the reduction order the precision is re-established against the frozen contract.",
467+ "bound": ["Scalar", "VEC", "访存"]
468+ },
469+ {
470+ "id": "I-21",
471+ "stage": "incore",
472+ "prior_gain": 0.5,
473+ "delta": "Make a small bounded control or reduction topology static, removing the dynamic back edge and the repeated start-up it costs. Applies when the frozen contract proves the trip count or the topology is fixed and small, and that dynamic edge, the repeated start-up, or a single accumulator's dependence chain is the main cost. Equivalent only if the amount of arithmetic, the owner and the output semantics do not change, and the static form neither spills nor outgrows the code budget.",
474+ "bound": ["Scalar", "VEC", "Cube", "精度"]
475+ },
476+ {
477+ "id": "I-22",
478+ "stage": "incore",
479+ "prior_gain": 0.5,
480+ "delta": "Narrow an internal key, index or value to the width its proved range needs. Applies when the full reachable range is established by the frozen contract or by permitted metadata, and the current width has a measurable cost in scalar work, vector work, registers or transfers. Equivalent only if no overflow or precision gate is bypassed on the way.",
481+ "moves": ["workspace"],
482+ "bound": ["Scalar", "VEC", "访存", "精度"]
483+ },
484+ {
485+ "id": "I-23",
486+ "stage": "incore",
487+ "prior_gain": 0.5,
488+ "delta": "Accumulate a dot product over a panel with a scalar broadcast in the vector unit, instead of taking the general path. Applies when the operator has a panel dot of that shape and its layout, stride, masking and tail are expressible. Equivalent only if the panel width divides the group width or an explicit tail path exists, and the frozen precision allows that accumulation and its compensation.",
489+ "requires": ["has_cube_op"],
490+ "bound": ["Vector", "Scalar", "搬运"]
491+ }
492+]
@@ -0,0 +1,26 @@
1+# Base campaign workflow
2+ 
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.
5+ 
6+## Initialize once
7+ 
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`).
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.
10+The memory objective sums source-derived high-water marks. Treat an incomplete reading as unknown.
11+ 
12+```sh
13+python3 "$S/measure.py" --op-file "$OP" --op-dir "$D" --device "$DEVICE" \
14+ --test-command "$TEST_COMMAND" --test-files "$TEST_FILES" \
15+ --memory-capacity "$CAPACITY" --out "$D/baseline.json"
16+python3 "$S/panko_harness.py" init --op-dir "$D" --op kernel --op-file "$OP" \
17+ --device "$DEVICE" --config '{"eval_budget":40}' --measurement-file "$D/baseline.json"
18+python3 "$S/panko_harness.py" select --op-dir "$D"
19+```
20+ 
21+## Verify and deliver
22+ 
23+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.
25+Run `report --op-dir "$D"`, check the restored source hash and retain the frontier sources.
26+Give the verifier the delivered file and hash, frozen test/reference files, command, environment, tolerances and receipts. Report success only after independent PASS.
@@ -0,0 +1,13 @@
1+# From profile to structural edit
2+ 
3+Inspect the continuation base’s warm latency, spread and launch count. For detailed counters, use the retained msprof CSV and [performance diagnosis](../../pypto-pro-kernel/references/diagnostics/performance.md).
4+For the selected action, cite one or two readings and the source function. Propose one edit, predict a metric change and say what would disprove it.
5+ 
6+- **SIMD batching:** map independent chains to lanes. Preserve order and private state. Compare setup savings with packing and register costs.
7+- **Shared production:** reuse a result only across matching inputs, masks, types and rounding. Check lifetime, reloads and synchronization.
8+- **Direct layout:** have the producer emit its consumer’s layout. Check all readers, allocation feasibility and transfers saved.
9+- **Earlier readiness:** advance work once its inputs are ready. Check stale reads, buffer reuse and tail/skip synchronization.
10+- **Cost-aware placement:** compare per-core finish times. Adjust partitions, core count or slots with exact coverage and chain order. Check tail time, overhead and storage within the measured boundary.
11+ 
12+Leave tile shapes to TPE. Compare precision, latency and counters under matched settings using the measured source hash: RECORD may already have changed the working file.
13+Use `evolve` to update priorities. Keep acquisition failures separate from kernel failures.
@@ -0,0 +1,12 @@
1+# Pro runtime
2+ 
3+Pro initialization copies the shared PyPTO skill’s `scripts/` into the installed Pro skill’s `scripts/_core/`. Rerun initialization after a core update.
4+At runtime, `panko_harness.py` registers `pro_backend.py`. Imports through `panko_core` use `bootstrap.core_path()` to find the installed copy or the sibling PyPTO scripts in a checkout.
5+ 
6+The core handles search, Pareto acceptance, rollback, STOP and ABBA delivery. Pro supplies its action catalog, legal tile and address rewrites, source staging, NPU measurements and source-derived memory usage.
7+ 
8+Run the host tests from the repository root:
9+ 
10+```sh
11+python3 -m unittest discover -s cannbot-skills/plugins-official/pypto-pro-op-orchestrator/tests
12+```
@@ -0,0 +1,19 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+"""Public PyPTO-Pro evaluator and tile API."""
10+from bootstrap import activate
11+ 
12+activate()
13+ 
14+ 
15+def __getattr__(name):
16+ from importlib import import_module
17+ if name not in {"apply", "block", "domain", "lever", "semantic", "evaluator"}:
18+ raise AttributeError(name)
19+ return import_module("." + name, __name__)
@@ -0,0 +1,673 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+"""Edit Pro tile shapes and replan addresses. Structural and launch settings belong to the agent."""
10+ 
11+__all__ = ["ApplyConflict", "Edit", "MAX_VEC_ARITY", "Site", "UNSET", "apply", "apply_edits", "current_config",
12+ "discover_sites", "launch_params", "relayout", "split_launch", "rewritable", "set_addrs", "set_depth",
13+ "set_shape", "tie_groups", "tunable_sites"]
14+ 
15+import ast
16+import logging
17+import re
18+from dataclasses import dataclass
19+from typing import List, MutableSequence, Optional, Sequence, Tuple
20+ 
21+# Use the reader’s UTF-8 column offsets to splice the same source spans.
22+from panko_core.bayesian_optimization.apply import (MAX_VEC_ARITY, UNSET, Site, _read_site, loop_spans, splice_edits,
23+ tie_groups as loop_groups)
24+from panko_core.pypto_ast import jit_decorators, keyword_value
25+from source_analysis.tile_sites import Offsets, TileProgram, read_sites
26+ 
27+from . import space
28+ 
29+logger = logging.getLogger(__name__)
30+ 
31+ 
32+def source_constants(extra_consts=None):
33+ """Copy bindings for this program; omitted bindings never inherit another run."""
34+ return dict(extra_consts or {})
35+ 
36+ 
37+class ApplyConflict(ValueError):
38+ """The edits do not describe a rewrite: they overlap, miss, or change nothing."""
39+ 
40+ 
41+@dataclass(frozen=True)
42+class Edit:
43+ """Replace `src[start:end]` with `text`. `what` is for the diff and the log."""
44+ 
45+ start: int
46+ end: int
47+ text: str
48+ what: str
49+ 
50+ @property
51+ def is_insert(self) -> bool:
52+ return self.start == self.end
53+ 
54+ def describe(self) -> str:
55+ return "%s: [%d,%d) -> %r" % (self.what, self.start, self.end, self.text)
56+ 
57+ 
58+def apply_edits(src: str, edits: Sequence[Edit]) -> str:
59+ """Apply original-source edits right to left, rejecting overlaps, invalid spans and no-ops."""
60+ if not edits:
61+ return src
62+ 
63+ n = len(src)
64+ for edit in edits:
65+ if not isinstance(edit, Edit):
66+ raise ApplyConflict("not an Edit: %r" % (edit,))
67+ if edit.start < 0 or edit.end < edit.start or edit.end > n:
68+ raise ApplyConflict("%s: span [%d,%d) is out of range for a %d-byte source" % (edit.what, edit.start,
69+ edit.end, n))
70+ if src[edit.start:edit.end] == edit.text:
71+ raise ApplyConflict(
72+ "%s: span [%d,%d) already reads %r; a no-op edit means the caller "
73+ "thinks it changed something it did not"
74+ % (edit.what, edit.start, edit.end, edit.text)
75+ )
76+ 
77+ ordered = sorted(edits, key=lambda e: (e.start, e.end))
78+ for earlier, later in zip(ordered, ordered[1:]):
79+ if later.start < earlier.end or later.start == earlier.start:
80+ raise ApplyConflict("overlapping edits: %s and %s" % (earlier.describe(), later.describe()))
81+ 
82+ return splice_edits(src, ((e.start, e.end, e.text) for e in reversed(ordered)))
83+ 
84+ 
85+def _address_literal(text):
86+ stripped = (text or "").strip()
87+ if not stripped:
88+ return "missing", None
89+ try:
90+ node = ast.parse(stripped, mode="eval").body
91+ except SyntaxError:
92+ return "other", None
93+ if isinstance(node, ast.Name):
94+ return "name", None
95+ if _nonnegative_address(node):
96+ return "int", [node.value]
97+ if isinstance(node, (ast.List, ast.Tuple)) and node.elts and all(_nonnegative_address(e) for e in node.elts):
98+ return "list", [e.value for e in node.elts]
99+ return "other", None
100+ 
@@ -0,0 +1,118 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+"""Run shape-only TPE after a tile action or structural edit. Charge measurements to the block."""
10+import math
11+ 
12+from panko_core.bayesian_optimization import block as shared_block
13+from panko import measurement as _measure
14+ 
15+from . import apply
16+from . import domain as domain_mod
17+from . import driver, lever, policy
18+from . import seed as seed_mod
19+from . import space
20+ 
21+ 
22+BlockOptions = shared_block.BlockOptions
23+ 
24+ 
25+def _block_start_points(src, hw, opts, sites):
26+ """Admit warm seeds without dropping the measured incumbent."""
27+ warm, measured, incumbent = shared_block.split_seed_points(lever.seed_points(
28+ src, hw, opts.dtype_bytes, opts.current_latency,
29+ widths=(opts.domain or {}).get("vec_dtype_bytes"), dom=opts.domain))
30+ groups = policy.shared_shape_groups(sites, domain=opts.domain) if opts.startup_cover else None
31+ return shared_block.complete_warm_starts(warm, measured, incumbent, sites, hw, opts,
32+ seed_mod, domain_mod, groups=groups)
33+ 
34+ 
35+def _tile_sites(src, hw, opts):
36+ sites = policy.shape_sites(apply.tunable_sites(src))
37+ if sites:
38+ return sites, None
39+ refused = apply.refusals(src)
40+ if refused:
41+ details = "; ".join("%s (%s)" % pair for pair in sorted(refused.items()))
42+ return [], "no tunable tile site: all %d pl.make_tile_group site(s) were refused -- %s" % (len(refused),
43+ details)
44+ return [], "no tunable tile site; this kernel writes no pl.make_tile_group(type=pl.TileType(shape=[...]))"
45+ 
46+ 
47+def _search(objective, sites, hw, opts, warm, measured, incumbent):
48+ options = shared_block.search_options(driver.SearchOptions, opts, warm, incumbent,
49+ apply.tie_groups(sites, incumbent), observed=measured, sites_per_draw=1)
50+ return driver.run_bo(objective, sites, hw, options)
51+ 
52+ 
53+def run(op_file, objective, hw, opts=None, *, confirm=None):
54+ opts = opts or BlockOptions()
55+ return shared_block.run_search(op_file, objective, hw, opts, discover=_tile_sites, seeds=_block_start_points,
56+ search=_search, prepare=lambda src,
57+ hw: apply.tile_program(src, getattr(hw, "extra_consts", None)), keep_ties=True,
58+ confirm=confirm or confirm_block_winner)
59+ 
60+ 
61+# Assumed log-difference noise for confirmation sample sizing.
62+CONFIRM_SIGMA_D = 0.02
63+ 
64+CONFIRM_RESOLVE = 0.02
65+ 
66+#: The one-sided z the pair count is sized at. 1.645 = 95 %.
67+CONFIRM_Z = 1.645
68+ 
69+CONFIRM_PAIRS = max(2, math.ceil((CONFIRM_Z * CONFIRM_SIGMA_D / CONFIRM_RESOLVE) ** 2))
70+ 
71+ 
72+def confirm_block_winner(objective, incumbent, winner, seed=0):
73+ return _measure.confirm_block_winner(objective, incumbent, winner, seed, pairs=CONFIRM_PAIRS)
74+ 
75+ 
76+def apply_best(src, best_config, extra_consts=None):
77+ """Apply all winning site edits and return (source, changed-site count)."""
78+ if not best_config:
79+ return src, 0
80+ return apply.apply(src, best_config, extra_consts)
81+ 
82+ 
83+def clusters_for(src, extra_consts=None, tune_launch=False, domain=None):
84+ """Size the sweep using the sampler’s tied groups and active case constants."""
85+ try:
86+ program = apply.tile_program(src, extra_consts)
87+ sites = policy.shape_sites(apply.tunable_sites(program))
88+ except SyntaxError:
89+ return []
90+ incumbent = apply.incumbent_config(program)
91+ groups = policy.shared_shape_groups(sites, domain=domain)
92+ tie = policy.expanded_ties(sites, apply.tie_groups(sites, incumbent), groups)
93+ return space.clusters(sites, groups, tie)
94+ 
95+ 
96+def hw_for(op_file, live_tiles=None, envelope=None, author_src=None, extra_consts=None):
97+ """Return the hardware envelope and derived domain used for static checks.
98+ 
99+ live_tiles describes simultaneous residency after structural edits. The caller supplies
100+ the same chip capacities as the feasibility gate. Calibration requires design-specific L1 data.
101+ Determine address ownership from the baseline author_src; use op_file when it is the baseline.
102+ """
103+ env = envelope or {}
104+ program, domain = domain_mod.analyze_file(op_file, live_tiles, env.get("ub_kb"), extra_consts)
105+ kw = {field: env[key] for field, key in shared_block.HW_FROM_ENVELOPE if key in env}
106+ consts = dict(domain.get("extra_consts") or {})
107+ sites = program.active_sites if program else ()
108+ author = sites if program and author_src == program.src else space.author_sites_of(author_src, consts)
109+ hw = space.HW(calibrated=False,
110+ dtype_bytes=domain.get("dtype_bytes", 4),
111+ vec_dtype_bytes=domain.get("vec_dtype_bytes"),
112+ vec_trailing_ok=domain.get("vec_trailing"),
113+ n_live_tiles=domain.get("live_tiles", 0),
114+ sites=sites, extra_consts=consts,
115+ # Resolve baseline sites using the same case constants as the candidate.
116+ author_sites=author,
117+ **kw)
118+ return hw, domain
@@ -0,0 +1,608 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+"""Derive legal Pro tile extents, move dependencies and the fingerprint that determines when to retune."""
10+import hashlib
11+import json
12+import logging
13+import math
14+import os
15+from pathlib import Path
16+from typing import Mapping
17+ 
18+from memory import onchip_layout
19+from source_analysis import tile_sites
20+ 
21+logger = logging.getLogger(__name__)
22+ 
23+DTYPE_BYTES = onchip_layout.DTYPE_BYTES
24+ 
25+# Zero disables the residency bound when live tile count is unknown.
26+DEFAULT_LIVE_TILES = 0
27+ 
28+ENFORCE_MOVE_LOCKS = True
29+ 
30+ 
31+def resolve_extra_consts(src, op_file=None, extra_consts=None):
32+ """Resolve integer constants imported from sibling modules through the source reader."""
33+ from source_analysis.case_context import validate_context
34+ validate_context(extra_consts)
35+ resolved = tile_sites.sibling_constants(src, op_file)
36+ resolved.update(extra_consts or {})
37+ return resolved
38+ 
39+ 
40+def _width(dtype_text):
41+ return onchip_layout.width_of_text(dtype_text)
42+ 
43+ 
44+def site_report(sites):
45+ """Per-site facts the rest of the domain is computed from."""
46+ out = {}
47+ for site in sites:
48+ out[site.site_id] = {
49+ "space": site.space,
50+ "dtype": onchip_layout.dtype_of(site),
51+ "dtype_bytes": _width(onchip_layout.dtype_of(site)) or None,
52+ "rank": len(site.shape),
53+ "shape": [e.value for e in site.shape],
54+ "depth": site.depth,
55+ "depth_source": site.depth_source,
56+ "depth_tunable": False, # Buffer count is fixed during shape TPE.
57+ "depth_editable": site.depth_span is not None,
58+ "valid_shape": list(getattr(site, "valid_shape", ()) or ()),
59+ "addrs": site.addrs_text,
60+ "resolvable": bool(site.resolvable),
61+ "unresolved": list(site.unresolved),
62+ }
63+ return out
64+ 
65+ 
66+def _site_widths(report, notes):
67+ """Resolve known widths and report sites that cannot be sized."""
68+ widths = {sid: cell["dtype_bytes"] for sid, cell in report.items() if cell["dtype_bytes"]}
69+ unknown = sorted(sid for sid, cell in report.items() if not cell["dtype_bytes"])
70+ if unknown:
71+ notes.append(
72+ "no element width for %s: the dtype is written as an expression, so "
73+ "these tiles cannot be sized and are refused rather than guessed at"
74+ % (", ".join(unknown),))
75+ 
76+ return widths
77+ 
78+ 
79+def _unreferenced_sites(src, sites, notes):
80+ """Report unused allocations without removing their reserved storage."""
81+ dead = tile_sites.unreferenced(src, sites) if sites else ()
82+ if dead:
83+ notes.append(
84+ "%s allocate on-chip space that nothing reads: their tile group is "
85+ "never mentioned again. The byte objective pays for them in full and "
86+ "the latency objective gains nothing. Reported, not removed -- a "
87+ "declaration may be read through an alias this cannot see, or exist "
88+ "to reserve an address another group's literal depends on"
89+ % (", ".join(dead),))
90+ 
91+ return dead
92+ 
93+ 
94+def _body_constraints(program, notes):
95+ """Read consumer windows, retaining declaration-only bounds on failure."""
96+ try:
97+ body = program.body_constraints() if program and program.active_sites else {}
98+ except (SyntaxError, ValueError) as exc:
99+ body = {}
100+ notes.append("the kernel body could not be read for consume windows "
@@ -0,0 +1,559 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+"""Run correctness-constrained TPE on measurable configurations within the Pro tile domain."""
10+import json
11+import random
12+from dataclasses import dataclass, replace
13+from typing import Any
14+import optuna
15+ 
16+from panko_core.bayesian_optimization import driver as _engine, evaluator
17+from . import domain as domain_mod, policy, space
18+from .lever import dist
19+ 
20+PENALTY = _engine.PENALTY
21+ 
22+error_signature = _engine.error_signature
23+ 
24+ 
25+# Limit persisted refusals per site.
26+SITE_REFUSALS_PER_SITE = 32
27+ 
28+ 
29+def site_delta(cfg, anchor):
30+ """Return (site_id, shape) only for a single-site change from the anchor."""
31+ if not anchor or not cfg:
32+ return None
33+ moved = [(sid, dict(c)) for sid, c in cfg.items() if dict(c) != dict(anchor.get(sid) or {})]
34+ return moved[0] if len(moved) == 1 else None
35+ 
36+ 
37+def shape_key(shape):
38+ return json.dumps(shape, sort_keys=True)
39+ 
40+ 
41+def remember_site_refusal(ctx, cfg, detail):
42+ """Cache structure-specific, single-site refusals. Capacity failures use separate ceilings."""
43+ got = None if ctx["state"].get("anchor_incorrect") else site_delta(cfg, ctx.get("anchor"))
44+ if got is None:
45+ return
46+ sid, shape = got
47+ store = ctx["state"].setdefault("site_refused", {}).setdefault(sid, {})
48+ if len(store) < SITE_REFUSALS_PER_SITE:
49+ store.setdefault(shape_key(shape), (detail or "s=0")[:160])
50+ 
51+ 
52+def site_refused(ctx, cfg):
53+ """Return the recorded reason for a known bad site shape, excluding the incumbent."""
54+ store = ctx["state"].get("site_refused") or {}
55+ if not store:
56+ return None
57+ anchor = ctx.get("anchor") or {}
58+ for sid, c in cfg.items():
59+ known = store.get(sid)
60+ if not known or dict(c) == dict(anchor.get(sid) or {}):
61+ continue # never refuse the program being tuned
62+ why = known.get(shape_key(dict(c)))
63+ if why is not None:
64+ return ("refused_site_shape", "%s: %s was measured and refused -- %s" % (sid, dict(c), why))
65+ return None
66+ 
67+ 
68+_dedup = _engine.dedup
69+ 
70+ 
71+def config_widths(opts):
72+ return _engine.site_widths(opts, live_for=domain_mod.live_for)
73+ 
74+ 
75+def _tile_bytes(cfg, dtype_bytes, widths=None):
76+ return _engine.draw_tile_bytes(cfg, dtype_bytes, widths, include_cube=False)
77+ 
78+ 
79+@dataclass
80+class SearchSeeds:
81+ """Pro seed observations and per-draw site limit."""
82+ 
83+ warm_start: Any = None
84+ observed: Any = None
85+ sites_per_draw: int = 0
86+ 
87+ 
88+@dataclass
89+class SearchOptions(_engine.SearchSettings, SearchSeeds):
90+ """Shared TPE controls following the original Pro seed arguments."""
91+ 
92+ 
93+def _in_seed_phase(ctx):
94+ """Use the draw cursor to identify queued seeds."""
95+ return ctx.get("_calls", 0) <= int(ctx.get("seeds_queued", 0) or 0)
96+ 
97+ 
98+def _clusters(ctx):
99+ """Cache the site groups used by the round-robin cursor and sweep budget."""
100+ if ctx.get("_clusters") is None:
@@ -0,0 +1,39 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+"""Process-group-aware command runner for the Pro STOP device probe."""
10+import os
11+import shutil
12+import subprocess
13+ 
14+from evaluation.process import run_captured
15+from panko_core.bayesian_optimization import evaluator as core_evaluator
16+from panko_core.bayesian_optimization.evaluator import DEVICE_CONTEXT_MARKERS, DEVICE_FAULT_MARKERS
17+ 
18+ 
19+def _run_one(step, cwd, timeout, env=None):
20+ """Resolve the executable and run one parsed step; return combined output and exit code."""
21+ argv, step_env = step
22+ run_env = {**(env or os.environ), **step_env}
23+ directory = os.path.abspath(cwd or os.curdir)
24+ command = os.path.join(directory, argv[0]) if os.path.dirname(argv[0]) else argv[0]
25+ search_path = os.pathsep.join(os.path.join(directory, entry) for entry in os.get_exec_path(run_env))
26+ exe = shutil.which(command, path=search_path)
27+ if not exe:
28+ return f"{argv[0]}: not found on PATH\n", 127
29+ try:
30+ r = run_captured([os.path.abspath(exe), *argv[1:]], cwd=cwd, env=run_env, timeout=timeout)
31+ except subprocess.TimeoutExpired as e:
32+ return e.output, 124
33+ except OSError as exc:
34+ return f"command invocation failed: {exc}\n", 126
35+ return (r.stdout or ""), r.returncode
36+ 
37+ 
38+def run_command(cmd, timeout, env=None):
39+ return core_evaluator.run_command(cmd, timeout, env, run_step=_run_one)
@@ -0,0 +1,175 @@
1+# -*- coding: utf-8 -*-
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+"""Rebuild the selected action’s Optuna study from campaign state on each dispatch."""
10+import hashlib
11+import json
12+from panko_core.bayesian_optimization import lever as core
13+from panko_core.bayesian_optimization.lever import AskOptions
14+ 
15+ 
16+from . import apply
17+from . import domain as tile_domain
18+from . import policy, space
19+ 
20+SCOPE_OF = {"F-1": "cube", "S-1": "cube", "F-2": "vec", "S-2": "vec"}
21+TILE_ACTIONS = set(SCOPE_OF)
22+ 
23+ 
24+# Map shape actions to tile sites by memory space. Mat, Left, Right and Acc serve cube
25+# operations. Vec serves vector operations.
26+SCOPE_PREFIXES = {"cube": ("mat", "left", "right", "acc"), "vec": ("vec",)}
27+ 
28+ 
29+def in_scope(site_id, scope):
30+ """Match a site to its memory-space scope. A scope of None includes every site.
31+ """
32+ return scope is None or site_id.split("#", 1)[0].split(":", 1)[-1] in SCOPE_PREFIXES.get(scope, ())
33+ 
34+ 
35+def _scoped(sites, scope):
36+ """Restrict a tile action to its eligible sites. An unscoped block searches their union."""
37+ # Unknown site kinds cannot own a recorded action delta.
38+ return [s for s in sites if in_scope(s.id, scope)]
39+ 
40+ 
41+def structural_signature(src, extra_consts=None):
42+ """Address relocation and tile edits belong to the same structural study."""
43+ try:
44+ spans = apply.erasable_spans(src, extra_consts)
45+ except SyntaxError:
46+ return "unparseable"
47+ return core.signature_from_spans(src, spans)
48+ 
49+ 
50+def lever_key(catalog_id, src, extra_consts=None):
51+ """Share observations within an action scope and structure. Unknown action IDs retain separate studies."""
52+ scope = SCOPE_OF.get(catalog_id)
53+ # Include fixed sites in the key because their shapes affect measured latency.
54+ try:
55+ held = {sid: value for sid, value in apply.current_config(src, extra_consts).items()
56+ if _is_tile(value) and not in_scope(sid, scope)}
57+ except SyntaxError:
58+ held = {}
59+ held_key = hashlib.sha256(json.dumps(held, sort_keys=True).encode()).hexdigest()[:12]
60+ constants = apply.source_constants(extra_consts)
61+ context_key = hashlib.sha256(json.dumps(constants, sort_keys=True, default=str).encode()).hexdigest()[:12]
62+ return (f"{policy.PARAMETER_SCOPE}|{scope or catalog_id}|"
63+ f"{structural_signature(src, constants)}|{held_key}|{context_key}")
64+ 
65+ 
66+def _is_tile(c):
67+ return any(k.startswith("d") for k in c)
68+ 
69+ 
70+def _shape_domain(index, arity, value):
71+ return space.admit(space.SHAPE_LADDER, value)
72+ 
73+ 
74+def _family(cur, dtype_bytes, widths=None):
75+ return core.seed_family(cur, dtype_bytes, widths, apply.MAX_VEC_ARITY, vector_domain=_shape_domain)
76+ 
77+ 
78+def seed_points(src, hw, dtype_bytes=4, current_latency=None, scope=None, widths=None, dom=None):
79+ """Return (configuration, measured latency or None, label) for the incumbent and footprint seeds."""
80+ cur = apply.current_config(src, getattr(hw, "extra_consts", None))
81+ cur = {k: v for k, v in cur.items() if _is_tile(v) and in_scope(k, scope)}
82+ options = core.SeedOptions(dtype_bytes, current_latency, scope, widths, dom)
83+ return core.seeds_from_anchor(cur, hw, options, _family, feasible=space.static_feasible, verify=tile_domain.verify)
84+ 
85+ 
86+def dist(name, sites, groups, anchor, held=None, domain=None):
87+ """Build the aligned categorical domain, retaining the incumbent and historical values."""
88+ import optuna
89+ sid, field = name.rsplit(".", 1)
90+ grouped = space.grouped_domains(groups, sites, anchor, domain)
91+ if name in grouped:
92+ return optuna.distributions.CategoricalDistribution(core.with_held(grouped[name], held))
93+ a = (anchor or {}).get(sid, {})
94+ if not (field.startswith("d") and field[1:].isdigit()):
95+ raise ValueError(f"not a tile dimension: {name}")
96+ base = space.vec_domain(sid, field, space.vec_fields(a), a, domain)
97+ return optuna.distributions.CategoricalDistribution(core.with_held(space.admit(base, a.get(field)), held))
98+ 
99+ 
100+def draw_one_site(study, ctx):
101+ rec, sites, anchor, groups = ctx["rec"], ctx["sites"], ctx["anchor"], ctx.get("groups")
102+ clusters = space.clusters(sites, groups)
103+ cluster = clusters[rec.get("cursor", 0) % len(clusters)]
104+ moving = [site for site in sites if site.id in cluster]
105+ return core.draw_cluster(study, ctx, moving, cluster[0], space, lambda name,
106+ held: dist(name, sites, groups, anchor, held, ctx.get("domain")), groups)
107+ 
108+ 
109+def _gate(cfg, hw, dtype_bytes, widths=None, dom=None):
110+ return core.gate_draw(cfg, hw, dtype_bytes, widths, dom, feasible=space.static_feasible, verify=tile_domain.verify)
111+ 
112+ 
113+def ask(state_bo, catalog_id, src, hw, opts=None):
114+ opts = opts or AskOptions()
115+ constants = getattr(hw, "extra_consts", None)
116+ key = lever_key(catalog_id, src, constants)
117+ rec = state_bo.setdefault(key, {"trials": [], "seeded": False, "pending": None})
118+ scope = SCOPE_OF.get(catalog_id)
119+ try:
120+ sites = _scoped(policy.shape_sites(apply.tunable_sites(src, constants)), scope)
121+ except SyntaxError:
122+ return None, {"reason": "unparseable"}
123+ if not sites:
124+ reason = f"no {scope} tile site" if scope else "no tunable tile site"
125+ return None, {"reason": reason, "scope": scope}
126+ 
127+ groups = policy.shared_shape_groups(sites, domain=opts.domain)
128+ rec["shape_groups"] = groups
129+ anchor = apply.current_config(src, constants)
130+ 
131+ def flatten(cfg, sites):
132+ return space.flatten(cfg, sites, groups)
133+ 
134+ if not rec["seeded"]:
135+ points = seed_points(src, hw, opts.dtype_bytes, opts.current_latency, scope, opts.vec_dtype_bytes, opts.domain)
136+ 
137+ def checked_params(cfg, label):
138+ params = flatten(cfg, sites)
139+ try:
140+ _validate_seed_parameters(params, sites, groups, anchor, opts.domain)
141+ except (ValueError, TypeError, RuntimeError) as exc:
142+ rec.setdefault("seed_skipped", []).append({
143+ "label": label, "params": params, "why": f"outside sampler domain: {exc}"})
144+ return None
145+ return params
146+ 
147+ core.fill_seeds(rec, sites, points, checked_params=checked_params)
148+ queued = core.next_seed(rec, sites, scope, flatten)
149+ if queued:
150+ if rec.get("seed_skipped"):
151+ queued[1]["seed_skipped"] = list(rec["seed_skipped"])
152+ return queued
153+ ctx = {"rec": rec, "sites": sites, "anchor": anchor, "groups": groups, "domain": opts.domain}
154+ study = core.replay_study(rec, opts.seed, lambda name, held: dist(name, sites, groups, anchor, held, opts.domain),
155+ lambda params: policy.shape_params(params, sites))
156+ return core.draw_until_feasible(study, ctx, scope, {s.id for s in sites}, hw, opts,
157+ draw_one_site, _gate, lambda trial, cfg: flatten(cfg, sites))
158+ 
159+ 
160+def tell(state_bo, catalog_id, src, s, p, extra_consts=None):
161+ rec = state_bo.get(lever_key(catalog_id, src, extra_consts))
162+ if not rec or not rec.get("pending"):
163+ return False
164+ sites = _scoped(policy.shape_sites(apply.tunable_sites(src, extra_consts)), SCOPE_OF.get(catalog_id))
165+ groups = policy.shared_shape_groups(sites, rec.get("shape_groups"))
166+ actual = space.flatten(apply.current_config(src, extra_consts), sites, groups)
167+ if actual != rec["pending"].get("params"):
168+ return False
169+ return core.record_pending(rec, s, p)
170+ 
171+ 
172+def _validate_seed_parameters(params, sites, groups, anchor, domain):
173+ """Reject seeds outside the sampler's per-parameter distributions."""
174+ for name, value in params.items():
175+ dist(name, sites, groups, anchor, domain=domain).to_internal_repr(value)