| @@ -92,7 +92,8 @@ Field notes: | |||
| 92 | drift cancels within the pair. `status`: `pending` → `confirmed` (95% bootstrap interval of | 92 | drift cancels within the pair. `status`: `pending` → `confirmed` (95% bootstrap interval of |
| 93 | median(preopt)/median(delivered) above 1) / `unconfirmed` / `regressed`; or `no_change`, | 93 | median(preopt)/median(delivered) above 1) / `unconfirmed` / `regressed`; or `no_change`, |
| 94 | `skipped`, `disabled`, `insufficient`. `arms.{preopt,delivered}` hold the readings, measured | 94 | `skipped`, `disabled`, `insufficient`. `arms.{preopt,delivered}` hold the readings, measured |
| 95 | - ABBA in `config.verify_runs / 2` per step; `result` holds the interval; `search_speedup` is | 95 | + in ABBA order. Each step uses the frozen `warmup` count (1 for older records without this field) |
| 96 | + and `runs_per_step` timed runs; `result` holds the interval; `search_speedup` is | ||
| 96 | what the search reported. The verdicts reach `frontier.json` as `front[i].verified`. | 97 | what the search reported. The verdicts reach `frontier.json` as `front[i].verified`. |
| 97 | - `config_key` — which entry of a factory kernel's per-case config table this campaign tunes: | 98 | - `config_key` — which entry of a factory kernel's per-case config table this campaign tunes: |
| 98 | `{key, action, knobs}`, or null for an ordinary kernel. `action` is `marked` or `inserted`. The | 99 | `{key, action, knobs}`, or null for an ordinary kernel. `action` is `marked` or `inserted`. The |
| @@ -144,16 +144,22 @@ def line_starts(src): | |||
| 144 | return lambda ln, col: starts[ln - 1] + col | 144 | return lambda ln, col: starts[ln - 1] + col |
| 145 | 145 | ||
| 146 | 146 | ||
| 147 | +def body_spans(tree, node_types, offset): | ||
| 148 | + """Yield each matching node and its body span in the caller's source coordinates.""" | ||
| 149 | + for node in ast.walk(tree): | ||
| 150 | + if isinstance(node, node_types) and node.body: | ||
| 151 | + first, last = node.body[0], node.body[-1] | ||
| 152 | + yield node, (offset(first.lineno, first.col_offset), | ||
| 153 | + offset(last.end_lineno, last.end_col_offset)) | ||
| 154 | + | ||
| 155 | + | ||
| 156 | +def loop_spans(tree, offset): | ||
| 157 | + return [span for _, span in body_spans(tree, (ast.For, ast.AsyncFor, ast.While), offset)] | ||
| 158 | + | ||
| 159 | + | ||
| 147 | def _func_spans(tree, off): | 160 | def _func_spans(tree, off): |
| 148 | - """{function name: byte span of its body}, for every `def` in the module.""" | 161 | + functions = body_spans(tree, (ast.FunctionDef, ast.AsyncFunctionDef), off) |
| 149 | - spans = {} | 162 | + return {node.name: span for node, span in functions} |
| 150 | - for n in ast.walk(tree): | ||
| 151 | - if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.body: | ||
| 152 | - spans[n.name] = ( | ||
| 153 | - off(n.body[0].lineno, n.body[0].col_offset), | ||
| 154 | - off(n.body[-1].end_lineno, n.body[-1].end_col_offset), | ||
| 155 | - ) | ||
| 156 | - return spans | ||
| 157 | 163 | ||
| 158 | 164 | ||
| 159 | def _enclosing_func(spans, pos): | 165 | def _enclosing_func(spans, pos): |
| @@ -595,20 +601,7 @@ def discover_sites(src): | |||
| 595 | """ | 601 | """ |
| 596 | tree = ast.parse(src) | 602 | tree = ast.parse(src) |
| 597 | off = line_starts(src) | 603 | off = line_starts(src) |
| 598 | - # Byte spans of every loop body. Both kinds count: `for idx in pypto.loop(...)` | 604 | + loops = loop_spans(tree, off) |
| 599 | - # and the plain `for n_off in range(0, N, NC)` a model writes to chunk an axis -- | ||
| 600 | - # the second is a Python loop unrolled at trace time, and a tile inside it still | ||
| 601 | - # governs every chunk. | ||
| 602 | - loops = [] | ||
| 603 | - for n in ast.walk(tree): | ||
| 604 | - if not isinstance(n, (ast.For, ast.AsyncFor, ast.While)) or not n.body: | ||
| 605 | - continue | ||
| 606 | - loops.append( | ||
| 607 | - ( | ||
| 608 | - off(n.body[0].lineno, n.body[0].col_offset), | ||
| 609 | - off(n.body[-1].end_lineno, n.body[-1].end_col_offset), | ||
| 610 | - ) | ||
| 611 | - ) | ||
| 612 | fspans = _func_spans(tree, off) | 605 | fspans = _func_spans(tree, off) |
| 613 | ctx = (off, src, loops, _inherited_depth(tree, off, loops, fspans), fspans) | 606 | ctx = (off, src, loops, _inherited_depth(tree, off, loops, fspans), fspans) |
| 614 | found = _walk_calls(tree, ctx) | 607 | found = _walk_calls(tree, ctx) |
| @@ -622,7 +615,7 @@ def discover_sites(src): | |||
| 622 | ) | 615 | ) |
| 623 | 616 | ||
| 624 | 617 | ||
| 625 | -def tie_groups(sites, anchor): | 618 | +def tie_groups(sites, anchor, fields_of=space.vec_fields, *, match_leading=False): |
| 626 | """Vec sites whose LEADING tile dimension must move together, as id lists. | 619 | """Vec sites whose LEADING tile dimension must move together, as id lists. |
| 627 | 620 | ||
| 628 | The row extent is a hand-off, not a per-site choice. Several vec scopes | 621 | The row extent is a hand-off, not a per-site choice. Several vec scopes |
| @@ -652,9 +645,16 @@ def tie_groups(sites, anchor): | |||
| 652 | # wide scopes and delete the best configuration this kernel has. Unknown | 645 | # wide scopes and delete the best configuration this kernel has. Unknown |
| 653 | # arity means do not tie. | 646 | # arity means do not tie. |
| 654 | a = (anchor or {}).get(s.id) | 647 | a = (anchor or {}).get(s.id) |
| 655 | - if not a or len(space.vec_fields(a)) < 2: | 648 | + fields = fields_of(a) if a else () |
| 649 | + if len(fields) < 2: | ||
| 656 | continue | 650 | continue |
| 657 | - by_span.setdefault(s.loop_span, []).append(s.id) | 651 | + key = s.loop_span |
| 652 | + if match_leading: | ||
| 653 | + extent = a.get(fields[0]) | ||
| 654 | + if not isinstance(extent, int) or isinstance(extent, bool) or extent < 1: | ||
| 655 | + continue | ||
| 656 | + key = (key, extent) | ||
| 657 | + by_span.setdefault(key, []).append(s.id) | ||
| 658 | return [g for g in by_span.values() if len(g) > 1] | 658 | return [g for g in by_span.values() if len(g) > 1] |
| 659 | 659 | ||
| 660 | 660 | ||
| @@ -813,9 +813,14 @@ def apply(src, site_configs): | |||
| 813 | for pos, knobs in kwarg_inserts.items(): | 813 | for pos, knobs in kwarg_inserts.items(): |
| 814 | body = ", ".join(f'"{k}": {{-1: {v}}}' for k, v in sorted(knobs.items())) | 814 | body = ", ".join(f'"{k}": {{-1: {v}}}' for k, v in sorted(knobs.items())) |
| 815 | edits.append((pos, pos, f", pass_options={{{body}}}")) | 815 | edits.append((pos, pos, f", pass_options={{{body}}}")) |
| 816 | - for start, end, text in sorted(edits, reverse=True): | 816 | + return splice_edits(src, sorted(edits, reverse=True)), n_sites |
| 817 | + | ||
| 818 | + | ||
| 819 | +def splice_edits(src, descending_edits): | ||
| 820 | + """Apply replacements from right to left so original offsets stay valid.""" | ||
| 821 | + for start, end, text in descending_edits: | ||
| 817 | src = src[:start] + text + src[end:] | 822 | src = src[:start] + text + src[end:] |
| 818 | - return src, n_sites | 823 | + return src |
| 819 | 824 | ||
| 820 | 825 | ||
| 821 | def _read_site(kind, nums): | 826 | def _read_site(kind, nums): |
| @@ -69,7 +69,7 @@ from . import apply, driver, lever, space | |||
| 69 | from . import domain as domain_mod, seed as seed_mod | 69 | from . import domain as domain_mod, seed as seed_mod |
| 70 | 70 | ||
| 71 | 71 | ||
| 72 | -def _read_text(path, errors="replace"): | 72 | +def read_text(path, errors="replace"): |
| 73 | """The file's text, with the handle closed before the caller sees it.""" | 73 | """The file's text, with the handle closed before the caller sees it.""" |
| 74 | with open(path, encoding="utf-8", errors=errors) as f: | 74 | with open(path, encoding="utf-8", errors=errors) as f: |
| 75 | return f.read() | 75 | return f.read() |
| @@ -104,32 +104,14 @@ def seeds_for(src, hw, ctx=SeedContext()): | |||
| 104 | dom=ctx.dom, | 104 | dom=ctx.dom, |
| 105 | ), | 105 | ), |
| 106 | ) | 106 | ) |
| 107 | - warm = [cfg for cfg, val, _ in pts if val is None] | 107 | + return split_seed_points(pts) |
| 108 | - measured = [(cfg, val) for cfg, val, _ in pts if val is not None] | 108 | + |
| 109 | - # The incumbent is returned SEPARATELY, and this is not tidying. | 109 | + |
| 110 | - # | 110 | +def split_seed_points(points): |
| 111 | - # `run_bo` takes its anchor from `warm_start[0]`, and the anchor is what the | 111 | + warm = [cfg for cfg, value, _ in points if value is None] |
| 112 | - # categorical domains are built around and what the capacity `floor` guard | 112 | + measured = [(cfg, value) for cfg, value, _ in points if value is not None] |
| 113 | - # measures. The incumbent is the only seed that carries a latency -- it is | 113 | + incumbent = next((cfg for cfg, _, label in points if label == "current"), None) |
| 114 | - # already running -- so in production it lands in `measured` and never in | 114 | + return warm, measured, incumbent |
| 115 | - # `warm`, and the anchor silently became the FLOOR seed: the smallest scaling | ||
| 116 | - # of the current shape that clears 16 KB. | ||
| 117 | - # | ||
| 118 | - # Three mechanisms then guard the wrong program. `floor` is ~16 KB instead of | ||
| 119 | - # the incumbent's footprint, so a capacity refusal at 24 KB is accepted as a | ||
| 120 | - # ceiling and everything above it is rejected for free -- including the tile | ||
| 121 | - # the kernel is running. `space.suggest` anchors the ladders on the floor | ||
| 122 | - # seed, so the incumbent's own values need not even be in the domain. And the | ||
| 123 | - # learned L1 relation is checked against the floor seed too. | ||
| 124 | - # | ||
| 125 | - # A recorded block shows the shape of it exactly: 42 trials, 35 rejected for | ||
| 126 | - # free, 7 reaching the device, ONE measurement, best unchanged at the preopt | ||
| 127 | - # -- and `ceiling=24576`, well under a [128,128] fp32 cube tile. The block was | ||
| 128 | - # searching a corner the incumbent is not in and could not have won from | ||
| 129 | - # there. `best_was_incumbent=true, winner_hash=null` in the earlier runs is | ||
| 130 | - # the same failure reported as a result. | ||
| 131 | - cur = next((cfg for cfg, _, lbl in pts if lbl == "current"), None) | ||
| 132 | - return warm, measured, cur | ||
| 133 | 115 | ||
| 134 | 116 | ||
| 135 | def memory_key(action_id, domain): | 117 | def memory_key(action_id, domain): |
| @@ -206,14 +188,13 @@ def ceiling_key(domain): | |||
| 206 | 188 | ||
| 207 | 189 | ||
| 208 | @dataclass | 190 | @dataclass |
| 209 | -class BlockOptions: | 191 | +class BlockBudget: |
| 210 | - """How one block runs, as one value. See driver.SearchOptions -- same | ||
| 211 | - reason, one level up: `run` takes the program, the objective and the | ||
| 212 | - envelope, and this. | ||
| 213 | - """ | ||
| 214 | - | ||
| 215 | stagnation_k: int = 7 # non-improving trials that close the block | 192 | stagnation_k: int = 7 # non-improving trials that close the block |
| 216 | max_trials: Any = None # the remaining evaluation budget | 193 | max_trials: Any = None # the remaining evaluation budget |
| 194 | + | ||
| 195 | + | ||
| 196 | +@dataclass | ||
| 197 | +class BlockSearchOptions: | ||
| 217 | current_latency: Any = None # what the incumbent measured, if known | 198 | current_latency: Any = None # what the incumbent measured, if known |
| 218 | dtype_bytes: int = 4 | 199 | dtype_bytes: int = 4 |
| 219 | on_trial: Any = None | 200 | on_trial: Any = None |
| @@ -227,31 +208,19 @@ class BlockOptions: | |||
| 227 | repair: bool = True # see space.repair | 208 | repair: bool = True # see space.repair |
| 228 | 209 | ||
| 229 | 210 | ||
| 230 | -def _search_options(opts, warm, incumbent, sites): | 211 | +@dataclass |
| 231 | - """The driver's options for one block, translated from BlockOptions.""" | 212 | +class BlockOptions(BlockSearchOptions, BlockBudget): |
| 232 | - return driver.SearchOptions( | 213 | + """Budget and search settings for a PyPTO tile block.""" |
| 233 | - warm_start=warm, | 214 | + |
| 234 | - anchor=incumbent, | 215 | + |
| 216 | +def search_options(options_type, opts, warm, incumbent, ties, **extra): | ||
| 217 | + """Pass the block budget, learned limits and warm observations to the sampler.""" | ||
| 218 | + return options_type( | ||
| 219 | + warm_start=warm, anchor=incumbent, tie=ties, seed=opts.seed, | ||
| 235 | n_trials=opts.max_trials if opts.max_trials is not None else 10**6, | 220 | n_trials=opts.max_trials if opts.max_trials is not None else 10**6, |
| 236 | - seed=opts.seed, | 221 | + on_trial=opts.on_trial, stagnation_limit=opts.stagnation_k, domain=opts.domain, |
| 237 | - on_trial=opts.on_trial, | 222 | + dtype_bytes=opts.dtype_bytes, memory=opts.memory, startup_min_feasible=opts.startup_min_feasible, |
| 238 | - stagnation_limit=opts.stagnation_k, | 223 | + repair=opts.repair, refusals=opts.refusals, ceiling=opts.ceiling, **extra, |
| 239 | - domain=opts.domain, | ||
| 240 | - dtype_bytes=opts.dtype_bytes, | ||
| 241 | - memory=opts.memory, | ||
| 242 | - startup_min_feasible=opts.startup_min_feasible, | ||
| 243 | - repair=opts.repair, | ||
| 244 | - # Run level, not structure level: what the compiler will not accept about | ||
| 245 | - # a tile call outlives the program shape that first asked it. | ||
| 246 | - refusals=opts.refusals, | ||
| 247 | - # Domain level, not structure level: which tiles the compiler accepts is | ||
| 248 | - # a property of the derived domain. See `ceiling_key`. | ||
| 249 | - ceiling=opts.ceiling, | ||
| 250 | - # The row extent of vec scopes inside one loop body is a hand-off, not a | ||
| 251 | - # per-site choice. Left untied, the sampler draws mismatched extents, | ||
| 252 | - # and those are reliably among the worst configurations of a run, | ||
| 253 | - # against an otherwise identical coherent baseline. | ||
| 254 | - tie=apply.tie_groups(sites, incumbent), | ||
| 255 | ) | 224 | ) |
| 256 | 225 | ||
| 257 | 226 | ||
| @@ -283,16 +252,22 @@ def _seeded_warm_starts(src, hw, opts, sites): | |||
| 283 | opts.domain, | 252 | opts.domain, |
| 284 | ), | 253 | ), |
| 285 | ) | 254 | ) |
| 255 | + return complete_warm_starts(warm, measured, incumbent, sites, hw, opts, seed_mod, domain_mod) | ||
| 256 | + | ||
| 257 | + | ||
| 258 | +def complete_warm_starts(warm, measured, incumbent, sites, hw, opts, sampler, domain, **cover_args): | ||
| 259 | + """Extend startup coverage while keeping the measured incumbent.""" | ||
| 286 | if opts.startup_cover: | 260 | if opts.startup_cover: |
| 287 | - warm = warm + seed_mod.cover( | 261 | + warm = warm + sampler.cover( |
| 288 | sites, | 262 | sites, |
| 289 | hw, | 263 | hw, |
| 290 | incumbent, | 264 | incumbent, |
| 291 | opts.startup_cover, | 265 | opts.startup_cover, |
| 292 | - seed_mod.CoverOptions( | 266 | + sampler.CoverOptions( |
| 293 | domain=opts.domain, | 267 | domain=opts.domain, |
| 294 | seed=opts.seed, | 268 | seed=opts.seed, |
| 295 | exclude=warm + ([incumbent] if incumbent else []), | 269 | exclude=warm + ([incumbent] if incumbent else []), |
| 270 | + **cover_args, | ||
| 296 | ), | 271 | ), |
| 297 | ) | 272 | ) |
| 298 | # Seeds are drawn from the current shape by scaling, so one can land outside | 273 | # Seeds are drawn from the current shape by scaling, so one can land outside |
| @@ -302,62 +277,55 @@ def _seeded_warm_starts(src, hw, opts, sites): | |||
| 302 | if opts.domain: | 277 | if opts.domain: |
| 303 | kept = [] | 278 | kept = [] |
| 304 | for c in warm: | 279 | for c in warm: |
| 305 | - if domain_mod.verify(opts.domain, c, opts.dtype_bytes)[0]: | 280 | + if domain.verify(opts.domain, c, opts.dtype_bytes)[0]: |
| 306 | kept.append(c) | 281 | kept.append(c) |
| 307 | warm = kept | 282 | warm = kept |
| 308 | return warm, measured, incumbent | 283 | return warm, measured, incumbent |
| 309 | 284 | ||
| 310 | 285 | ||
| 311 | -def run(op_file, objective, hw, opts=None): | 286 | +def _tile_sites(src, hw, opts): |
| 312 | - """Run one block against the program currently in `op_file`. | 287 | + sites = [s for s in apply.tunable_sites(src) if s.kind in ("cube", "vec")] |
| 288 | + return sites, "no tunable tile site; the tile call is not written with integer literals (normalise at INIT)" | ||
| 313 | 289 | ||
| 314 | - objective : site_configs -> (s, p). In production this is a | ||
| 315 | - `evaluator.RealEvaluator`, which applies each config on top of | ||
| 316 | - a base captured at construction and restores that base | ||
| 317 | - afterwards, so trials never contaminate each other. In tests it | ||
| 318 | - is a plain function. | ||
| 319 | - max_trials: the remaining evaluation budget. None means unbounded, which is | ||
| 320 | - only correct in tests. | ||
| 321 | - startup_cover: how many space-covering points to measure before TPE's own | ||
| 322 | - draws. 0 restores the previous behaviour (scaling seeds only). | ||
| 323 | 290 | ||
| 324 | - Returns the `run_bo` dict, plus `reason` when no trial could be run at all. | 291 | +def run_search(op_file, objective, hw, opts, *, discover, seeds, search, keep_ties=False, confirm=None, prepare=None): |
| 325 | - """ | 292 | + """Run one budgeted block, then compare its winner with already measured seeds.""" |
| 326 | - opts = opts or BlockOptions() | 293 | + src = read_text(op_file) |
| 327 | - src = _read_text(op_file) | ||
| 328 | try: | 294 | try: |
| 329 | - sites = [s for s in apply.tunable_sites(src) if s.kind in ("cube", "vec")] | 295 | + if prepare is not None: |
| 330 | - except SyntaxError as e: | 296 | + src = prepare(src, hw) |
| 331 | - return _empty(f"kernel does not parse: {e}") | 297 | + sites, reason = discover(src, hw, opts) |
| 298 | + except SyntaxError as exc: | ||
| 299 | + return _empty(f"kernel does not parse: {exc}") | ||
| 332 | if not sites: | 300 | if not sites: |
| 333 | - # The single most consequential outcome, so it is named rather than | 301 | + return _empty(reason) |
| 334 | - # returned as an empty result: a kernel whose tile call is written with | ||
| 335 | - # named constants has no tunable site, and normalisation at INIT is what | ||
| 336 | - # fixes it. Silence here is what a whole recorded run looked like. | ||
| 337 | - return _empty( | ||
| 338 | - "no tunable tile site; the tile call is not written with " | ||
| 339 | - "integer literals (normalise at INIT)" | ||
| 340 | - ) | ||
| 341 | if opts.max_trials is not None and opts.max_trials <= 0: | 302 | if opts.max_trials is not None and opts.max_trials <= 0: |
| 342 | return _empty("no evaluation budget remaining") | 303 | return _empty("no evaluation budget remaining") |
| 343 | 304 | ||
| 344 | - warm, measured, incumbent = _seeded_warm_starts(src, hw, opts, sites) | 305 | + warm, measured, incumbent = seeds(src, hw, opts, sites) |
| 345 | - result = driver.run_bo( | 306 | + result = search(objective, sites, hw, opts, warm, measured, incumbent) |
| 346 | - objective, | 307 | + for cfg, value in measured: |
| 347 | - sites, | 308 | + best = result["best_objective_us"] |
| 348 | - hw, | 309 | + # Pro enqueues the incumbent as a study observation. Keep it on a tie. |
| 349 | - _search_options(opts, warm, incumbent, sites), | 310 | + if best is None or (value <= best if keep_ties else value < best): |
| 350 | - ) | 311 | + result["best_config"], result["best_objective_us"] = cfg, float(value) |
| 351 | - # An already-measured configuration is evidence and costs nothing, so it | ||
| 352 | - # competes with what the block found rather than being discarded. | ||
| 353 | - for cfg, val in measured: | ||
| 354 | - if result["best_objective_us"] is None or val < result["best_objective_us"]: | ||
| 355 | - result["best_config"], result["best_objective_us"] = cfg, float(val) | ||
| 356 | result["best_was_incumbent"] = True | 312 | result["best_was_incumbent"] = True |
| 357 | result.setdefault("best_was_incumbent", False) | 313 | result.setdefault("best_was_incumbent", False) |
| 314 | + if confirm is not None and result.get("best_config") and not result["best_was_incumbent"]: | ||
| 315 | + result["confirm"] = confirm(objective, incumbent, result["best_config"], opts.seed or 0) | ||
| 358 | return result | 316 | return result |
| 359 | 317 | ||
| 360 | 318 | ||
| 319 | +def _search(objective, sites, hw, opts, warm, measured, incumbent): | ||
| 320 | + options = search_options(driver.SearchOptions, opts, warm, incumbent, apply.tie_groups(sites, incumbent)) | ||
| 321 | + return driver.run_bo(objective, sites, hw, options) | ||
| 322 | + | ||
| 323 | + | ||
| 324 | +def run(op_file, objective, hw, opts=None): | ||
| 325 | + return run_search(op_file, objective, hw, opts or BlockOptions(), | ||
| 326 | + discover=_tile_sites, seeds=_seeded_warm_starts, search=_search) | ||
| 327 | + | ||
| 328 | + | ||
| 361 | def apply_best(src, best_config): | 329 | def apply_best(src, best_config): |
| 362 | """(new_src, n_sites_rewritten) for the winning configuration. | 330 | """(new_src, n_sites_rewritten) for the winning configuration. |
| 363 | 331 | ||
| @@ -418,7 +386,7 @@ def _merge_bounds(op_file): | |||
| 418 | # space.HW's field name for each chip-envelope key. The two differ because the | 386 | # space.HW's field name for each chip-envelope key. The two differ because the |
| 419 | # envelope is named after the chip's own datasheet and HW after what the static | 387 | # envelope is named after the chip's own datasheet and HW after what the static |
| 420 | # check calls the same quantity. | 388 | # check calls the same quantity. |
| 421 | -_HW_FROM_ENVELOPE = ( | 389 | +HW_FROM_ENVELOPE = ( |
| 422 | ("ub_budget_kb", "ub_kb"), | 390 | ("ub_budget_kb", "ub_kb"), |
| 423 | ("l1_budget_kb", "l1_kb"), | 391 | ("l1_budget_kb", "l1_kb"), |
| 424 | ("l0a_kb", "l0a_kb"), | 392 | ("l0a_kb", "l0a_kb"), |
| @@ -446,14 +414,14 @@ def hw_for(op_file, live_tiles=None, envelope=None): | |||
| 446 | the tile search and the static feasibility gate validate against the SAME | 414 | the tile search and the static feasibility gate validate against the SAME |
| 447 | numbers. They did not: this function passed none, so the search used the | 415 | numbers. They did not: this function passed none, so the search used the |
| 448 | dataclass defaults while `--ub-kb` / `--l1-kb` moved only the other gate. | 416 | dataclass defaults while `--ub-kb` / `--l1-kb` moved only the other gate. |
| 449 | - None keeps the defaults, for a caller that has no envelope to hand. | 417 | + Without a supplied UB capacity, both the hardware and domain report it as unknown. |
| 450 | """ | 418 | """ |
| 451 | env = envelope or {} | 419 | env = envelope or {} |
| 452 | - domain = domain_mod.derive(op_file, live_tiles, ub_budget_kb=env.get("ub_kb", 192)) | 420 | + domain = domain_mod.derive(op_file, live_tiles, ub_budget_kb=env.get("ub_kb")) |
| 453 | bounds = _merge_bounds(op_file) | 421 | bounds = _merge_bounds(op_file) |
| 454 | if bounds: | 422 | if bounds: |
| 455 | domain["subgraph_counts"] = bounds | 423 | domain["subgraph_counts"] = bounds |
| 456 | - kw = {field: env[key] for field, key in _HW_FROM_ENVELOPE if key in env} | 424 | + kw = {field: env[key] for field, key in HW_FROM_ENVELOPE if key in env} |
| 457 | hw = space.HW( | 425 | hw = space.HW( |
| 458 | calibrated=False, | 426 | calibrated=False, |
| 459 | dtype_bytes=domain.get("dtype_bytes", 4), | 427 | dtype_bytes=domain.get("dtype_bytes", 4), |
| @@ -34,25 +34,14 @@ admitting more; the incumbent-value check and the golden are what bound the cost | |||
| 34 | 34 | ||
| 35 | import ast | 35 | import ast |
| 36 | 36 | ||
| 37 | +if __package__ == "bayesian_optimization": | ||
| 38 | + import pypto_ast | ||
| 39 | +else: | ||
| 40 | + from .. import pypto_ast | ||
| 41 | + | ||
| 37 | _LOOP = "loop" | 42 | _LOOP = "loop" |
| 38 | 43 | ||
| 39 | 44 | ||
| 40 | -def _fname(func): | ||
| 41 | - if isinstance(func, ast.Attribute): | ||
| 42 | - return func.attr | ||
| 43 | - if isinstance(func, ast.Name): | ||
| 44 | - return func.id | ||
| 45 | - return "" | ||
| 46 | - | ||
| 47 | - | ||
| 48 | -def _is_jit(fn): | ||
| 49 | - for d in getattr(fn, "decorator_list", []): | ||
| 50 | - node = d.func if isinstance(d, ast.Call) else d | ||
| 51 | - if _fname(node) == "jit": | ||
| 52 | - return True | ||
| 53 | - return False | ||
| 54 | - | ||
| 55 | - | ||
| 56 | def _int_lit(n): | 45 | def _int_lit(n): |
| 57 | return ( | 46 | return ( |
| 58 | isinstance(n, ast.Constant) | 47 | isinstance(n, ast.Constant) |
| @@ -113,14 +102,6 @@ def bindings(tree, starts): | |||
| 113 | return out | 102 | return out |
| 114 | 103 | ||
| 115 | 104 | ||
| 116 | -def _parents(tree): | ||
| 117 | - out = {} | ||
| 118 | - for node in ast.walk(tree): | ||
| 119 | - for child in ast.iter_child_nodes(node): | ||
| 120 | - out[child] = node | ||
| 121 | - return out | ||
| 122 | - | ||
| 123 | - | ||
| 124 | def _contexts(node, parents, jit_nodes): | 105 | def _contexts(node, parents, jit_nodes): |
| 125 | """The contexts a Name read sits inside.""" | 106 | """The contexts a Name read sits inside.""" |
| 126 | flags, cur = set(), node | 107 | flags, cur = set(), node |
| @@ -131,7 +112,7 @@ def _contexts(node, parents, jit_nodes): | |||
| 131 | if isinstance(cur, (ast.arg, ast.AnnAssign)): | 112 | if isinstance(cur, (ast.arg, ast.AnnAssign)): |
| 132 | flags.add("annot") | 113 | flags.add("annot") |
| 133 | if isinstance(cur, ast.Call): | 114 | if isinstance(cur, ast.Call): |
| 134 | - n = _fname(cur.func) | 115 | + n = pypto_ast.function_name(cur.func) |
| 135 | if n == _LOOP: | 116 | if n == _LOOP: |
| 136 | flags.add("loop") | 117 | flags.add("loop") |
| 137 | elif ( | 118 | elif ( |
| @@ -184,10 +165,10 @@ def analyse(src): | |||
| 184 | binds = bindings(tree, starts) | 165 | binds = bindings(tree, starts) |
| 185 | if not binds: | 166 | if not binds: |
| 186 | return {} | 167 | return {} |
| 187 | - parents = _parents(tree) | 168 | + parents = pypto_ast.parent_map(tree) |
| 188 | jit_nodes = set() | 169 | jit_nodes = set() |
| 189 | for fn in ast.walk(tree): | 170 | for fn in ast.walk(tree): |
| 190 | - if isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)) and _is_jit(fn): | 171 | + if isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)) and any(pypto_ast.jit_decorators(fn)): |
| 191 | jit_nodes.update(ast.walk(fn)) | 172 | jit_nodes.update(ast.walk(fn)) |
| 192 | reads = [ | 173 | reads = [ |
| 193 | n | 174 | n |
| @@ -62,7 +62,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |||
| 62 | 62 | ||
| 63 | # One home, shared with `predicates`: see pypto_ast. Not optional -- every tile | 63 | # One home, shared with `predicates`: see pypto_ast. Not optional -- every tile |
| 64 | # this module counts depends on knowing which calls are pypto's. | 64 | # this module counts depends on knowing which calls are pypto's. |
| 65 | -from pypto_ast import pypto_roots # noqa: E402 | 65 | +from pypto_ast import keyword_value as _kwarg, pypto_roots # noqa: E402 |
| 66 | 66 | ||
| 67 | try: | 67 | try: |
| 68 | import feasibility # noqa: E402 | 68 | import feasibility # noqa: E402 |
| @@ -1154,13 +1154,6 @@ def _covers(have, need): | |||
| 1154 | return True | 1154 | return True |
| 1155 | 1155 | ||
| 1156 | 1156 | ||
| 1157 | -def _kwarg(call, name): | ||
| 1158 | - for k in call.keywords: | ||
| 1159 | - if k.arg == name: | ||
| 1160 | - return k.value | ||
| 1161 | - return None | ||
| 1162 | - | ||
| 1163 | - | ||
| 1164 | def _rhs_attr(rhs): | 1157 | def _rhs_attr(rhs): |
| 1165 | """The method name a statement's right-hand side calls, or None.""" | 1158 | """The method name a statement's right-hand side calls, or None.""" |
| 1166 | if isinstance(rhs, ast.Call) and isinstance(rhs.func, ast.Attribute): | 1159 | if isinstance(rhs, ast.Call) and isinstance(rhs.func, ast.Attribute): |
| @@ -31,7 +31,6 @@ leaves them None: run_cmd = subprocess, measure_fn = the frozen scripts/measure_ | |||
| 31 | pass fakes so the whole (s, p) contract, correctness gating, and base-restore run without an NPU. | 31 | pass fakes so the whole (s, p) contract, correctness gating, and base-restore run without an NPU. |
| 32 | """ | 32 | """ |
| 33 | 33 | ||
| 34 | -import json | ||
| 35 | import os | 34 | import os |
| 36 | import re | 35 | import re |
| 37 | import shlex | 36 | import shlex |
| @@ -40,9 +39,15 @@ import signal | |||
| 40 | import subprocess | 39 | import subprocess |
| 41 | import sys | 40 | import sys |
| 42 | import time | 41 | import time |
| 42 | +from pathlib import Path | ||
| 43 | 43 | ||
| 44 | from . import apply | 44 | from . import apply |
| 45 | 45 | ||
| 46 | +if __package__ == "bayesian_optimization": | ||
| 47 | + from jsonio import last_object | ||
| 48 | +else: | ||
| 49 | + from ..jsonio import last_object | ||
| 50 | + | ||
| 46 | 51 | ||
| 47 | FIRST_CALL_MARKER = "[panko-progress] first_call_done" | 52 | FIRST_CALL_MARKER = "[panko-progress] first_call_done" |
| 48 | 53 | ||
| @@ -190,15 +195,16 @@ def _run_one(step, cwd, timeout, env=None): | |||
| 190 | return (r.stdout or ""), r.returncode | 195 | return (r.stdout or ""), r.returncode |
| 191 | 196 | ||
| 192 | 197 | ||
| 193 | -def run_command(cmd, timeout, env=None): | 198 | +def run_command(cmd, timeout, env=None, *, run_step=None): |
| 194 | """Run a correctness command without a shell. Returns (combined output, exit code). | 199 | """Run a correctness command without a shell. Returns (combined output, exit code). |
| 195 | 200 | ||
| 196 | `&&` semantics: the steps run in order and stop at the first failure. | 201 | `&&` semantics: the steps run in order and stop at the first failure. |
| 197 | """ | 202 | """ |
| 198 | steps, cwd = command_steps(cmd) | 203 | steps, cwd = command_steps(cmd) |
| 204 | + run_step = run_step or _run_one | ||
| 199 | text, code = "", 0 | 205 | text, code = "", 0 |
| 200 | for step in steps: | 206 | for step in steps: |
| 201 | - out, code = _run_one(step, cwd, timeout, env) | 207 | + out, code = run_step(step, cwd, timeout, env) |
| 202 | text += out | 208 | text += out |
| 203 | if code: | 209 | if code: |
| 204 | break | 210 | break |
| @@ -467,7 +473,8 @@ class RealEvaluator: | |||
| 467 | lint_root=None, lint_stage=7, | 473 | lint_root=None, lint_stage=7, |
| 468 | warmup=1, runs=9, agg="median", eval_timeout_s=300, | 474 | warmup=1, runs=9, agg="median", eval_timeout_s=300, |
| 469 | run_cmd=None, measure_fn=None, | 475 | run_cmd=None, measure_fn=None, |
| 470 | - fault_backoff_s=(30, 90), sleep_fn=None, evaluation_mode="subprocess"): | 476 | + fault_backoff_s=(30, 90), sleep_fn=None, evaluation_mode="subprocess", |
| 477 | + write_source=None): | ||
| 471 | """test_command : shell string that exits 0 iff golden+layout pass (from the dispatch prompt). | 478 | """test_command : shell string that exits 0 iff golden+layout pass (from the dispatch prompt). |
| 472 | lint_root : path to the pypto-op-lint hook directory under | 479 | lint_root : path to the pypto-op-lint hook directory under |
| 473 | cannbot-skills/plugins-official/pypto-op-orchestrator/hooks | 480 | cannbot-skills/plugins-official/pypto-op-orchestrator/hooks |
| @@ -481,6 +488,7 @@ class RealEvaluator: | |||
| 481 | waits bound a trial at about two extra minutes, which | 488 | waits bound a trial at about two extra minutes, which |
| 482 | is cheaper than one lost run by a wide margin. | 489 | is cheaper than one lost run by a wide margin. |
| 483 | sleep_fn : injected in tests so the schedule is asserted, not waited on. | 490 | sleep_fn : injected in tests so the schedule is asserted, not waited on. |
| 491 | + write_source : frontend staging hook. Its on-disk bytes identify the trial. | ||
| 484 | """ | 492 | """ |
| 485 | self.op = op | 493 | self.op = op |
| 486 | self.op_dir = op_dir | 494 | self.op_dir = op_dir |
| @@ -522,7 +530,9 @@ class RealEvaluator: | |||
| 522 | raise ValueError("injected runners require subprocess mode") | 530 | raise ValueError("injected runners require subprocess mode") |
| 523 | self.evaluation_mode = evaluation_mode | 531 | self.evaluation_mode = evaluation_mode |
| 524 | self._session_result = {} | 532 | self._session_result = {} |
| 525 | - with open(op_file, "r", encoding="utf-8") as f: | 533 | + self.write_source = write_source |
| 534 | + self.last_trial_bytes = None | ||
| 535 | + with open(op_file, "r", encoding="utf-8", newline="" if write_source else None) as f: | ||
| 526 | self.base_src = f.read() | 536 | self.base_src = f.read() |
| 527 | # Discover the per-site tunable tile calls once; pass self.sites to driver.run_bo. | 537 | # Discover the per-site tunable tile calls once; pass self.sites to driver.run_bo. |
| 528 | try: | 538 | try: |
| @@ -541,11 +551,12 @@ class RealEvaluator: | |||
| 541 | # under whatever `last_detail` still held attributed one trial's compiler | 551 | # under whatever `last_detail` still held attributed one trial's compiler |
| 542 | # error to another trial's parameters. | 552 | # error to another trial's parameters. |
| 543 | self.last_detail = "" | 553 | self.last_detail = "" |
| 554 | + self.last_trial_bytes = None | ||
| 544 | new_src, n = apply.apply(self.base_src, site_configs) | 555 | new_src, n = apply.apply(self.base_src, site_configs) |
| 545 | if n == 0: | 556 | if n == 0: |
| 546 | return 0, None # nothing to apply -> guard (misconfigured site ids) | 557 | return 0, None # nothing to apply -> guard (misconfigured site ids) |
| 547 | - self._write(new_src) | ||
| 548 | try: | 558 | try: |
| 559 | + self.last_trial_bytes = self._write(new_src) | ||
| 549 | # `_run_test` distinguishes "this candidate is wrong" from "the device | 560 | # `_run_test` distinguishes "this candidate is wrong" from "the device |
| 550 | # could not be used", and waits out the second. Only the first is a | 561 | # could not be used", and waits out the second. Only the first is a |
| 551 | # verdict; the second must not be charged, counted, or learned from. | 562 | # verdict; the second must not be charged, counted, or learned from. |
| @@ -795,8 +806,12 @@ class RealEvaluator: | |||
| 795 | ) | 806 | ) |
| 796 | 807 | ||
| 797 | def _write(self, src): | 808 | def _write(self, src): |
| 809 | + if self.write_source is not None: | ||
| 810 | + self.write_source(self.op_file, src) | ||
| 811 | + return Path(self.op_file).read_bytes() | ||
| 798 | with open(self.op_file, "w", encoding="utf-8") as f: | 812 | with open(self.op_file, "w", encoding="utf-8") as f: |
| 799 | f.write(src) | 813 | f.write(src) |
| 814 | + return None | ||
| 800 | 815 | ||
| 801 | def _lint_ok(self): | 816 | def _lint_ok(self): |
| 802 | if self.evaluation_mode != "subprocess": | 817 | if self.evaluation_mode != "subprocess": |
| @@ -873,13 +888,9 @@ class RealEvaluator: | |||
| 873 | # Kept so `_env_fault` can see a device fault raised during measurement, | 888 | # Kept so `_env_fault` can see a device fault raised during measurement, |
| 874 | # not only during the correctness command. | 889 | # not only during the correctness command. |
| 875 | self._last_output = out | 890 | self._last_output = out |
| 876 | - for line in reversed(out.strip().splitlines()): | 891 | + result = last_object(out) |
| 877 | - line = line.strip() | 892 | + if result is not None: |
| 878 | - if line.startswith("{"): | 893 | + return result |
| 879 | - try: | ||
| 880 | - return json.loads(line) | ||
| 881 | - except ValueError: | ||
| 882 | - continue | ||
| 883 | if timed_out: | 894 | if timed_out: |
| 884 | return classify_timeout(out) | 895 | return classify_timeout(out) |
| 885 | return {} | 896 | return {} |
| @@ -35,7 +35,6 @@ own cycle, not here. | |||
| 35 | import ast | 35 | import ast |
| 36 | import hashlib | 36 | import hashlib |
| 37 | import math | 37 | import math |
| 38 | -import re | ||
| 39 | 38 | ||
| 40 | from dataclasses import dataclass | 39 | from dataclasses import dataclass |
| 41 | from typing import Any, NamedTuple | 40 | from typing import Any, NamedTuple |
| @@ -86,39 +86,28 @@ def _cube_features(c, hw): | |||
| 86 | 86 | ||
| 87 | 87 | ||
| 88 | def _vec_features(v, hw, domain, site_id): | 88 | def _vec_features(v, hw, domain, site_id): |
| 89 | - """UB occupancy of one vector tile, and the trip count it implies.""" | 89 | + return vector_features(v, hw, domain, site_id, fields=space.vec_fields(v), |
| 90 | - dims = [v[f] for f in space.vec_fields(v)] | 90 | + cores=getattr(hw, "vector_cores", VECTOR_CORES)) |
| 91 | - n = 1 | ||
| 92 | - for d in dims: | ||
| 93 | - n *= max(1, d) | ||
| 94 | - res = ((domain or {}).get("vec_residency") or {}).get(site_id) or 1 | ||
| 95 | - ub = (domain or {}).get("ub_bytes") or (192 * 1024) | ||
| 96 | - cap = (domain or {}).get("capacity_elems") | ||
| 97 | - f = {"ub": min(1.0, n * hw.dtype_bytes * res / ub)} | ||
| 98 | - if cap: | ||
| 99 | - trips = cap / max(1, n) | ||
| 100 | - f["trips"] = trips | ||
| 101 | - # Below one trip per core, some cores are handed nothing. Division, not | ||
| 102 | - # a model: it is true whatever the kernel does with the work it gets. | ||
| 103 | - f["waves"] = trips / getattr(hw, "vector_cores", VECTOR_CORES) | ||
| 104 | - return f | ||
| 105 | 91 | ||
| 106 | 92 | ||
| 107 | def features(cfg, hw, domain=None): | 93 | def features(cfg, hw, domain=None): |
| 108 | """Flat feature vector for a per-site config. Keys are stable, values finite.""" | 94 | """Flat feature vector for a per-site config. Keys are stable, values finite.""" |
| 95 | + return site_features(cfg, hw, domain, space.vec_fields, _vec_features, _cube_features) | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +def site_features(cfg, hw, domain, fields, vector, cube=None): | ||
| 99 | + """Describe tile sites only; scalar launch and scheduling knobs have no occupancy.""" | ||
| 109 | out = {} | 100 | out = {} |
| 110 | - for sid, v in sorted(cfg.items()): | 101 | + for sid, config in sorted(cfg.items()): |
| 111 | - if not isinstance(v, dict) or "value" in v: | 102 | + if not isinstance(config, dict) or "value" in config: |
| 112 | - # A global / unroll / pass site holds a scalar under "value", not a | ||
| 113 | - # tile. `vec_fields` will happily invent dimension names for it, and | ||
| 114 | - # reading them raises. There is no buffer occupancy to compute for a | ||
| 115 | - # scheduling mode or a merge granularity. | ||
| 116 | continue | 103 | continue |
| 117 | - if "mL0" in v: | 104 | + if cube is not None and "mL0" in config: |
| 118 | - out.update({f"{sid}.{k}": x for k, x in _cube_features(v, hw).items()}) | 105 | + values = cube(config, hw) |
| 119 | - elif space.vec_fields(v): | 106 | + elif fields(config): |
| 120 | - vec = _vec_features(v, hw, domain, sid) | 107 | + values = vector(config, hw, domain, sid) |
| 121 | - out.update({f"{sid}.{k}": x for k, x in vec.items()}) | 108 | + else: |
| 109 | + continue | ||
| 110 | + out.update({f"{sid}.{key}": value for key, value in values.items()}) | ||
| 122 | return out | 111 | return out |
| 123 | 112 | ||
| 124 | 113 | ||
| @@ -238,12 +227,13 @@ def _rand_cube(a, rng): | |||
| 238 | 227 | ||
| 239 | def _rand_vec(site_id, a, domain, rng): | 228 | def _rand_vec(site_id, a, domain, rng): |
| 240 | """A vec draw, or {} when the incumbent names no fields to draw.""" | 229 | """A vec draw, or {} when the incumbent names no fields to draw.""" |
| 241 | - fields = space.vec_fields(a) | 230 | + return draw_vector(site_id, a, domain, rng, space) |
| 242 | - if not fields: | 231 | + |
| 243 | - return {} | 232 | + |
| 244 | - return { | 233 | +def draw_vector(site_id, anchor, domain, rng, tile_space): |
| 245 | - f: rng.choice(space.vec_domain(site_id, f, fields, a, domain)) for f in fields | 234 | + fields = tile_space.vec_fields(anchor) |
| 246 | - } | 235 | + return {f: rng.choice(tile_space.vec_domain(site_id, f, fields, anchor, domain)) |
| 236 | + for f in fields} | ||
| 247 | 237 | ||
| 248 | 238 | ||
| 249 | def _sample_space(sites, anchor, domain, n, rng): | 239 | def _sample_space(sites, anchor, domain, n, rng): |
| @@ -252,16 +242,20 @@ def _sample_space(sites, anchor, domain, n, rng): | |||
| 252 | Sampling then filtering is deliberate: the domains are what the sampler will | 242 | Sampling then filtering is deliberate: the domains are what the sampler will |
| 253 | actually see, so a point selected here is one TPE could also have proposed. | 243 | actually see, so a point selected here is one TPE could also have proposed. |
| 254 | """ | 244 | """ |
| 245 | + def draw(site, a): | ||
| 246 | + if site.kind == "cube": | ||
| 247 | + return _rand_cube(a, rng) | ||
| 248 | + return _rand_vec(site.id, a, domain, rng) | ||
| 249 | + | ||
| 250 | + return draw_pool(sites, anchor, n, draw) | ||
| 251 | + | ||
| 252 | + | ||
| 253 | +def draw_pool(sites, anchor, n, draw): | ||
| 255 | out = [] | 254 | out = [] |
| 256 | for _ in range(n): | 255 | for _ in range(n): |
| 257 | cfg = {} | 256 | cfg = {} |
| 258 | for s in sites: | 257 | for s in sites: |
| 259 | - a = (anchor or {}).get(s.id, {}) | 258 | + drawn = draw(s, (anchor or {}).get(s.id, {})) |
| 260 | - drawn = ( | ||
| 261 | - _rand_cube(a, rng) | ||
| 262 | - if s.kind == "cube" | ||
| 263 | - else _rand_vec(s.id, a, domain, rng) | ||
| 264 | - ) | ||
| 265 | if drawn: | 259 | if drawn: |
| 266 | cfg[s.id] = drawn | 260 | cfg[s.id] = drawn |
| 267 | if cfg: | 261 | if cfg: |
| @@ -295,26 +289,38 @@ def n_dims(sites, anchor=None): | |||
| 295 | The arity comes from `anchor`, which is the configuration currently in the | 289 | The arity comes from `anchor`, which is the configuration currently in the |
| 296 | file. Without it, fall back to two. | 290 | file. Without it, fall back to two. |
| 297 | """ | 291 | """ |
| 298 | - n = 0 | 292 | + return count_dimensions(sites, anchor, {"cube": 6, "global": 1, "unroll": 1}, space.vec_fields) |
| 299 | - for s in sites: | 293 | + |
| 300 | - if s.kind == "cube": | 294 | + |
| 301 | - n += 6 | 295 | +def count_dimensions(sites, anchor, scalar_widths, vector_fields): |
| 302 | - elif s.kind in ("global", "unroll"): | 296 | + total = 0 |
| 303 | - n += 1 | 297 | + for site in sites: |
| 304 | - else: | 298 | + width = scalar_widths.get(site.kind) |
| 305 | - fields = space.vec_fields((anchor or {}).get(s.id, {})) | 299 | + if width is None: |
| 306 | - n += len(fields) or 2 | 300 | + width = len(vector_fields((anchor or {}).get(site.id, {}))) or 2 |
| 307 | - return n | 301 | + total += width |
| 302 | + return total | ||
| 303 | + | ||
| 308 | 304 | ||
| 309 | 305 | ||
| 310 | @dataclass | 306 | @dataclass |
| 311 | -class CoverOptions: | 307 | +class CoverSampling: |
| 312 | - """How `cover` draws its candidates: where from, and what to leave out.""" | 308 | + """Sampling controls shared by both domain frontends.""" |
| 313 | 309 | ||
| 314 | - domain: Any = None | ||
| 315 | seed: int = 0 | 310 | seed: int = 0 |
| 316 | - pool: int = 400 # candidates sampled before the k are picked | 311 | + pool: int = 400 |
| 317 | - exclude: Any = () # configs already queued, not to repeat | 312 | + exclude: Any = () |
| 313 | + | ||
| 314 | + | ||
| 315 | +def feasible_rows(rows, seen, admitted): | ||
| 316 | + kept = [] | ||
| 317 | + for cfg in rows: | ||
| 318 | + identity = _key(cfg) | ||
| 319 | + if identity in seen or not admitted(cfg): | ||
| 320 | + continue | ||
| 321 | + seen.add(identity) | ||
| 322 | + kept.append(cfg) | ||
| 323 | + return kept | ||
| 318 | 324 | ||
| 319 | 325 | ||
| 320 | def cover(sites, hw, anchor, k, opts=None): | 326 | def cover(sites, hw, anchor, k, opts=None): |
| @@ -340,34 +346,16 @@ def cover(sites, hw, anchor, k, opts=None): | |||
| 340 | costs one device trial per block. | 346 | costs one device trial per block. |
| 341 | """ | 347 | """ |
| 342 | opts = opts or CoverOptions() | 348 | opts = opts or CoverOptions() |
| 343 | - if k <= 0 or not sites or n_dims(sites, anchor) < MIN_DIMS: | 349 | + setup = cover_setup(sites, anchor, k, opts, n_dims, MIN_DIMS) |
| 350 | + if setup is None: | ||
| 344 | return [] | 351 | return [] |
| 345 | - rng = random.Random(opts.seed) | 352 | + rng, seen = setup |
| 346 | - seen = {_key(c) for c in opts.exclude} | ||
| 347 | - if anchor: | ||
| 348 | - seen.add(_key(anchor)) | ||
| 349 | 353 | ||
| 350 | def _keep(rows): | 354 | def _keep(rows): |
| 351 | - out = [] | 355 | + def admitted(cfg): |
| 352 | - for cfg in rows: | 356 | + return (space.static_feasible(cfg, hw)[0] |
| 353 | - key = _key(cfg) | 357 | + and (not opts.domain or verify_domain(opts.domain, cfg)[0])) |
| 354 | - if key in seen or not space.static_feasible(cfg, hw)[0]: | 358 | + return feasible_rows(rows, seen, admitted) |
| 355 | - continue | ||
| 356 | - # The derived domain too, not alignment alone. `block.run` filters | ||
| 357 | - # the merged warm list through `domain.verify` before handing it to | ||
| 358 | - # the driver, so a covering point that fails it is simply deleted -- | ||
| 359 | - # and farthest-point selection walks to the EXTREMES of the pool, | ||
| 360 | - # which is exactly where verify rejects. Only a fraction of a pool | ||
| 361 | - # that clears alignment also clears verify, and the extreme points | ||
| 362 | - # `cover` prefers are the likeliest to fail it -- so the set that | ||
| 363 | - # survives is the small-tile end, losing the high-occupancy corner | ||
| 364 | - # this function exists to keep. Gating here means the k picked are | ||
| 365 | - # k kept. | ||
| 366 | - if opts.domain and not verify_domain(opts.domain, cfg)[0]: | ||
| 367 | - continue | ||
| 368 | - seen.add(key) | ||
| 369 | - out.append(cfg) | ||
| 370 | - return out | ||
| 371 | 359 | ||
| 372 | # ONE slot reserved for the L1-only family, because farthest-point cannot | 360 | # ONE slot reserved for the L1-only family, because farthest-point cannot |
| 373 | # reach it: those points hold the incumbent's L0, so their L0A / L0B / L0C | 361 | # reach it: those points hold the incumbent's L0, so their L0A / L0B / L0C |
| @@ -399,12 +387,32 @@ def cover(sites, hw, anchor, k, opts=None): | |||
| 399 | # fires six to nine blocks. | 387 | # fires six to nine blocks. |
| 400 | reserved = [random.Random(opts.seed ^ 0x5EED).choice(l1_cands)] if l1_cands else [] | 388 | reserved = [random.Random(opts.seed ^ 0x5EED).choice(l1_cands)] if l1_cands else [] |
| 401 | 389 | ||
| 402 | - cands = _keep(_sample_space(sites, anchor, opts.domain, opts.pool, rng)) | 390 | + candidates = _keep(_sample_space(sites, anchor, opts.domain, opts.pool, rng)) |
| 403 | - if not cands: | 391 | + return reserved + select_cover(candidates, anchor, k, hw, opts.domain, features) |
| 404 | - return reserved | ||
| 405 | 392 | ||
| 406 | - base = [features(anchor, hw, opts.domain)] if anchor else [] | 393 | + |
| 407 | - vecs = _normalise(base + [features(c, hw, opts.domain) for c in cands]) | 394 | +def select_cover(candidates, anchor, k, hw, domain, describe): |
| 395 | + """Choose diverse feasible candidates, measuring distance from the incumbent first.""" | ||
| 396 | + if not candidates: | ||
| 397 | + return [] | ||
| 398 | + base = [describe(anchor, hw, domain)] if anchor else [] | ||
| 399 | + vectors = [describe(cfg, hw, domain) for cfg in candidates] | ||
| 400 | + return farthest_points(candidates, base, vectors, k) | ||
| 401 | + | ||
| 402 | + | ||
| 403 | +def _key(cfg): | ||
| 404 | + return tuple( | ||
| 405 | + sorted( | ||
| 406 | + (sid, tuple(sorted(v.items()))) | ||
| 407 | + for sid, v in cfg.items() | ||
| 408 | + if isinstance(v, dict) | ||
| 409 | + ) | ||
| 410 | + ) | ||
| 411 | + | ||
| 412 | + | ||
| 413 | +def farthest_points(cands, base, vectors, k): | ||
| 414 | + """Cover normalized feature space while excluding already represented regimes.""" | ||
| 415 | + vecs = _normalise(base + vectors) | ||
| 408 | chosen_vecs = vecs[: len(base)] | 416 | chosen_vecs = vecs[: len(base)] |
| 409 | pool_vecs = vecs[slice(len(base), None)] | 417 | pool_vecs = vecs[slice(len(base), None)] |
| 410 | 418 | ||
| @@ -429,16 +437,51 @@ def cover(sites, hw, anchor, k, opts=None): | |||
| 429 | for j in avail | 437 | for j in avail |
| 430 | if min(_dist2(pool_vecs[j], c) for c in chosen_vecs) > _MIN_SEP2 | 438 | if min(_dist2(pool_vecs[j], c) for c in chosen_vecs) > _MIN_SEP2 |
| 431 | ] | 439 | ] |
| 432 | - # Reserved point first: if the block's budget is cut short, the one that no | 440 | + return picked |
| 433 | - # other mechanism can produce should not be the one dropped. | ||
| 434 | - return reserved + picked | ||
| 435 | 441 | ||
| 436 | 442 | ||
| 437 | -def _key(cfg): | 443 | +@dataclass |
| 438 | - return tuple( | 444 | +class CoverDomain: |
| 439 | - sorted( | 445 | + domain: Any = None |
| 440 | - (sid, tuple(sorted(v.items()))) | 446 | + |
| 441 | - for sid, v in cfg.items() | 447 | + |
| 442 | - if isinstance(v, dict) | 448 | +@dataclass |
| 443 | - ) | 449 | +class CoverOptions(CoverSampling, CoverDomain): |
| 444 | - ) | 450 | + """Classic cover options, retaining their positional order.""" |
| 451 | + | ||
| 452 | + | ||
| 453 | +def vector_features(v, hw, domain, site_id, *, fields, cores): | ||
| 454 | + """Return tile coverage features, omitting UB occupancy if capacity is unknown.""" | ||
| 455 | + dims = [v[f] for f in fields] | ||
| 456 | + n = 1 | ||
| 457 | + for d in dims: | ||
| 458 | + n *= max(1, d) | ||
| 459 | + res = ((domain or {}).get("vec_residency") or {}).get(site_id) or 1 | ||
| 460 | + ub = (domain or {}).get("ub_bytes") or 0 | ||
| 461 | + if ub <= 0: | ||
| 462 | + ub = (getattr(hw, "ub_budget_kb", 0) or 0) * 1024 | ||
| 463 | + cap = (domain or {}).get("capacity_elems") | ||
| 464 | + f = {"ub": min(1.0, n * hw.dtype_bytes * res / ub)} if ub > 0 else {} | ||
| 465 | + if cap: | ||
| 466 | + trips = cap / max(1, n) | ||
| 467 | + f["trips"] = trips | ||
| 468 | + # Below one trip per core, some cores are handed nothing. Division, not | ||
| 469 | + # a model: it is true whatever the kernel does with the work it gets. | ||
| 470 | + f["waves"] = trips / cores | ||
| 471 | + return f | ||
| 472 | + | ||
| 473 | + | ||
| 474 | +def cover_setup(sites, anchor, k, opts, dimensions, min_dims): | ||
| 475 | + """Initialize the seeded coverage pool without consuming random draws.""" | ||
| 476 | + if k <= 0 or not sites or dimensions(sites, anchor) < min_dims: | ||
| 477 | + return None | ||
| 478 | + seen = {_key(c) for c in opts.exclude} | ||
| 479 | + if anchor: | ||
| 480 | + seen.add(_key(anchor)) | ||
| 481 | + return random.Random(opts.seed), seen | ||
| 482 | + | ||
| 483 | + | ||
| 484 | +# Public service API used by the shared core and DSL adapters. | ||
| 485 | +dist2 = _dist2 | ||
| 486 | +key = _key | ||
| 487 | +normalise = _normalise | ||
| @@ -241,7 +241,7 @@ class HW: | |||
| 241 | # these two need only the program and the chip. Leaving the footprint bound | 241 | # these two need only the program and the chip. Leaving the footprint bound |
| 242 | # switched off is what let a 16384-element tile reach the device against a | 242 | # switched off is what let a 16384-element tile reach the device against a |
| 243 | # buffer that holds about 12288. | 243 | # buffer that holds about 12288. |
| 244 | - ub_budget_kb: int = 192 | 244 | + ub_budget_kb: int = 0 # Unknown until the target supplies a capacity. |
| 245 | # 0 => unknown, rule off. Supplied by the optimizer as a FACT about | 245 | # 0 => unknown, rule off. Supplied by the optimizer as a FACT about |
| 246 | # residency, never as a bound. | 246 | # residency, never as a bound. |
| 247 | n_live_tiles: int = 0 | 247 | n_live_tiles: int = 0 |
| @@ -315,13 +315,13 @@ def kind_of(sites, sid): | |||
| 315 | 315 | ||
| 316 | 316 | ||
| 317 | # ------------------------------------------------------------------------------- per-site space | 317 | # ------------------------------------------------------------------------------- per-site space |
| 318 | -def admit(base, val): | 318 | +def admit(base, val, *, key=None): |
| 319 | """Base domain, guaranteeing the anchor (current) value is a legal choice. Optuna categoricals | 319 | """Base domain, guaranteeing the anchor (current) value is a legal choice. Optuna categoricals |
| 320 | must contain the enqueued warm-start value, and real kernels use values outside our static sets | 320 | must contain the enqueued warm-start value, and real kernels use values outside our static sets |
| 321 | (device_sched_mode=3, a 40-row tile, a 10240-wide tile, ...) — so always include the current | 321 | (device_sched_mode=3, a 40-row tile, a 10240-wide tile, ...) — so always include the current |
| 322 | one. The ladder is a sampling grid, never a constraint on what the kernel may already hold. | 322 | one. The ladder is a sampling grid, never a constraint on what the kernel may already hold. |
| 323 | """ | 323 | """ |
| 324 | - return base if (val is None or val in base) else sorted(set(base) | {val}) | 324 | + return base if (val is None or val in base) else sorted(set(base) | {val}, key=key) |
| 325 | 325 | ||
| 326 | 326 | ||
| 327 | CONST_SCALES = [1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8] | 327 | CONST_SCALES = [1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8] |
| @@ -393,25 +393,21 @@ def vec_domain(site_id, field, fields, anchor_cfg, domain=None): | |||
| 393 | per candidate, too narrow is invisible. | 393 | per candidate, too narrow is invisible. |
| 394 | """ | 394 | """ |
| 395 | base = VEC_TRAILING_CHOICES if field == fields[-1] else VEC_CHOICES | 395 | base = VEC_TRAILING_CHOICES if field == fields[-1] else VEC_CHOICES |
| 396 | - derived = (domain or {}).get("per_site", {}).get(site_id, {}).get(field) | ||
| 397 | - ladder = list(derived if derived else base) | ||
| 398 | - # Drop rungs that overflow the UB even with every other dimension at its | ||
| 399 | - # smallest -- no feasible tile can use them, so sampling them only burns TPE's | ||
| 400 | - # startup draws (the ladder reaches 16384 against a cap that can be near 1024). | ||
| 401 | - # This removes no reachable config; `dom` still re-admits the anchor, so the | ||
| 402 | - # running kernel's value is a legal choice even if it sits above the cap. | ||
| 403 | - # Aliased: the bare import rebound the PARAMETER `domain` to the module, so | ||
| 404 | - # the derived domain was lost and the module itself was passed in its place. | ||
| 405 | from . import domain as domain_mod | 396 | from . import domain as domain_mod |
| 406 | - | 397 | + ladder = capped_ladder(domain, site_id, field, base, |
| 407 | - cap = domain_mod.vec_ladder_cap(domain, site_id, field, fields) | 398 | + domain_mod.vec_ladder_cap(domain, site_id, field, fields)) |
| 408 | - if cap: | ||
| 409 | - pruned = [v for v in ladder if v <= cap] | ||
| 410 | - if pruned: # never empty the ladder | ||
| 411 | - ladder = pruned | ||
| 412 | return admit(ladder, (anchor_cfg or {}).get(field)) | 399 | return admit(ladder, (anchor_cfg or {}).get(field)) |
| 413 | 400 | ||
| 414 | 401 | ||
| 402 | +def capped_ladder(domain, site_id, field, fallback, cap): | ||
| 403 | + """Use a derived ladder when available; apply the cap only if a rung remains.""" | ||
| 404 | + derived = (domain or {}).get("per_site", {}).get(site_id, {}).get(field) | ||
| 405 | + ladder = list(derived or fallback) | ||
| 406 | + if cap: | ||
| 407 | + return [v for v in ladder if v <= cap] or ladder | ||
| 408 | + return ladder | ||
| 409 | + | ||
| 410 | + | ||
| 415 | def tied_lead_domain(tie, sites, anchor=None, domain=None): | 411 | def tied_lead_domain(tie, sites, anchor=None, domain=None): |
| 416 | """{tie_head: [choices]} -- ONE domain for the leading field a tie group shares. | 412 | """{tie_head: [choices]} -- ONE domain for the leading field a tie group shares. |
| 417 | 413 | ||
| @@ -551,7 +547,7 @@ def _draw_site(trial, site, r, ctx): | |||
| 551 | return _draw_vec(trial, r, a, ctx) | 547 | return _draw_vec(trial, r, a, ctx) |
| 552 | 548 | ||
| 553 | 549 | ||
| 554 | -def _apply_tie(cfg, tie): | 550 | +def _apply_tie(cfg, tie, fields_of=vec_fields): |
| 555 | """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. |
| 556 | 552 | ||
| 557 | A tied site is drawn independently (it is its own `rep`), so without this the | 553 | A tied site is drawn independently (it is its own `rep`), so without this the |
| @@ -562,7 +558,7 @@ def _apply_tie(cfg, tie): | |||
| 562 | head = next((cfg.get(g) for g in grp if g in cfg), None) | 558 | head = next((cfg.get(g) for g in grp if g in cfg), None) |
| 563 | if not head: | 559 | if not head: |
| 564 | continue | 560 | continue |
| 565 | - f0 = next(iter(vec_fields(head)), None) | 561 | + f0 = next(iter(fields_of(head)), None) |
| 566 | if f0 is None: | 562 | if f0 is None: |
| 567 | continue | 563 | continue |
| 568 | for sid in grp: | 564 | for sid in grp: |
| @@ -591,14 +587,23 @@ def suggest(trial, sites, opts=None): | |||
| 591 | # `tied_lead_domain`. | 587 | # `tied_lead_domain`. |
| 592 | "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), |
| 593 | } | 589 | } |
| 590 | + cfg = draw_grouped(trial, sites, rep, ctx, _draw_site) | ||
| 591 | + _apply_tie(cfg, opts.tie) | ||
| 592 | + return cfg | ||
| 593 | + | ||
| 594 | + | ||
| 595 | +def draw_grouped(trial, sites, rep, ctx, draw_site, *, movable=None, anchor=None): | ||
| 596 | + """Draw each representative once. Held sites keep their values outside the trial.""" | ||
| 594 | drawn = {} | 597 | drawn = {} |
| 595 | cfg = {} | 598 | cfg = {} |
| 596 | - for s in sites: | 599 | + for site in sites: |
| 597 | - r = rep[s.id] | 600 | + if movable is not None and site.id not in movable: |
| 598 | - if r not in drawn: | 601 | + cfg[site.id] = dict(anchor.get(site.id) or {}) |
| 599 | - drawn[r] = _draw_site(trial, s, r, ctx) | 602 | + continue |
| 600 | - cfg[s.id] = dict(drawn[r]) | 603 | + representative = rep[site.id] |
| 601 | - _apply_tie(cfg, opts.tie) | 604 | + if representative not in drawn: |
| 605 | + drawn[representative] = draw_site(trial, site, representative, ctx) | ||
| 606 | + cfg[site.id] = dict(drawn[representative]) | ||
| 602 | return cfg | 607 | return cfg |
| 603 | 608 | ||
| 604 | 609 | ||
| @@ -640,19 +645,26 @@ def flatten(site_configs, sites, groups=None, tie=None): | |||
| 640 | """ | 645 | """ |
| 641 | rep = _rep(sites, groups) | 646 | rep = _rep(sites, groups) |
| 642 | lead = _tie_rep(sites, tie) | 647 | lead = _tie_rep(sites, tie) |
| 648 | + return encode_sites(site_configs, sites, rep, lead, vec_fields, cube_encoder=_cube_to_params) | ||
| 649 | + | ||
| 650 | + | ||
| 651 | +def encode_sites(site_configs, sites, rep, lead, fields_of, *, partial=False, cube_encoder=None): | ||
| 652 | + """Encode a site map using its group representatives and leading-axis ties.""" | ||
| 643 | params = {} | 653 | params = {} |
| 644 | for s in sites: | 654 | for s in sites: |
| 645 | r = rep[s.id] | 655 | r = rep[s.id] |
| 656 | + if partial and site_configs.get(s.id) is None: | ||
| 657 | + continue | ||
| 646 | cfg = site_configs[s.id] | 658 | cfg = site_configs[s.id] |
| 647 | - if s.kind == "cube": | 659 | + if cube_encoder and s.kind == "cube": |
| 648 | # L1 is encoded as a multiplier so the params match the fixed domain | 660 | # L1 is encoded as a multiplier so the params match the fixed domain |
| 649 | # `suggest` draws from; the config keeps the actual L1 value. | 661 | # `suggest` draws from; the config keeps the actual L1 value. |
| 650 | - params.update(_cube_to_params(r, cfg)) | 662 | + params.update(cube_encoder(r, cfg)) |
| 651 | continue | 663 | continue |
| 652 | # Field-agnostic for the rest: the config carries whatever knobs the site | 664 | # Field-agnostic for the rest: the config carries whatever knobs the site |
| 653 | # has, which for a vec site is however many arguments the call was written | 665 | # has, which for a vec site is however many arguments the call was written |
| 654 | # with. | 666 | # with. |
| 655 | - fields = vec_fields(cfg) if s.kind == "vec" else [] | 667 | + fields = fields_of(cfg) if s.kind == "vec" else [] |
| 656 | for field, v in cfg.items(): | 668 | for field, v in cfg.items(): |
| 657 | params[_lead_key(lead, r, field, fields)] = v | 669 | params[_lead_key(lead, r, field, fields)] = v |
| 658 | return params | 670 | return params |
| @@ -662,11 +674,16 @@ def unflatten(params, sites, groups=None, tie=None): | |||
| 662 | """Flat Optuna params -> per-site config dict.""" | 674 | """Flat Optuna params -> per-site config dict.""" |
| 663 | rep = _rep(sites, groups) | 675 | rep = _rep(sites, groups) |
| 664 | lead = _tie_rep(sites, tie) | 676 | lead = _tie_rep(sites, tie) |
| 677 | + return decode_sites(params, sites, rep, lead, cube_decoder=_params_to_cube) | ||
| 678 | + | ||
| 679 | + | ||
| 680 | +def decode_sites(params, sites, rep, lead, *, cube_decoder=None): | ||
| 681 | + """Recover local coordinates and the shared leading axis for each site.""" | ||
| 665 | cfg = {} | 682 | cfg = {} |
| 666 | for s in sites: | 683 | for s in sites: |
| 667 | pre = rep[s.id] + "." | 684 | pre = rep[s.id] + "." |
| 668 | - if s.kind == "cube": | 685 | + if cube_decoder and s.kind == "cube": |
| 669 | - cfg[s.id] = _params_to_cube(pre, params) | 686 | + cfg[s.id] = cube_decoder(pre, params) |
| 670 | continue | 687 | continue |
| 671 | own = {} | 688 | own = {} |
| 672 | for k, v in params.items(): | 689 | for k, v in params.items(): |
| @@ -963,9 +980,12 @@ def repair(cfg, check, ctx=RepairContext()): | |||
| 963 | return None, ctx.max_steps | 980 | return None, ctx.max_steps |
| 964 | 981 | ||
| 965 | 982 | ||
| 966 | -def _is_capacity(why): | 983 | +def is_capacity(why): |
| 967 | return ( | 984 | return ( |
| 968 | why.startswith(("L0A", "L0B", "L0C", "L1 tile", "largest tile")) | 985 | why.startswith(("L0A", "L0B", "L0C", "L1 tile", "largest tile")) |
| 969 | or " UB" in why | 986 | or " UB" in why |
| 970 | or "head_dim" in why | 987 | or "head_dim" in why |
| 971 | ) | 988 | ) |
| 989 | + | ||
| 990 | + | ||
| 991 | +_is_capacity = is_capacity | ||
| @@ -44,3 +44,15 @@ _log.propagate = False | |||
| 44 | def emit(obj, indent=None): | 44 | def emit(obj, indent=None): |
| 45 | """Write one JSON document to the protocol channel.""" | 45 | """Write one JSON document to the protocol channel.""" |
| 46 | _log.info(json.dumps(obj, ensure_ascii=False, indent=indent)) | 46 | _log.info(json.dumps(obj, ensure_ascii=False, indent=indent)) |
| 47 | + | ||
| 48 | + | ||
| 49 | +def last_object(text): | ||
| 50 | + """Read the last complete JSON object line from subprocess output.""" | ||
| 51 | + for line in reversed((text or "").strip().splitlines()): | ||
| 52 | + line = line.strip() | ||
| 53 | + if line.startswith("{"): | ||
| 54 | + try: | ||
| 55 | + return json.loads(line) | ||
| 56 | + except ValueError: | ||
| 57 | + continue | ||
| 58 | + return None | ||
| @@ -53,14 +53,16 @@ import time | |||
| 53 | import types | 53 | import types |
| 54 | from typing import Any, NamedTuple | 54 | from typing import Any, NamedTuple |
| 55 | 55 | ||
| 56 | -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | 56 | +if __package__: |
| 57 | -import jsonio # noqa: E402 | 57 | + jsonio = importlib.import_module(f"{__package__}.jsonio") |
| 58 | -import workspace_probe # noqa: E402 | 58 | + workspace_probe = importlib.import_module(f"{__package__}.workspace_probe") |
| 59 | - | 59 | + chip_profile = importlib.import_module(f"{__package__}.chip_profile") |
| 60 | -# One home for the two runtime questions, rather than a copy here: ask for an | 60 | + _optional, _quietly = chip_profile.optional, chip_profile.quietly |
| 61 | -# optional module, and treat a driver's refusal as the answer. `chip_profile` | 61 | +else: |
| 62 | -# owns them because it is where the refusals are load-bearing. | 62 | + sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| 63 | -from chip_profile import optional as _optional, quietly as _quietly # noqa: E402 | 63 | + import jsonio |
| 64 | + import workspace_probe | ||
| 65 | + from chip_profile import optional as _optional, quietly as _quietly | ||
| 64 | 66 | ||
| 65 | leaked_capture = [] # capture files a cleanup could not remove | 67 | leaked_capture = [] # capture files a cleanup could not remove |
| 66 | 68 | ||
| @@ -272,12 +274,15 @@ def _sigma_log(vals): | |||
| 272 | return round(math.sqrt(var), 6) | 274 | return round(math.sqrt(var), 6) |
| 273 | 275 | ||
| 274 | 276 | ||
| 275 | -def _agg(vals, how): | 277 | +def aggregate(vals, how="median"): |
| 276 | if not vals: | 278 | if not vals: |
| 277 | return None | 279 | return None |
| 278 | return round(min(vals) if how == "min" else statistics.median(vals), 4) | 280 | return round(min(vals) if how == "min" else statistics.median(vals), 4) |
| 279 | 281 | ||
| 280 | 282 | ||
| 283 | +_agg = aggregate | ||
| 284 | + | ||
| 285 | + | ||
| 281 | FIRST_CALL_MARKER = "[panko-progress] first_call_done" | 286 | FIRST_CALL_MARKER = "[panko-progress] first_call_done" |
| 282 | 287 | ||
| 283 | 288 | ||
| @@ -503,7 +508,7 @@ MSPROF_RATIO_RANGES = { | |||
| 503 | } | 508 | } |
| 504 | 509 | ||
| 505 | 510 | ||
| 506 | -def _cell(row, column): | 511 | +def profile_cell(row, column): |
| 507 | """`row[column]` as a float, tolerating the header's unit suffix and tabs.""" | 512 | """`row[column]` as a float, tolerating the header's unit suffix and tabs.""" |
| 508 | want = column.split("(")[0].strip().lower() | 513 | want = column.split("(")[0].strip().lower() |
| 509 | for k, v in row.items(): | 514 | for k, v in row.items(): |
| @@ -516,6 +521,9 @@ def _cell(row, column): | |||
| 516 | return None | 521 | return None |
| 517 | 522 | ||
| 518 | 523 | ||
| 524 | +_cell = profile_cell | ||
| 525 | + | ||
| 526 | + | ||
| 519 | def msprof_metrics(rows, total, warmup): | 527 | def msprof_metrics(rows, total, warmup): |
| 520 | """The diagnostic columns of the warm MIX_AIC rows. | 528 | """The diagnostic columns of the warm MIX_AIC rows. |
| 521 | 529 | ||
| @@ -575,6 +583,11 @@ def _row_start(row): | |||
| 575 | return None | 583 | return None |
| 576 | 584 | ||
| 577 | 585 | ||
| 586 | +def read_profile_rows(csv_path): | ||
| 587 | + with open(csv_path, encoding="utf-8", errors="replace", newline="") as handle: | ||
| 588 | + return list(csv.DictReader(handle)) | ||
| 589 | + | ||
| 590 | + | ||
| 578 | def mix_aic_rows(csv_path): | 591 | def mix_aic_rows(csv_path): |
| 579 | """One op_summary's MIX_AIC rows in launch order. | 592 | """One op_summary's MIX_AIC rows in launch order. |
| 580 | 593 | ||
| @@ -582,8 +595,7 @@ def mix_aic_rows(csv_path): | |||
| 582 | raw rows so the diagnostic columns are read from the same rows as `p`, | 595 | raw rows so the diagnostic columns are read from the same rows as `p`, |
| 583 | never from a second, differently filtered pass. | 596 | never from a second, differently filtered pass. |
| 584 | """ | 597 | """ |
| 585 | - with open(csv_path, encoding="utf-8", errors="replace", newline="") as f: | 598 | + allrows = read_profile_rows(csv_path) |
| 586 | - allrows = list(csv.DictReader(f)) | ||
| 587 | task_types = sorted({str(r.get("Task Type", "")).strip() for r in allrows}) | 599 | task_types = sorted({str(r.get("Task Type", "")).strip() for r in allrows}) |
| 588 | rows = [ | 600 | rows = [ |
| 589 | r for r in allrows if str(r.get("Task Type", "")).strip() == MIX_AIC_TASK_TYPE | 601 | r for r in allrows if str(r.get("Task Type", "")).strip() == MIX_AIC_TASK_TYPE |
| @@ -642,15 +654,7 @@ def mix_aic_reading(rows, total, warmup, agg="median", task_types=None): | |||
| 642 | } | 654 | } |
| 643 | 655 | ||
| 644 | 656 | ||
| 645 | -def _last_json(text): | 657 | +_last_json = jsonio.last_object |
| 646 | - for line in reversed((text or "").strip().splitlines()): | ||
| 647 | - line = line.strip() | ||
| 648 | - if line.startswith("{"): | ||
| 649 | - try: | ||
| 650 | - return json.loads(line) | ||
| 651 | - except ValueError: | ||
| 652 | - continue | ||
| 653 | - return None | ||
| 654 | 658 | ||
| 655 | 659 | ||
| 656 | class ProfOptions(NamedTuple): | 660 | class ProfOptions(NamedTuple): |
| @@ -661,6 +665,13 @@ class ProfOptions(NamedTuple): | |||
| 661 | msprof: str = "msprof" | 665 | msprof: str = "msprof" |
| 662 | 666 | ||
| 663 | 667 | ||
| 668 | +def msprof_command(executable, out_dir, argv, *, aic_metrics=None): | ||
| 669 | + command = [executable, f"--output={out_dir}", "--ai-core=on", "--task-time=on", "--ascendcl=on"] | ||
| 670 | + if aic_metrics: | ||
| 671 | + command.append(f"--aic-metrics={aic_metrics}") | ||
| 672 | + return [*command, *argv] | ||
| 673 | + | ||
| 674 | + | ||
| 664 | def measure_under_msprof(argv, warmup, runs, agg, prof_opts=ProfOptions()): | 675 | def measure_under_msprof(argv, warmup, runs, agg, prof_opts=ProfOptions()): |
| 665 | """Run the measurement as a child of msprof; `p` becomes its MIX_AIC. | 676 | """Run the measurement as a child of msprof; `p` becomes its MIX_AIC. |
| 666 | 677 | ||
| @@ -676,8 +687,7 @@ def measure_under_msprof(argv, warmup, runs, agg, prof_opts=ProfOptions()): | |||
| 676 | out_dir = tempfile.mkdtemp(prefix="panko_msprof_", dir=prof_opts.prof_root) | 687 | out_dir = tempfile.mkdtemp(prefix="panko_msprof_", dir=prof_opts.prof_root) |
| 677 | env = dict(os.environ) | 688 | env = dict(os.environ) |
| 678 | env[MSPROF_CHILD_ENV] = "1" | 689 | env[MSPROF_CHILD_ENV] = "1" |
| 679 | - cmd = [prof_opts.msprof, f"--output={out_dir}", "--ai-core=on", "--task-time=on", | 690 | + cmd = msprof_command(prof_opts.msprof, out_dir, [sys.executable, os.path.abspath(__file__), *argv]) |
| 680 | - "--ascendcl=on", sys.executable, os.path.abspath(__file__), *argv] | ||
| 681 | r = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=None, text=True, env=env, | 691 | r = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=None, text=True, env=env, |
| 682 | check=False) | 692 | check=False) |
| 683 | if r.stdout: | 693 | if r.stdout: |
| @@ -0,0 +1,47 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | + | ||
| 10 | +"""Select a DSL adapter before importing the command modules. | ||
| 11 | + | ||
| 12 | +The native entrypoint never registers one and retains its existing defaults. | ||
| 13 | +A CLI process uses exactly one backend; command modules are not monkey-patched. | ||
| 14 | +""" | ||
| 15 | +import sys | ||
| 16 | + | ||
| 17 | +_frontend = None | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def register(frontend): | ||
| 21 | + """Install one DSL adapter for this process before importing panko_harness or panko.config. | ||
| 22 | + | ||
| 23 | + At import time the core reads the adapter's catalog path, defaults mapping, | ||
| 24 | + predicates and feasibility modules, and calls bayesian() for its tile-search API. | ||
| 25 | + A second or late registration raises RuntimeError. Classic uses the built-in defaults. | ||
| 26 | + | ||
| 27 | + INIT uses revision() for code provenance, default_reference as a (value, provenance) | ||
| 28 | + pair, state_metadata(args) to extend campaign state, and verify_initialization(args, state). | ||
| 29 | + | ||
| 30 | + Search uses wrapper_signature(source) and debug_options_signature(source) to check edits. | ||
| 31 | + If owned bindings were recorded, wrapper_signature also takes context and owned bindings. | ||
| 32 | + tile_constants(state, path, source) supplies tile-search keyword arguments. | ||
| 33 | + EXPORT_OUTCOMES controls whether outcome records also go to the shared prior store. | ||
| 34 | + | ||
| 35 | + entry_reads(row) returns independent readings. reading_interval(xs, ys, alpha=...) | ||
| 36 | + returns ratio bounds (ci_low and ci_high) or None. write_source(path, text) stages | ||
| 37 | + or restores code, export_source(src, dst) exports its snapshot, and verification_policy() | ||
| 38 | + returns the policy for the final ABBA comparison. | ||
| 39 | + """ | ||
| 40 | + global _frontend | ||
| 41 | + if _frontend is not None or __package__ + ".config" in sys.modules: | ||
| 42 | + raise RuntimeError("select the PANKO backend once, before importing commands") | ||
| 43 | + _frontend = frontend | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def current(): | ||
| 47 | + return _frontend | ||
| @@ -17,10 +17,12 @@ measurement of the program it proposed. | |||
| 17 | import datetime | 17 | import datetime |
| 18 | import hashlib | 18 | import hashlib |
| 19 | import os | 19 | import os |
| 20 | +from pathlib import Path | ||
| 20 | 21 | ||
| 22 | +from .backend import current | ||
| 21 | from .config import FREE, REFUSAL_GLOBAL_AFTER, Refusal, SEARCH_PROTOCOL, bayesian, out | 23 | from .config import FREE, REFUSAL_GLOBAL_AFTER, Refusal, SEARCH_PROTOCOL, bayesian, out |
| 22 | -from .state import (_structure, chip_envelope, confirm_chip, load, merge_refusals, op_file_path, | 24 | +from .state import (_source_wrapper_drift, _structure, chip_envelope, confirm_chip, file_hash, load, merge_refusals, |
| 23 | - refusals_for_structure, save, stored_refusals) | 25 | + op_file_path, refusals_for_structure, save, snapshot_source, stored_refusals) |
| 24 | from .measurement import incumbent_latency, observe_noise | 26 | from .measurement import incumbent_latency, observe_noise |
| 25 | from .front import archive_record | 27 | from .front import archive_record |
| 26 | from .stopping import _free_rejects, block_budget, budget_reason, fault_markers | 28 | from .stopping import _free_rejects, block_budget, budget_reason, fault_markers |
| @@ -45,7 +47,7 @@ def _block_context(a, st, cfg): | |||
| 45 | is the evidence, so a run now pays twice and saves the remainder. | 47 | is the evidence, so a run now pays twice and saves the remainder. |
| 46 | """ | 48 | """ |
| 47 | op_file = op_file_path(st, a.op_dir) | 49 | op_file = op_file_path(st, a.op_dir) |
| 48 | - with open(op_file, encoding="utf-8", errors="replace") as f: | 50 | + with open(op_file, encoding="utf-8", errors="replace", newline="" if current() else None) as f: |
| 49 | base_src = f.read() | 51 | base_src = f.read() |
| 50 | hw, domain = bayesian.block.hw_for(op_file, a.live_tiles, chip_envelope(st)) | 52 | hw, domain = bayesian.block.hw_for(op_file, a.live_tiles, chip_envelope(st)) |
| 51 | structure = _structure(st, a.op_dir) | 53 | structure = _structure(st, a.op_dir) |
| @@ -100,9 +102,11 @@ def _block_search(a, st, ctx, cfg): | |||
| 100 | asks whether `best_aicore_e2e_us` may be quoted as THIS program's incumbent, and | 102 | asks whether `best_aicore_e2e_us` may be quoted as THIS program's incumbent, and |
| 101 | that is only true of the exact bytes. | 103 | that is only true of the exact bytes. |
| 102 | """ | 104 | """ |
| 105 | + frontend = current() | ||
| 103 | ev = bayesian.evaluator.RealEvaluator( | 106 | ev = bayesian.evaluator.RealEvaluator( |
| 104 | op=st["op"], op_dir=a.op_dir, op_file=ctx["op_file"], device=st.get("device_id", ""), | 107 | op=st["op"], op_dir=a.op_dir, op_file=ctx["op_file"], device=st.get("device_id", ""), |
| 105 | test_command=a.test_command, lint_root=(a.lint_root or None), | 108 | test_command=a.test_command, lint_root=(a.lint_root or None), |
| 109 | + write_source=frontend.write_source if frontend is not None else None, | ||
| 106 | eval_timeout_s=cfg.get("eval_timeout_s", 300), | 110 | eval_timeout_s=cfg.get("eval_timeout_s", 300), |
| 107 | evaluation_mode=getattr(a, "evaluation_mode", "subprocess"), | 111 | evaluation_mode=getattr(a, "evaluation_mode", "subprocess"), |
| 108 | # Overridable so tests can assert the schedule without waiting it out. | 112 | # Overridable so tests can assert the schedule without waiting it out. |
| @@ -119,7 +123,7 @@ def _block_search(a, st, ctx, cfg): | |||
| 119 | # by a comparison against `ratchet_best_hash` -- which gave up the | 123 | # by a comparison against `ratchet_best_hash` -- which gave up the |
| 120 | # incumbent entirely whenever the front base was not `best_node`. | 124 | # incumbent entirely whenever the front base was not `best_node`. |
| 121 | current_latency=incumbent_latency(st, ctx["base_src"]), | 125 | current_latency=incumbent_latency(st, ctx["base_src"]), |
| 122 | - on_trial=block_recorder(a, st, ctx), domain=ctx["domain"], | 126 | + on_trial=block_recorder(a, st, ctx, ev if frontend is not None else None), domain=ctx["domain"], |
| 123 | # `bayesian.block.run` defaults this to 4, while `hw_for` derives the real | 127 | # `bayesian.block.run` defaults this to 4, while `hw_for` derives the real |
| 124 | # element width from the kernel and defaults it to 2. Leaving it | 128 | # element width from the kernel and defaults it to 2. Leaving it |
| 125 | # unthreaded meant every block on a bf16/fp16 kernel computed its 16 KB | 129 | # unthreaded meant every block on a bf16/fp16 kernel computed its 16 KB |
| @@ -281,7 +285,7 @@ def _fault_record(st, a, rec): | |||
| 281 | "detail": (rec.get("detail") or "")[:2000]} | 285 | "detail": (rec.get("detail") or "")[:2000]} |
| 282 | 286 | ||
| 283 | 287 | ||
| 284 | -def block_recorder(a, st, ctx): | 288 | +def block_recorder(a, st, ctx, evaluator=None): |
| 285 | """Build the per-trial callback: count what touched the device, and cache the | 289 | """Build the per-trial callback: count what touched the device, and cache the |
| 286 | bytes it measured. | 290 | bytes it measured. |
| 287 | 291 | ||
| @@ -339,10 +343,17 @@ def block_recorder(a, st, ctx): | |||
| 339 | if rec.get("metrics"): | 343 | if rec.get("metrics"): |
| 340 | t["metrics"] = rec["metrics"] | 344 | t["metrics"] = rec["metrics"] |
| 341 | ctx["trials"].append(t) | 345 | ctx["trials"].append(t) |
| 342 | - new_src, n = bayesian.block.apply_best(ctx["base_src"], rec.get("config")) | 346 | + if evaluator is None: |
| 343 | - if not n: | 347 | + new_src, n = bayesian.block.apply_best(ctx["base_src"], rec.get("config"), **ctx.get("apply_options", {})) |
| 344 | - return | 348 | + if not n: |
| 345 | - h = hashlib.sha256(new_src.encode("utf-8")).hexdigest() | 349 | + return |
| 350 | + data = new_src.encode("utf-8") | ||
| 351 | + else: | ||
| 352 | + data = evaluator.last_trial_bytes | ||
| 353 | + if data is None: | ||
| 354 | + return | ||
| 355 | + h = hashlib.sha256(data).hexdigest() | ||
| 356 | + t["code_hash"] = h | ||
| 346 | ctx["winners"].setdefault(h, 0) | 357 | ctx["winners"].setdefault(h, 0) |
| 347 | ctx["winners"][h] += 1 | 358 | ctx["winners"][h] += 1 |
| 348 | # `p` is what the trial was ranked on, which is `J_OBJECTIVE`'s | 359 | # `p` is what the trial was ranked on, which is `J_OBJECTIVE`'s |
| @@ -359,22 +370,45 @@ def block_recorder(a, st, ctx): | |||
| 359 | entry["samples"] = list(rec["samples"]) | 370 | entry["samples"] = list(rec["samples"]) |
| 360 | cache.setdefault(h, entry) | 371 | cache.setdefault(h, entry) |
| 361 | if rec.get("objective_us"): | 372 | if rec.get("objective_us"): |
| 362 | - archive_record(st, h, rec["objective_us"], | 373 | + if not _source_wrapper_drift(st, data.decode("utf-8", errors="replace")): |
| 363 | - rec.get("metrics") or {}, a.parent) | 374 | + archive_record(st, h, rec["objective_us"], rec.get("metrics") or {}, a.parent) |
| 375 | + if st["config"].get("snapshot_all_candidates", True): | ||
| 376 | + # The working file may already be restored to the block's base. | ||
| 377 | + try: | ||
| 378 | + snapshot_source(a.op_dir, h, data) | ||
| 379 | + except OSError: | ||
| 380 | + progress = st["progress"] | ||
| 381 | + progress["snapshot_misses"] = progress.get("snapshot_misses", 0) + 1 | ||
| 364 | 382 | ||
| 365 | return on_trial | 383 | return on_trial |
| 366 | 384 | ||
| 367 | 385 | ||
| 386 | +def _write_text(path, src): | ||
| 387 | + Path(path).write_text(src, encoding="utf-8") | ||
| 388 | + | ||
| 389 | + | ||
| 368 | def block_apply_winner(st, ctx, result): | 390 | def block_apply_winner(st, ctx, result): |
| 369 | """Write the winning tile config into the op_file, if the block found one.""" | 391 | """Write the winning tile config into the op_file, if the block found one.""" |
| 370 | if not result.get("best_config") or result.get("best_was_incumbent"): | 392 | if not result.get("best_config") or result.get("best_was_incumbent"): |
| 371 | return | 393 | return |
| 372 | - new_src, n = bayesian.block.apply_best(ctx["base_src"], result["best_config"]) | 394 | + new_src, n = bayesian.block.apply_best(ctx["base_src"], result["best_config"], **ctx.get("apply_options", {})) |
| 373 | if not n: | 395 | if not n: |
| 374 | return | 396 | return |
| 375 | - winner_hash = hashlib.sha256(new_src.encode("utf-8")).hexdigest() | 397 | + frontend = current() |
| 376 | - with open(ctx["op_file"], "w", encoding="utf-8") as f: | 398 | + path = ctx["op_file"] |
| 377 | - f.write(new_src) | 399 | + write = frontend.write_source if frontend is not None else _write_text |
| 400 | + write(path, new_src) | ||
| 401 | + winner_hash = file_hash(path) | ||
| 402 | + expected = None | ||
| 403 | + for trial in reversed(ctx.get("trials", [])): | ||
| 404 | + if trial.get("objective_us") and trial.get("config") == result["best_config"] and "code_hash" in trial: | ||
| 405 | + expected = trial.get("code_hash") | ||
| 406 | + break | ||
| 407 | + if expected is not None and expected != winner_hash: | ||
| 408 | + write(path, ctx["base_src"]) | ||
| 409 | + result.update(aborted="winner bytes differ from the measured trial", best_config=None, | ||
| 410 | + best_objective_us=None) | ||
| 411 | + return | ||
| 378 | # Left OUT of the cache on purpose: `record` must see it as new, so it charges | 412 | # Left OUT of the cache on purpose: `record` must see it as new, so it charges |
| 379 | # the one remaining evaluation and runs the ratchet. | 413 | # the one remaining evaluation and runs the ratchet. |
| 380 | entry = st.setdefault("eval_cache", {}).pop(winner_hash, None) | 414 | entry = st.setdefault("eval_cache", {}).pop(winner_hash, None) |
| @@ -19,7 +19,11 @@ import os | |||
| 19 | import sys | 19 | import sys |
| 20 | import typing | 20 | import typing |
| 21 | 21 | ||
| 22 | +from contextvars import ContextVar | ||
| 22 | import jsonio | 23 | import jsonio |
| 24 | +from .backend import current | ||
| 25 | + | ||
| 26 | +_FRONTEND = current() | ||
| 23 | 27 | ||
| 24 | 28 | ||
| 25 | # The package needs `optuna`, which is a real dependency of the tile search and | 29 | # The package needs `optuna`, which is a real dependency of the tile search and |
| @@ -65,7 +69,10 @@ def is_missing_optuna(exc): | |||
| 65 | 69 | ||
| 66 | 70 | ||
| 67 | try: | 71 | try: |
| 68 | - import bayesian_optimization as bayesian | 72 | + if _FRONTEND is None: |
| 73 | + import bayesian_optimization as bayesian | ||
| 74 | + else: | ||
| 75 | + bayesian = _FRONTEND.bayesian() | ||
| 69 | _BAYESIAN_UNAVAILABLE = None | 76 | _BAYESIAN_UNAVAILABLE = None |
| 70 | except ModuleNotFoundError as _e: # pragma: no cover | 77 | except ModuleNotFoundError as _e: # pragma: no cover |
| 71 | if not is_missing_optuna(_e): | 78 | if not is_missing_optuna(_e): |
| @@ -601,9 +608,28 @@ def skill_path(*parts): | |||
| 601 | DEFAULT_CATALOG = skill_path("references", "action_catalog.json") | 608 | DEFAULT_CATALOG = skill_path("references", "action_catalog.json") |
| 602 | 609 | ||
| 603 | 610 | ||
| 611 | + | ||
| 612 | +_reply = ContextVar("panko_reply", default=None) | ||
| 613 | + | ||
| 614 | + | ||
| 615 | +def call_transition(command, args): | ||
| 616 | + """Run an existing CLI transition inside the campaign lock and retain its reply.""" | ||
| 617 | + replies = [] | ||
| 618 | + token = _reply.set(replies.append) | ||
| 619 | + try: | ||
| 620 | + command(args) | ||
| 621 | + except Refusal as exc: | ||
| 622 | + exc.reply = replies[-1] if replies else {"error": "transition_refused"} | ||
| 623 | + raise | ||
| 624 | + finally: | ||
| 625 | + _reply.reset(token) | ||
| 626 | + reply, = replies | ||
| 627 | + return reply | ||
| 628 | + | ||
| 629 | + | ||
| 604 | def out(obj): | 630 | def out(obj): |
| 605 | """One JSON directive on the protocol channel. See jsonio.""" | 631 | """One JSON directive on the protocol channel. See jsonio.""" |
| 606 | - jsonio.emit(obj) | 632 | + (_reply.get() or jsonio.emit)(obj) |
| 607 | 633 | ||
| 608 | 634 | ||
| 609 | class Refusal(Exception): | 635 | class Refusal(Exception): |
| @@ -896,3 +922,11 @@ class CandidateRow(typing.NamedTuple): | |||
| 896 | archive: typing.Any | 922 | archive: typing.Any |
| 897 | n: typing.Any | 923 | n: typing.Any |
| 898 | note: str = "" | 924 | note: str = "" |
| 925 | + | ||
| 926 | + | ||
| 927 | +if _FRONTEND is not None: | ||
| 928 | + DEFAULT_CATALOG = _FRONTEND.catalog | ||
| 929 | + DEFAULT_CONFIG.update(_FRONTEND.defaults) | ||
| 930 | + predicates = _FRONTEND.predicates | ||
| 931 | + feasibility = _FRONTEND.feasibility | ||
| 932 | + SYMPTOM_ACTIONS = {key: set() for key in SYMPTOM_ACTIONS} | ||
| @@ -13,6 +13,7 @@ The ABBA pass, the front written out as source, and the human-readable | |||
| 13 | summary. Opened by `stop`; nothing here decides what to search next. | 13 | summary. Opened by `stop`; nothing here decides what to search next. |
| 14 | """ | 14 | """ |
| 15 | 15 | ||
| 16 | +from dataclasses import dataclass | ||
| 16 | import datetime | 17 | import datetime |
| 17 | import hashlib | 18 | import hashlib |
| 18 | import json | 19 | import json |
| @@ -77,10 +78,8 @@ def _delivered_check(st, op_dir): | |||
| 77 | So the last thing the harness says about a run includes the hash of what it | 78 | So the last thing the harness says about a run includes the hash of what it |
| 78 | actually left on disk, next to the hash it claims to have found. | 79 | actually left on disk, next to the hash it claims to have found. |
| 79 | 80 | ||
| 80 | - `best_code_hash` is what SHOULD be on disk -- `delivery_point`, falling | 81 | + `best_code_hash` is the eligible measurement chosen by `delivery_point`. |
| 81 | - back to `best_node`. `best_node_code_hash` is reported beside it whenever | 82 | + If the ratchet chose a different program, report its hash as `best_node_code_hash`. |
| 82 | - the two differ, because that difference is the defect C1 exists for and it | ||
| 83 | - should be visible in the run's own output rather than only in a hand diff. | ||
| 84 | """ | 83 | """ |
| 85 | want, detail = delivery_point(st, op_dir) | 84 | want, detail = delivery_point(st, op_dir) |
| 86 | node = ratchet_best_hash(st) | 85 | node = ratchet_best_hash(st) |
| @@ -88,8 +87,8 @@ def _delivered_check(st, op_dir): | |||
| 88 | on_disk = None | 87 | on_disk = None |
| 89 | if f and os.path.exists(f): | 88 | if f and os.path.exists(f): |
| 90 | on_disk = hashlib.sha256(_read_bytes(f)).hexdigest() | 89 | on_disk = hashlib.sha256(_read_bytes(f)).hexdigest() |
| 91 | - out_d = {"best_code_hash": want or node, "delivered_code_hash": on_disk, | 90 | + out_d = {"best_code_hash": want, "delivered_code_hash": on_disk, |
| 92 | - "delivered_is_best": bool(want or node) and on_disk == (want or node), | 91 | + "delivered_is_best": bool(want) and on_disk == want, |
| 93 | "delivery": detail} | 92 | "delivery": detail} |
| 94 | if want and node and want != node: | 93 | if want and node and want != node: |
| 95 | out_d["best_node_code_hash"] = node | 94 | out_d["best_node_code_hash"] = node |
| @@ -115,9 +114,8 @@ def _deliver_best(st, a): | |||
| 115 | "delivered": best_hash, "best_node": node, | 114 | "delivered": best_hash, "best_node": node, |
| 116 | "delivered_values": detail.get("values"), | 115 | "delivered_values": detail.get("values"), |
| 117 | "at_eval": st["progress"]["evals_used"]} | 116 | "at_eval": st["progress"]["evals_used"]} |
| 118 | - best_hash = best_hash or node | ||
| 119 | op_f = op_file_path(st, a.op_dir) | 117 | op_f = op_file_path(st, a.op_dir) |
| 120 | - if restore(a.op_dir, op_f, best_hash) or file_hash(op_f) == best_hash: | 118 | + if best_hash and (restore(a.op_dir, op_f, best_hash) or file_hash(op_f) == best_hash): |
| 121 | # Frozen, because everything after the stop has to name THIS program: | 119 | # Frozen, because everything after the stop has to name THIS program: |
| 122 | # the verification arm, the file put back between passes, the speedup | 120 | # the verification arm, the file put back between passes, the speedup |
| 123 | # the pass is compared against. `ratchet_best_hash` is `best_node` and | 121 | # the pass is compared against. `ratchet_best_hash` is `best_node` and |
| @@ -128,8 +126,8 @@ def _deliver_best(st, a): | |||
| 128 | return | 126 | return |
| 129 | out({"stop": False, "refused": True, "error": "restore_failed", | 127 | out({"stop": False, "refused": True, "error": "restore_failed", |
| 130 | "best_code_hash": best_hash, "op_file": op_f, | 128 | "best_code_hash": best_hash, "op_file": op_f, |
| 131 | - "reason": ("the global best has no snapshot on disk" | 129 | + "reason": ("the global best could not be restored" |
| 132 | - if best_hash else "no global best code_hash is recorded"), | 130 | + if best_hash else "no eligible measurement has a deliverable source"), |
| 133 | "hint": "the run cannot be closed out on a file that is not the " | 131 | "hint": "the run cannot be closed out on a file that is not the " |
| 134 | "winner. Restore optimization/nodes/<best_code_hash>.py " | 132 | "winner. Restore optimization/nodes/<best_code_hash>.py " |
| 135 | "into the kernel, then call stop again."}) | 133 | "into the kernel, then call stop again."}) |
| @@ -215,7 +213,7 @@ def cmd_report(a): | |||
| 215 | "duplicate_rejected": pr.get("duplicate_rejected", 0)}) | 213 | "duplicate_rejected": pr.get("duplicate_rejected", 0)}) |
| 216 | 214 | ||
| 217 | 215 | ||
| 218 | -def _delivered_hash(st): | 216 | +def delivered_hash(st): |
| 219 | """The program this run ships, for every step that follows `stop`. | 217 | """The program this run ships, for every step that follows `stop`. |
| 220 | 218 | ||
| 221 | `_deliver_best` freezes it in `progress.delivered_code_hash` as it puts it | 219 | `_deliver_best` freezes it in `progress.delivered_code_hash` as it puts it |
| @@ -227,7 +225,10 @@ def _delivered_hash(st): | |||
| 227 | return st["progress"].get("delivered_code_hash") or ratchet_best_hash(st) | 225 | return st["progress"].get("delivered_code_hash") or ratchet_best_hash(st) |
| 228 | 226 | ||
| 229 | 227 | ||
| 230 | -def _delivered_speedup(st, code_hash): | 228 | +_delivered_hash = delivered_hash |
| 229 | + | ||
| 230 | + | ||
| 231 | +def delivered_speedup(st, code_hash): | ||
| 231 | """The search's own claim ABOUT THE DELIVERED PROGRAM, on `J`'s instrument. | 232 | """The search's own claim ABOUT THE DELIVERED PROGRAM, on `J`'s instrument. |
| 232 | 233 | ||
| 233 | `progress.best_speedup_vs_preopt` tracks `best_node` for the same reason, | 234 | `progress.best_speedup_vs_preopt` tracks `best_node` for the same reason, |
| @@ -244,9 +245,12 @@ def _delivered_speedup(st, code_hash): | |||
| 244 | return pr.get("best_speedup_vs_preopt") | 245 | return pr.get("best_speedup_vs_preopt") |
| 245 | 246 | ||
| 246 | 247 | ||
| 247 | -def _open_verification(st): | 248 | +_delivered_speedup = delivered_speedup |
| 248 | - """Create the verification record at the first real stop. Idempotent: | 249 | + |
| 249 | - `stop` is sticky and may be called again.""" | 250 | + |
| 251 | +def open_verification(st, *, policy=None): | ||
| 252 | + """Create the verification record once, even when STOP is called again.""" | ||
| 253 | + policy = policy or _classic_verification_policy() | ||
| 250 | if "verification" in st: | 254 | if "verification" in st: |
| 251 | return | 255 | return |
| 252 | pre_hash = st["nodes"]["closed"][0]["code_hash"] | 256 | pre_hash = st["nodes"]["closed"][0]["code_hash"] |
| @@ -255,6 +259,10 @@ def _open_verification(st): | |||
| 255 | if not cfg.get("end_verify", DEFAULT_CONFIG["end_verify"]): | 259 | if not cfg.get("end_verify", DEFAULT_CONFIG["end_verify"]): |
| 256 | st["verification"] = {"status": "disabled"} | 260 | st["verification"] = {"status": "disabled"} |
| 257 | return | 261 | return |
| 262 | + queue = _front_to_verify(st, pre_hash, best_hash, policy=policy) | ||
| 263 | + point = "delivered" | ||
| 264 | + if best_hash == pre_hash and policy.strict_restore and queue: | ||
| 265 | + best_hash = point = queue.pop(0) | ||
| 258 | if best_hash == pre_hash: | 266 | if best_hash == pre_hash: |
| 259 | # Nothing was kept, so there is no claim to verify. | 267 | # Nothing was kept, so there is no claim to verify. |
| 260 | st["verification"] = {"status": "no_change", "preopt": pre_hash, | 268 | st["verification"] = {"status": "no_change", "preopt": pre_hash, |
| @@ -264,26 +272,25 @@ def _open_verification(st): | |||
| 264 | per_step = max(1, -(-runs // 2)) # each arm is measured twice | 272 | per_step = max(1, -(-runs // 2)) # each arm is measured twice |
| 265 | st["verification"] = { | 273 | st["verification"] = { |
| 266 | "status": "pending", | 274 | "status": "pending", |
| 267 | - "arms": {"preopt": {"code_hash": pre_hash, "samples": []}, | 275 | + "arms": {"preopt": _verification_arm(pre_hash, policy), |
| 268 | - "delivered": {"code_hash": best_hash, "samples": []}}, | 276 | + "delivered": _verification_arm(best_hash, policy)}, |
| 269 | "schedule": list(VERIFY_ORDER), "step": 0, | 277 | "schedule": list(VERIFY_ORDER), "step": 0, |
| 270 | - "runs_per_step": per_step, | 278 | + "warmup": policy.warmup, "runs_per_step": per_step, |
| 271 | - "protocol": f"warmup=1,runs={per_step},agg=median x{len(VERIFY_ORDER)} ABBA", | 279 | + "protocol": f"warmup={policy.warmup},runs={per_step},agg=median x{len(VERIFY_ORDER)} ABBA", |
[P2] ABBA 测量指令使用了错误的预热次数 问题描述 验证状态按前端策略记录 依据 在 建议 把预热次数作为结构化字段持久化,并用同一字段生成验证指令。旧状态缺少该字段时沿用 1 次预热。 ![]() ![]() | |||
| 272 | "search_speedup": _delivered_speedup(st, best_hash), | 280 | "search_speedup": _delivered_speedup(st, best_hash), |
| 273 | - "point": "delivered", | 281 | + "point": point, |
| 274 | } | 282 | } |
| 275 | - st["verify_queue"] = _front_to_verify(st, pre_hash, best_hash) | 283 | + st["verify_queue"] = queue |
| 276 | 284 | ||
| 277 | 285 | ||
| 278 | -def _front_to_verify(st, pre_hash, best_hash): | 286 | +_open_verification = open_verification |
| 287 | + | ||
| 288 | + | ||
| 289 | +def front_to_verify(st, pre_hash, best_hash, *, policy=None): | ||
| 279 | """The front points that still need an ABBA pass, in front order. | 290 | """The front points that still need an ABBA pass, in front order. |
| 280 | 291 | ||
| 281 | - The delivered point is the one already being verified, and the preopt is the | 292 | + The baseline serves as the reference arm. Queue the other points in archive |
| 282 | - other arm of every pass, so neither is queued. A point whose source was not | 293 | + order; strict backends retain missing snapshots for a later retry. |
| 283 | - retained cannot be verified -- `verify` stages the program from | ||
| 284 | - `nodes/<hash>.py` -- but it is dropped when the queue is CONSUMED | ||
| 285 | - (`_next_verification`), not here: a snapshot can arrive between the stop and | ||
| 286 | - the pass, and a queue filtered at the stop would have already forgotten it. | ||
| 287 | """ | 294 | """ |
| 288 | if not st["config"].get("verify_front", DEFAULT_CONFIG["verify_front"]): | 295 | if not st["config"].get("verify_front", DEFAULT_CONFIG["verify_front"]): |
| 289 | return [] | 296 | return [] |
| @@ -291,14 +298,18 @@ def _front_to_verify(st, pre_hash, best_hash): | |||
| 291 | if e["code_hash"] not in (pre_hash, best_hash)] | 298 | if e["code_hash"] not in (pre_hash, best_hash)] |
| 292 | 299 | ||
| 293 | 300 | ||
| 294 | -def _next_verification(st, op_dir): | 301 | +_front_to_verify = front_to_verify |
| 302 | + | ||
| 303 | + | ||
| 304 | +def next_verification(st, op_dir, *, policy=None): | ||
| 295 | """Retire the finished pass and open the next front point's, if any. | 305 | """Retire the finished pass and open the next front point's, if any. |
| 296 | 306 | ||
| 297 | Returns the code hash now being verified, or None when the front is done. | 307 | Returns the code hash now being verified, or None when the front is done. |
| 298 | """ | 308 | """ |
| 309 | + policy = policy or _classic_verification_policy() | ||
| 299 | v = st.get("verification") or {} | 310 | v = st.get("verification") or {} |
| 300 | queue = [h for h in (st.get("verify_queue") or []) | 311 | queue = [h for h in (st.get("verify_queue") or []) |
| 301 | - if os.path.exists(npath(op_dir, h))] | 312 | + if policy.strict_restore or os.path.exists(npath(op_dir, h))] |
| 302 | st["verify_queue"] = queue[1:] | 313 | st["verify_queue"] = queue[1:] |
| 303 | if not queue: | 314 | if not queue: |
| 304 | # The last pass stays in `verification`, where every summary reads it. | 315 | # The last pass stays in `verification`, where every summary reads it. |
| @@ -308,13 +319,13 @@ def _next_verification(st, op_dir): | |||
| 308 | point = next((e for e in (st.get("archive") or []) if e["code_hash"] == nxt), {}) | 319 | point = next((e for e in (st.get("archive") or []) if e["code_hash"] == nxt), {}) |
| 309 | st["verification"] = { | 320 | st["verification"] = { |
| 310 | "status": "pending", | 321 | "status": "pending", |
| 311 | - "arms": {"preopt": {"code_hash": v["arms"]["preopt"]["code_hash"], "samples": []}, | 322 | + "arms": {"preopt": _verification_arm(v["arms"]["preopt"]["code_hash"], policy), |
| 312 | # Keyed `delivered` because that is what the ABBA schedule and | 323 | # Keyed `delivered` because that is what the ABBA schedule and |
| 313 | # `_finish_verification` name the second arm; `point` says which | 324 | # `_finish_verification` name the second arm; `point` says which |
| 314 | # program it actually is. | 325 | # program it actually is. |
| 315 | - "delivered": {"code_hash": nxt, "samples": []}}, | 326 | + "delivered": _verification_arm(nxt, policy)}, |
| 316 | "schedule": list(VERIFY_ORDER), "step": 0, | 327 | "schedule": list(VERIFY_ORDER), "step": 0, |
| 317 | - "runs_per_step": v["runs_per_step"], "protocol": v["protocol"], | 328 | + "warmup": v.get("warmup", 1), "runs_per_step": v["runs_per_step"], "protocol": v["protocol"], |
| 318 | "point": nxt, | 329 | "point": nxt, |
| 319 | "objectives": point.get("values"), | 330 | "objectives": point.get("values"), |
| 320 | # The search's own claim about this point, on `J`'s instrument -- the | 331 | # The search's own claim about this point, on `J`'s instrument -- the |
| @@ -328,6 +339,9 @@ def _next_verification(st, op_dir): | |||
| 328 | return nxt | 339 | return nxt |
| 329 | 340 | ||
| 330 | 341 | ||
| 342 | +_next_verification = next_verification | ||
| 343 | + | ||
| 344 | + | ||
| 331 | def _verify_directive(st): | 345 | def _verify_directive(st): |
| 332 | v = st.get("verification") | 346 | v = st.get("verification") |
| 333 | if not v: | 347 | if not v: |
| @@ -349,7 +363,7 @@ def _verification_summary(st): | |||
| 349 | return {k: v[k] for k in keep if k in v} | 363 | return {k: v[k] for k in keep if k in v} |
| 350 | 364 | ||
| 351 | 365 | ||
| 352 | -def _verification_line(st): | 366 | +def verification_line(st): |
| 353 | v = st.get("verification") or {} | 367 | v = st.get("verification") or {} |
| 354 | status = v.get("status", "not_started") | 368 | status = v.get("status", "not_started") |
| 355 | r = v.get("result") | 369 | r = v.get("result") |
| @@ -365,27 +379,38 @@ def _verification_line(st): | |||
| 365 | return status | 379 | return status |
| 366 | 380 | ||
| 367 | 381 | ||
| 368 | -def _finish_verification(st, v): | 382 | +_verification_line = verification_line |
| 369 | - pre = v["arms"]["preopt"]["samples"] | 383 | + |
| 370 | - dele = v["arms"]["delivered"]["samples"] | 384 | + |
| 371 | - ci = bootstrap_speedup(pre, dele) | 385 | +def _finish_verification(st, v, *, policy=None): |
| 386 | + policy = policy or _classic_verification_policy() | ||
| 387 | + pre = policy.readings(v["arms"]["preopt"]) | ||
| 388 | + dele = policy.readings(v["arms"]["delivered"]) | ||
| 389 | + ci = policy.interval(pre, dele) | ||
| 372 | if ci is None: | 390 | if ci is None: |
| 373 | v["status"] = "insufficient" | 391 | v["status"] = "insufficient" |
| 374 | return | 392 | return |
| 375 | ci.update(n_preopt=len(pre), n_delivered=len(dele), | 393 | ci.update(n_preopt=len(pre), n_delivered=len(dele), |
| 376 | preopt_us=median_of(pre), delivered_us=median_of(dele)) | 394 | preopt_us=median_of(pre), delivered_us=median_of(dele)) |
| 395 | + if policy.acquisition_reads: | ||
| 396 | + ci.update(n_launches_preopt=len(v["arms"]["preopt"].get("samples") or []), | ||
| 397 | + n_launches_delivered=len(v["arms"]["delivered"].get("samples") or [])) | ||
| 377 | v["result"] = ci | 398 | v["result"] = ci |
| 378 | v["status"] = ci_verdict(ci) | 399 | v["status"] = ci_verdict(ci) |
| 379 | 400 | ||
| 380 | 401 | ||
| 381 | -def _verify_short_circuit(a, st, op_f): | 402 | +def verify_short_circuit(a, st, op_f, *, policy=None): |
| 382 | """True when this `verify` call is answered without new readings.""" | 403 | """True when this `verify` call is answered without new readings.""" |
| 404 | + policy = policy or _classic_verification_policy() | ||
| 383 | v = st["verification"] | 405 | v = st["verification"] |
| 406 | + if policy.strict_restore and (getattr(a, "skip", "") or v["status"] != "pending"): | ||
| 407 | + restore_verification_program(a, op_f, "delivered", _delivered_hash(st), policy=policy) | ||
| 384 | if getattr(a, "skip", ""): | 408 | if getattr(a, "skip", ""): |
| 385 | if v["status"] == "pending": | 409 | if v["status"] == "pending": |
| 386 | v["status"] = "skipped" | 410 | v["status"] = "skipped" |
| 387 | v["skip_reason"] = a.skip | 411 | v["skip_reason"] = a.skip |
| 388 | - restore(a.op_dir, op_f, _delivered_hash(st)) | 412 | + if not policy.strict_restore: |
| 413 | + restore(a.op_dir, op_f, _delivered_hash(st)) | ||
| 389 | save(a.op_dir, st) | 414 | save(a.op_dir, st) |
| 390 | out({"verified": False, **_verification_summary(st)}) | 415 | out({"verified": False, **_verification_summary(st)}) |
| 391 | return True | 416 | return True |
| @@ -396,24 +421,34 @@ def _verify_short_circuit(a, st, op_f): | |||
| 396 | return False | 421 | return False |
| 397 | 422 | ||
| 398 | 423 | ||
| 399 | -def _verify_stage_arm(a, v, op_f, arm, want): | 424 | +_verify_short_circuit = verify_short_circuit |
| 425 | + | ||
| 426 | + | ||
| 427 | +def _verify_stage_arm(a, v, op_f, arm, want, policy): | ||
| 400 | """Put one arm's program in the working file and say how to measure it.""" | 428 | """Put one arm's program in the working file and say how to measure it.""" |
| 429 | + warmup = v.get("warmup", 1) | ||
| 430 | + if policy.strict_restore: | ||
| 431 | + restore_verification_program(a, op_f, arm, want, policy=policy) | ||
| 432 | + out({"stage": v["step"], "arm": arm, "code_hash": want, "op_file": op_f, | ||
| 433 | + "warmup": warmup, "runs": v["runs_per_step"]}) | ||
| 434 | + return | ||
| 401 | if not (restore(a.op_dir, op_f, want) or file_hash(op_f) == want): | 435 | if not (restore(a.op_dir, op_f, want) or file_hash(op_f) == want): |
| 402 | out({"verified": False, "error": "restore_failed", "arm": arm, | 436 | out({"verified": False, "error": "restore_failed", "arm": arm, |
| 403 | "code_hash": want}) | 437 | "code_hash": want}) |
| 404 | raise Refusal(2) | 438 | raise Refusal(2) |
| 405 | out({"stage": v["step"], "arm": arm, "code_hash": want, "op_file": op_f, | 439 | out({"stage": v["step"], "arm": arm, "code_hash": want, "op_file": op_f, |
| 406 | - "runs": v["runs_per_step"], | 440 | + "warmup": warmup, "runs": v["runs_per_step"], |
| 407 | - "measure": f"measure_latency --op-file {op_f} --warmup 1 " | 441 | + "measure": f"measure_latency --op-file {op_f} --warmup {warmup} " |
| 408 | f"--runs {v['runs_per_step']} --agg median", | 442 | f"--runs {v['runs_per_step']} --agg median", |
| 409 | "then": "HARNESS verify --op-dir <op_dir> --samples <samples>"}) | 443 | "then": "HARNESS verify --op-dir <op_dir> --samples <samples>"}) |
| 410 | 444 | ||
| 411 | 445 | ||
| 412 | -def _verify_readings(a, op_f, arm, want): | 446 | +def _verify_readings(a, op_f, arm, want, *, policy=None): |
| 413 | """This step's readings, once they are known to be the staged program's.""" | 447 | """This step's readings, once they are known to be the staged program's.""" |
| 448 | + policy = policy or _classic_verification_policy() | ||
| 414 | # The readings must belong to the program this step staged. Anything else | 449 | # The readings must belong to the program this step staged. Anything else |
| 415 | # would silently verify a kernel nobody is shipping. | 450 | # would silently verify a kernel nobody is shipping. |
| 416 | - if file_hash(op_f) != want: | 451 | + if not policy.matches(a.op_dir, op_f, want): |
| 417 | out({"verified": False, "error": "wrong_program", "arm": arm, | 452 | out({"verified": False, "error": "wrong_program", "arm": arm, |
| 418 | "expected": want, "on_disk": file_hash(op_f), | 453 | "expected": want, "on_disk": file_hash(op_f), |
| 419 | "hint": "call `verify` without --samples first; it stages the arm"}) | 454 | "hint": "call `verify` without --samples first; it stages the arm"}) |
| @@ -425,39 +460,45 @@ def _verify_readings(a, op_f, arm, want): | |||
| 425 | return samples | 460 | return samples |
| 426 | 461 | ||
| 427 | 462 | ||
| 428 | -def cmd_verify(a): | 463 | +def cmd_verify(a, *, policy=None): |
| 429 | - """Re-measure the delivered kernel against the preopt, after `stop`. | 464 | + """Advance post-stop verification without changing the search budget.""" |
| 430 | - | 465 | + policy = policy or _classic_verification_policy() |
| 431 | - Without --samples: stage the next arm into the working file and say which. | ||
| 432 | - With --samples: record that arm's readings, then put the delivered kernel | ||
| 433 | - back, so the deliverable is intact between calls. | ||
| 434 | - """ | ||
| 435 | st = load(a.op_dir) | 466 | st = load(a.op_dir) |
| 436 | v = st.get("verification") | 467 | v = st.get("verification") |
| 437 | if not st["progress"].get("stop_reason") or not v: | 468 | if not st["progress"].get("stop_reason") or not v: |
| 438 | out({"verified": False, "error": "no_stop", | 469 | out({"verified": False, "error": "no_stop", |
| 439 | - "note": "verification runs after `stop`, on the programs it hands over"}) | 470 | + "note": "verification runs after `stop`, on the programs it hands over"}) |
| 440 | raise Refusal(2) | 471 | raise Refusal(2) |
| 441 | op_f = op_file_path(st, a.op_dir) | 472 | op_f = op_file_path(st, a.op_dir) |
| 442 | - if _verify_short_circuit(a, st, op_f): | 473 | + if _verify_short_circuit(a, st, op_f, policy=policy): |
| 443 | return | 474 | return |
| 444 | arm = v["schedule"][v["step"]] | 475 | arm = v["schedule"][v["step"]] |
| 445 | want = v["arms"][arm]["code_hash"] | 476 | want = v["arms"][arm]["code_hash"] |
| 446 | if a.samples is None: | 477 | if a.samples is None: |
| 447 | - _verify_stage_arm(a, v, op_f, arm, want) | 478 | + _verify_stage_arm(a, v, op_f, arm, want, policy) |
| 448 | return | 479 | return |
| 449 | - samples = _verify_readings(a, op_f, arm, want) | 480 | + samples = _verify_readings(a, op_f, arm, want, policy=policy) |
| 450 | v["arms"][arm]["samples"].extend(samples) | 481 | v["arms"][arm]["samples"].extend(samples) |
| 482 | + if policy.acquisition_reads: | ||
| 483 | + v["arms"][arm].setdefault("reads", []).append(median_of(samples)) | ||
| 484 | + if getattr(a, "receipt", None): | ||
| 485 | + v.setdefault("receipts", []).append(a.receipt) | ||
| 451 | v["step"] += 1 | 486 | v["step"] += 1 |
| 487 | + if policy.strict_restore: | ||
| 488 | + restore_verification_program(a, op_f, "delivered", _delivered_hash(st), policy=policy) | ||
| 452 | nxt = None | 489 | nxt = None |
| 453 | if v["step"] >= len(v["schedule"]): | 490 | if v["step"] >= len(v["schedule"]): |
| 454 | - _finish_verification(st, v) | 491 | + _finish_verification(st, v, policy=policy) |
| 455 | line = _verification_line(st) | 492 | line = _verification_line(st) |
| 456 | - append_log(a.op_dir, st["op"], | 493 | + label = str(v.get("point")) |
| 457 | - f"- verification[{str(v.get('point'))[:8]}]: {line}") | 494 | + if policy.acquisition_reads: |
| 495 | + label = ((v.get("arms") or {}).get("delivered", {}).get("code_hash") | ||
| 496 | + or str(v.get("point") or "?")) | ||
| 497 | + append_log(a.op_dir, st["op"], f"- verification[{label[:8]}]: {line}") | ||
| 458 | # The front is the deliverable, so every point on it gets its own pass. | 498 | # The front is the deliverable, so every point on it gets its own pass. |
| 459 | - nxt = _next_verification(st, a.op_dir) | 499 | + nxt = _next_verification(st, a.op_dir, policy=policy) |
| 460 | - restore(a.op_dir, op_f, _delivered_hash(st)) | 500 | + if not policy.strict_restore: |
| 501 | + restore(a.op_dir, op_f, _delivered_hash(st)) | ||
| 461 | save(a.op_dir, st) | 502 | save(a.op_dir, st) |
| 462 | summary = _verification_summary(st) | 503 | summary = _verification_summary(st) |
| 463 | if nxt: | 504 | if nxt: |
| @@ -487,7 +528,7 @@ def _frontier_dir(op_dir): | |||
| 487 | return os.path.join(sdir(op_dir), "frontier") | 528 | return os.path.join(sdir(op_dir), "frontier") |
| 488 | 529 | ||
| 489 | 530 | ||
| 490 | -def _verdicts_by_point(st): | 531 | +def verdicts_by_point(st): |
| 491 | """code_hash -> what its ABBA pass concluded, for every pass this run ran.""" | 532 | """code_hash -> what its ABBA pass concluded, for every pass this run ran.""" |
| 492 | out_v = {} | 533 | out_v = {} |
| 493 | for v in list(st.get("verifications") or []) + [st.get("verification") or {}]: | 534 | for v in list(st.get("verifications") or []) + [st.get("verification") or {}]: |
| @@ -501,6 +542,24 @@ def _verdicts_by_point(st): | |||
| 501 | return out_v | 542 | return out_v |
| 502 | 543 | ||
| 503 | 544 | ||
| 545 | +_verdicts_by_point = verdicts_by_point | ||
| 546 | + | ||
| 547 | + | ||
| 548 | +def _export_source(src, dst): | ||
| 549 | + from .backend import current | ||
| 550 | + if not os.path.exists(src): | ||
| 551 | + return False | ||
| 552 | + try: | ||
| 553 | + backend = current() | ||
| 554 | + if backend is None: | ||
| 555 | + shutil.copyfile(src, dst) | ||
| 556 | + else: | ||
| 557 | + backend.export_source(src, dst) | ||
| 558 | + except OSError: | ||
| 559 | + return False | ||
| 560 | + return True | ||
| 561 | + | ||
| 562 | + | ||
| 504 | def export_frontier(st, op_dir): | 563 | def export_frontier(st, op_dir): |
| 505 | """ | 564 | """ |
| 506 | Write the archive to `optimization/frontier/`: one source per point, and | 565 | Write the archive to `optimization/frontier/`: one source per point, and |
| @@ -516,7 +575,7 @@ def export_frontier(st, op_dir): | |||
| 516 | os.makedirs(_frontier_dir(op_dir), exist_ok=True) | 575 | os.makedirs(_frontier_dir(op_dir), exist_ok=True) |
| 517 | # What `impl.py` holds, which is `delivery_point` -- `is_impl` has to mark | 576 | # What `impl.py` holds, which is `delivery_point` -- `is_impl` has to mark |
| 518 | # the row the file actually carries, not the row `best_node` names. | 577 | # the row the file actually carries, not the row `best_node` names. |
| 519 | - best = delivery_point(st, op_dir)[0] or ratchet_best_hash(st) | 578 | + best = delivery_point(st, op_dir)[0] |
| 520 | objs = objectives_of(st) | 579 | objs = objectives_of(st) |
| 521 | verdicts = _verdicts_by_point(st) | 580 | verdicts = _verdicts_by_point(st) |
| 522 | for i, e in enumerate(points): | 581 | for i, e in enumerate(points): |
| @@ -527,12 +586,7 @@ def export_frontier(st, op_dir): | |||
| 527 | if e.get("workspace_b") is not None else "") | 586 | if e.get("workspace_b") is not None else "") |
| 528 | name = f"{i:02d}{ws_tag}_{e['code_hash'][:8]}.py" | 587 | name = f"{i:02d}{ws_tag}_{e['code_hash'][:8]}.py" |
| 529 | dst = os.path.join(_frontier_dir(op_dir), name) | 588 | dst = os.path.join(_frontier_dir(op_dir), name) |
| 530 | - have = os.path.exists(src) | 589 | + have = _export_source(src, dst) |
| 531 | - if have: | ||
| 532 | - try: | ||
| 533 | - shutil.copyfile(src, dst) | ||
| 534 | - except OSError: | ||
| 535 | - have = False | ||
| 536 | if not have: | 590 | if not have: |
| 537 | missing += 1 | 591 | missing += 1 |
| 538 | rows.append({"rank": i, "code_hash": e["code_hash"], | 592 | rows.append({"rank": i, "code_hash": e["code_hash"], |
| @@ -813,3 +867,44 @@ def cmd_pareto(a): | |||
| 813 | except OSError: | 867 | except OSError: |
| 814 | out_obj["written"] = None | 868 | out_obj["written"] = None |
| 815 | out(out_obj) | 869 | out(out_obj) |
| 870 | + | ||
| 871 | + | ||
| 872 | +def restore_verification_program(a, op_f, arm, want, *, policy): | ||
| 873 | + """Restore a delivery artifact; strict backends verify the complete bundle.""" | ||
| 874 | + if not policy.strict_restore: | ||
| 875 | + restore(a.op_dir, op_f, want) | ||
| 876 | + return | ||
| 877 | + if not policy.matches(a.op_dir, op_f, want): | ||
| 878 | + restore(a.op_dir, op_f, want) | ||
| 879 | + if not policy.matches(a.op_dir, op_f, want): | ||
| 880 | + out({"verified": False, "error": "restore_failed", "arm": arm, | ||
| 881 | + "code_hash": want}) | ||
| 882 | + raise Refusal(2) | ||
| 883 | + | ||
| 884 | + | ||
| 885 | +@dataclass(frozen=True) | ||
| 886 | +class VerificationPolicy: | ||
| 887 | + """Keep each frontend's acquisition, artifact and persistence contracts.""" | ||
| 888 | + warmup: int | ||
| 889 | + readings: object | ||
| 890 | + interval: object | ||
| 891 | + matches: object | ||
| 892 | + strict_restore: bool = False | ||
| 893 | + acquisition_reads: bool = False | ||
| 894 | + | ||
| 895 | + | ||
| 896 | +def _classic_verification_policy(): | ||
| 897 | + from .backend import current | ||
| 898 | + if current() is not None: | ||
| 899 | + return current().verification_policy() | ||
| 900 | + return VerificationPolicy( | ||
| 901 | + warmup=1, readings=lambda arm: arm["samples"], interval=bootstrap_speedup, | ||
| 902 | + matches=lambda op_dir, op_f, want: file_hash(op_f) == want, | ||
| 903 | + ) | ||
| 904 | + | ||
| 905 | + | ||
| 906 | +def _verification_arm(code_hash, policy): | ||
| 907 | + arm = {"code_hash": code_hash, "samples": []} | ||
| 908 | + if policy.acquisition_reads: | ||
| 909 | + arm["reads"] = [] | ||
| 910 | + return arm | ||
| @@ -23,7 +23,8 @@ import mo_hv | |||
| 23 | 23 | ||
| 24 | from .config import (DEFAULT_CONFIG, FrontContext, J_OBJECTIVE, OBJECTIVE_ALIASES, Refusal, VERIFY_ALPHA, VERIFY_BOOT, | 24 | from .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, live_frontier, npath, open_node, preopt_code_hash | 26 | +from .state import (_base_hash, _wrapper_drift, file_hash, live_frontier, npath, op_file_path, |
| 27 | + open_node, preopt_code_hash) | ||
| 27 | from .measurement import (bootstrap_speedup, compute_j, is_bytes, median_of, objective_values, objectives_of, | 28 | from .measurement import (bootstrap_speedup, compute_j, is_bytes, median_of, objective_values, objectives_of, |
| 28 | preopt_values) | 29 | preopt_values) |
| 29 | 30 | ||
| @@ -239,46 +240,34 @@ def _refresh_front_point(point, entry, objs, st): | |||
| 239 | def delivery_point(st, op_dir): | 240 | def delivery_point(st, op_dir): |
| 240 | """(code_hash, detail): the program `stop` leaves in the working file. | 241 | """(code_hash, detail): the program `stop` leaves in the working file. |
| 241 | 242 | ||
| 242 | - The best PRIMARY objective among every correct measurement whose source is | 243 | + Rank correct measurements with complete objective vectors and a source |
| 243 | - on disk, ties broken by the remaining objectives in order and then by the | 244 | + that passes the campaign's frozen-wrapper check. A valid measurement |
| 244 | - hash. `impl.py` is still "the fastest point" -- what changes is that it is | 245 | + can outlive its Pareto archive row after a remeasurement, so start from |
| 245 | - now read off the measurements instead of off `best_node`. | 246 | + the evaluation cache. A retained block snapshot alone is audit evidence. |
| 246 | - | ||
| 247 | - Not `best_node`: it is `J`, and it only moves at an action's `close`. A run | ||
| 248 | - can deliver a program another point beats -- slower, at a workspace many | ||
| 249 | - times larger -- because the deliverable was chosen by a scalar that had | ||
| 250 | - stopped tracking the measurements. | ||
| 251 | - | ||
| 252 | - Not the archive either: the bootstrap lets a 0.3% slower point with a better | ||
| 253 | - secondary objective dominate the fastest one, so the fastest program can | ||
| 254 | - leave the front (see `dominates_measured`). It never leaves `eval_cache`, | ||
| 255 | - which is why the candidates come from there. | ||
| 256 | - | ||
| 257 | - Nothing here needs a non-domination filter: a point that is strictly best | ||
| 258 | - on the primary objective cannot be dominated, and when several tie on it | ||
| 259 | - the remaining objectives order them -- which is exactly the tied case. | ||
| 260 | - | ||
| 261 | - (None, detail) when no measurement can be delivered; the caller falls back | ||
| 262 | - to `best_node`. | ||
| 263 | """ | 247 | """ |
| 264 | objs = objectives_of(st) | 248 | objs = objectives_of(st) |
| 249 | + cache = st.get("eval_cache") or {} | ||
| 250 | + best = next((n for n in st.get("nodes", {}).get("closed", []) if n.get("id") == st.get("best_node")), {}) | ||
| 251 | + best_hash = best.get("code_hash") | ||
| 252 | + if best_hash and best_hash not in cache and best.get("eval"): | ||
| 253 | + cache = {**cache, best_hash: best["eval"]} | ||
| 265 | rank = [] | 254 | rank = [] |
| 266 | - for h, e in (st.get("eval_cache") or {}).items(): | 255 | + for h, e in cache.items(): |
| 267 | if not e.get("s") or not e.get("p"): | 256 | if not e.get("s") or not e.get("p"): |
| 268 | continue | 257 | continue |
| 269 | - if not os.path.exists(npath(op_dir, h)): | 258 | + vals, missing = objective_values(objs, e["p"], e.get("m")) |
| 259 | + if missing or not all(math.isfinite(v) for v in vals.values()): | ||
| 270 | continue | 260 | continue |
| 271 | - vals, _ = objective_values(objs, e["p"], e.get("m")) | 261 | + path = npath(op_dir, h) |
| 272 | - if vals.get(objs[0]["name"]) is None: | 262 | + if not os.path.isfile(path): |
| 263 | + # STOP can keep an already-restored best if its snapshot was lost. | ||
| 264 | + path = op_file_path(st, op_dir) | ||
| 265 | + if h != best_hash or file_hash(path) != h: | ||
| 266 | + continue | ||
| 267 | + if _wrapper_drift(st, path): | ||
| 273 | continue | 268 | continue |
| 274 | - key = [] | 269 | + key = tuple(-vals[o["name"]] if o["direction"] == "max" else vals[o["name"]] for o in objs) |
| 275 | - for o in objs: | 270 | + rank.append((key, h, vals)) |
| 276 | - v = vals.get(o["name"]) | ||
| 277 | - # Missing secondary objectives sort last, so a tie on the primary | ||
| 278 | - # goes to the point whose trade-off is actually known. | ||
| 279 | - key.append(float("inf") if v is None | ||
| 280 | - else (-float(v) if o["direction"] == "max" else float(v))) | ||
| 281 | - rank.append((tuple(key), h, vals)) | ||
| 282 | if not rank: | 271 | if not rank: |
| 283 | return None, {"why": "no_deliverable_measurement"} | 272 | return None, {"why": "no_deliverable_measurement"} |
| 284 | rank.sort(key=lambda t: (t[0], t[1])) | 273 | rank.sort(key=lambda t: (t[0], t[1])) |
| @@ -594,7 +583,10 @@ def measured_order(xs, ys, alpha=None): | |||
| 594 | interval to compute and the answer is undetermined rather than assumed. | 583 | interval to compute and the answer is undetermined rather than assumed. |
| 595 | """ | 584 | """ |
| 596 | alpha = VERIFY_ALPHA if alpha is None else alpha | 585 | alpha = VERIFY_ALPHA if alpha is None else alpha |
| 597 | - ci = bootstrap_speedup(xs, ys, alpha=alpha) | 586 | + from .backend import current |
| 587 | + backend = current() | ||
| 588 | + interval = backend.reading_interval if backend is not None else bootstrap_speedup | ||
| 589 | + ci = interval(xs, ys, alpha=alpha) | ||
| 598 | if ci is None: | 590 | if ci is None: |
| 599 | return "undetermined", None | 591 | return "undetermined", None |
| 600 | if ci["ci_high"] < 1.0: | 592 | if ci["ci_high"] < 1.0: |
| @@ -613,6 +605,9 @@ def row_samples(o, row): | |||
| 613 | `samples_from: "samples"` (that list has always been `p`'s). An objective | 605 | `samples_from: "samples"` (that list has always been `p`'s). An objective |
| 614 | that declares no sample source has none here, and is compared as a number. | 606 | that declares no sample source has none here, and is compared as a number. |
| 615 | """ | 607 | """ |
| 608 | + from .backend import current | ||
| 609 | + if current() is not None and o.get('samples_from') == 'samples': | ||
| 610 | + return current().entry_reads(row) | ||
[P1] 建议核对重测后 Pareto 比较使用的读数 在主机用例中,基线原为 100 µs,三份独立的 10 µs 重测收据均通过校验。显示的基线耗时已更新为 10 µs,但前沿行的 建议看看重测后,前沿比较读取的采集历史是否也随显示值一起更新。回归时可以同时观察耗时和最终保留的候选,这两个结果应当能相互解释。 ![]() ![]() | |||
| 616 | by = (row.get("samples_by_objective") or {}).get(o["name"]) | 611 | by = (row.get("samples_by_objective") or {}).get(o["name"]) |
| 617 | if by: | 612 | if by: |
| 618 | return list(by) | 613 | return list(by) |
| @@ -787,7 +782,7 @@ def archive_point(st, code_hash, p, m, action=None): | |||
| 787 | # wrote (or, for the preopt, the one `init` wrote). | 782 | # wrote (or, for the preopt, the one `init` wrote). |
| 788 | entry = (st.get("eval_cache") or {}).get(code_hash) or {} | 783 | entry = (st.get("eval_cache") or {}).get(code_hash) or {} |
| 789 | samples = entry.get("samples") | 784 | samples = entry.get("samples") |
| 790 | - return {"code_hash": code_hash, "values": vals, | 785 | + point = {"code_hash": code_hash, "values": vals, |
| 791 | "samples": list(samples or []), | 786 | "samples": list(samples or []), |
| 792 | # Per objective, so dominance is judged on the readings that | 787 | # Per objective, so dominance is judged on the readings that |
| 793 | # belong to the axis being compared rather than on `p`'s for all | 788 | # belong to the axis being compared rather than on `p`'s for all |
| @@ -804,6 +799,11 @@ def archive_point(st, code_hash, p, m, action=None): | |||
| 804 | "action": action, "catalog_id": (node or {}).get("catalog_id"), | 799 | "action": action, "catalog_id": (node or {}).get("catalog_id"), |
| 805 | "eval_no": st["progress"]["evals_used"]} | 800 | "eval_no": st["progress"]["evals_used"]} |
| 806 | 801 | ||
| 802 | + from .backend import current | ||
| 803 | + if current() is not None: | ||
| 804 | + point["reads"] = current().entry_reads(entry) | ||
| 805 | + return point | ||
| 806 | + | ||
| 807 | 807 | ||
| 808 | def _hv_vectors(objs, rows, draw=None): | 808 | def _hv_vectors(objs, rows, draw=None): |
| 809 | """Archive rows as vectors on the hypervolume's axes. | 809 | """Archive rows as vectors on the hypervolume's axes. |
| @@ -23,8 +23,8 @@ import evaluation_session | |||
| 23 | from .config import (DEFAULT_CONFIG, OPTUNA_MIN_VERSION, Refusal, SEARCH_PROTOCOL, SEED_V, SKILL_ROOT, _diag_log, | 23 | from .config import (DEFAULT_CONFIG, OPTUNA_MIN_VERSION, Refusal, SEARCH_PROTOCOL, SEED_V, SKILL_ROOT, _diag_log, |
| 24 | bayesian, bayesian_capability, out, predicates) | 24 | bayesian, bayesian_capability, out, predicates) |
| 25 | from .state import (_apply_chip_memory, _code_version, _domain_state, _pypto_defaults, _resolve_envelope, | 25 | from .state import (_apply_chip_memory, _code_version, _domain_state, _pypto_defaults, _resolve_envelope, |
| 26 | - confirm_chip, debug_options_signature, file_hash, next_id, npath, op_file_path, read_text, save, | 26 | + confirm_chip, debug_options_signature, file_hash, next_id, npath, occupancy_options, op_file_path, |
| 27 | - snapshot, wrapper_signature) | 27 | + read_text, save, snapshot, wrapper_signature) |
| 28 | from .measurement import (_preopt_metrics, cli_pipes, cli_samples, compute_j, derive_eval_timeout, objective_values, | 28 | from .measurement import (_preopt_metrics, cli_pipes, cli_samples, compute_j, derive_eval_timeout, objective_values, |
| 29 | objectives_of, observe_noise, parse_objectives) | 29 | objectives_of, observe_noise, parse_objectives) |
| 30 | from .front import _hv_reference_report, archive_record, refuse_no_hv_reference | 30 | from .front import _hv_reference_report, archive_record, refuse_no_hv_reference |
| @@ -315,25 +315,29 @@ def _init_state(a, cfg, opening): | |||
| 315 | } | 315 | } |
| 316 | st["nodes"]["held"] = [] | 316 | st["nodes"]["held"] = [] |
| 317 | _init_noise(st, a, opening, preopt_m) | 317 | _init_noise(st, a, opening, preopt_m) |
| 318 | + from .backend import current | ||
| 319 | + if current() is not None: | ||
| 320 | + st.update(current().state_metadata(a)) | ||
| 318 | return st | 321 | return st |
| 319 | 322 | ||
| 320 | 323 | ||
| 321 | def _seed_frontier(st, a, cfg, seeds): | 324 | def _seed_frontier(st, a, cfg, seeds): |
| 322 | """Seed the frontier from the action catalog. Returns the predicate reading.""" | 325 | """Seed the frontier from the action catalog. Returns the predicate reading.""" |
| 323 | - preds = (predicates.compute(a.op_file or "", a.op_dir) | 326 | + preds = (predicates.compute(a.op_file or "", a.op_dir, **occupancy_options(st)) |
| 324 | if (predicates and cfg.get("action_preconditions", True)) else None) | 327 | if (predicates and cfg.get("action_preconditions", True)) else None) |
| 325 | st["predicates"] = preds | 328 | st["predicates"] = preds |
| 326 | learn = cfg.get("prior_gain_source", DEFAULT_CONFIG["prior_gain_source"]) == "learned" | 329 | learn = cfg.get("prior_gain_source", DEFAULT_CONFIG["prior_gain_source"]) == "learned" |
| 327 | _snapshot_prior_table(st, a.op_dir) | 330 | _snapshot_prior_table(st, a.op_dir) |
| 328 | table = action_posterior.load_table(_prior_table_path(st)) if learn else None | 331 | table = action_posterior.load_table(_prior_table_path(st)) if learn else None |
| 329 | st["prior_gain_source"] = ("learned" if table else "catalog") | 332 | st["prior_gain_source"] = ("learned" if table else "catalog") |
| 333 | + from .backend import current as current_backend | ||
| 330 | for sd in seeds: | 334 | for sd in seeds: |
| 331 | if sd.get("conversion") and not cfg.get("conversion_actions", True): | 335 | if sd.get("conversion") and not cfg.get("conversion_actions", True): |
| 332 | continue | 336 | continue |
| 333 | node = { | 337 | node = { |
| 334 | "id": next_id(st, "u"), "parent": "root", "stage": sd["stage"], | 338 | "id": next_id(st, "u"), "parent": "root", "stage": sd["stage"], |
| 335 | "catalog_id": sd.get("id"), # keep the F-x/S-x/I-x id for symptom matching | 339 | "catalog_id": sd.get("id"), # keep the F-x/S-x/I-x id for symptom matching |
| 336 | - "delta": sd["delta"], "V": float(sd.get("prior_gain", 0.5)), | 340 | + "delta": sd["delta"], "V": (0.5 if current_backend() is not None else float(sd.get("prior_gain", 0.5))), |
| 337 | "prior_gain": float(sd.get("prior_gain", 0.5)), "tried": 0, | 341 | "prior_gain": float(sd.get("prior_gain", 0.5)), "tried": 0, |
| 338 | "requires": sd.get("requires", []), | 342 | "requires": sd.get("requires", []), |
| 339 | "prior_gain_catalog": float(sd.get("prior_gain", 0.5)), | 343 | "prior_gain_catalog": float(sd.get("prior_gain", 0.5)), |
| @@ -498,6 +502,9 @@ def cmd_init(a): | |||
| 498 | op_file_path(st, a.op_dir), | 502 | op_file_path(st, a.op_dir), |
| 499 | cli_pipes(a, "preopt_")) # first-move symptom bias | 503 | cli_pipes(a, "preopt_")) # first-move symptom bias |
| 500 | _init_snapshot(a, op_file, opening["preopt_hash"]) | 504 | _init_snapshot(a, op_file, opening["preopt_hash"]) |
| 505 | + from .backend import current | ||
| 506 | + if current() is not None: | ||
| 507 | + current().verify_initialization(a, st) | ||
| 501 | save(a.op_dir, st) | 508 | save(a.op_dir, st) |
| 502 | evaluation_session.clear_terminal_marker(a.op_dir) | 509 | evaluation_session.clear_terminal_marker(a.op_dir) |
| 503 | _init_baseline_log(a, opening, objs, pre_vals) | 510 | _init_baseline_log(a, opening, objs, pre_vals) |
| @@ -628,6 +635,10 @@ def _init_p_ref(a, cfg, user_cfg): | |||
| 628 | """ | 635 | """ |
| 629 | if a.p_ref is not None: | 636 | if a.p_ref is not None: |
| 630 | return "explicit:cli" | 637 | return "explicit:cli" |
| 638 | + from .backend import current | ||
| 639 | + if current() is not None: | ||
| 640 | + a.p_ref, provenance = current().default_reference | ||
| 641 | + return provenance | ||
| 631 | a.p_ref = float(a.preopt_p) | 642 | a.p_ref = float(a.preopt_p) |
| 632 | if "success_stop" not in user_cfg: | 643 | if "success_stop" not in user_cfg: |
| 633 | cfg["success_stop"] = False | 644 | cfg["success_stop"] = False |
| @@ -20,6 +20,7 @@ import time | |||
| 20 | import action_posterior | 20 | import action_posterior |
| 21 | import evaluation_session | 21 | import evaluation_session |
| 22 | 22 | ||
| 23 | +from .backend import current | ||
| 23 | from .config import (CATALOG_PRIOR_DEFAULT, CandidateRow, MeasurementVerdict, RatchetMeasurement, Refusal, | 24 | from .config import (CATALOG_PRIOR_DEFAULT, CandidateRow, MeasurementVerdict, RatchetMeasurement, Refusal, |
| 24 | 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, |
| 25 | feasibility, out) | 26 | feasibility, out) |
| @@ -96,10 +97,13 @@ def _restore_or_refuse(a, restore_hash, op_f): | |||
| 96 | 97 | ||
| 97 | def cmd_select(a): | 98 | def cmd_select(a): |
| 98 | st = load(a.op_dir) | 99 | st = load(a.op_dir) |
| 99 | - _refuse_if_action_open(st) | 100 | + refinement = (st["progress"].get("refine") or {}) if getattr(a, "dispatch_id", None) else {} |
| 101 | + if not refinement.get("action"): | ||
| 102 | + _refuse_if_action_open(st) | ||
| 100 | active = st["progress"]["active_stage"] | 103 | active = st["progress"]["active_stage"] |
| 101 | staged = st["config"]["staged_prior"] | 104 | staged = st["config"]["staged_prior"] |
| 102 | - frontier = live_frontier(st, a.op_dir) | 105 | + frontier = ([node for node in st["nodes"]["open"] if node["id"] == refinement["action"]] |
| 106 | + if refinement.get("action") else live_frontier(st, a.op_dir)) | ||
| 103 | if not frontier: | 107 | if not frontier: |
| 104 | _out_expansion_required(st, a) | 108 | _out_expansion_required(st, a) |
| 105 | return | 109 | return |
| @@ -110,7 +114,8 @@ def cmd_select(a): | |||
| 110 | # not left to the agent). restore_code_hash is still returned for visibility/logging. | 114 | # not left to the agent). restore_code_hash is still returned for visibility/logging. |
| 111 | # Phase 1: the global best (greedy accumulation). Phase 2: the front point | 115 | # Phase 1: the global best (greedy accumulation). Phase 2: the front point |
| 112 | # being extended -- `_base_hash` is the only thing that differs. | 116 | # being extended -- `_base_hash` is the only thing that differs. |
| 113 | - restore_hash = _base_hash(st, a.op_dir) | 117 | + base = refinement.get("base") or refinement.get("best") or {} |
| 118 | + restore_hash = base.get("code_hash") or _base_hash(st, a.op_dir) | ||
| 114 | op_f = op_file_path(st, a.op_dir) | 119 | op_f = op_file_path(st, a.op_dir) |
| 115 | restored = _restore_or_refuse(a, restore_hash, op_f) | 120 | restored = _restore_or_refuse(a, restore_hash, op_f) |
| 116 | # `already_measured` is the whole point: the file the coder is about to edit IS | 121 | # `already_measured` is the whole point: the file the coder is about to edit IS |
| @@ -150,6 +155,9 @@ def _record_duplicate(a, st, pr, cache): | |||
| 150 | """ | 155 | """ |
| 151 | if a.code_hash not in cache: | 156 | if a.code_hash not in cache: |
| 152 | return False | 157 | return False |
| 158 | + if current() is not None: | ||
| 159 | + cached = cache[a.code_hash] | ||
| 160 | + _tile_bayes_tell(st, a.op_dir, a.parent, cached.get("s"), cached.get("p")) | ||
| 153 | pr["duplicate_rejected"] = pr.get("duplicate_rejected", 0) + 1 | 161 | pr["duplicate_rejected"] = pr.get("duplicate_rejected", 0) + 1 |
| 154 | r0 = _refine_for(pr, a.parent) | 162 | r0 = _refine_for(pr, a.parent) |
| 155 | # A run of duplicates is the only honest signal that an action has no | 163 | # A run of duplicates is the only honest signal that an action has no |
| @@ -358,10 +366,21 @@ def _halt_on_broken_chain(a, st, payload, chain_error, op_file): | |||
| 358 | raise Refusal(3) | 366 | raise Refusal(3) |
| 359 | 367 | ||
| 360 | 368 | ||
| 369 | +def _check_staged_measurement(a, op_file): | ||
| 370 | + if current() is not None and (a.remeasure or not a.unevaluated): | ||
| 371 | + staged_hash = file_hash(op_file) | ||
| 372 | + if not staged_hash or staged_hash != a.code_hash: | ||
| 373 | + out({"recorded": False, "refused": True, "error": "code_hash_mismatch", | ||
| 374 | + "code_hash": a.code_hash, "staged_hash": staged_hash, "op_file": op_file}) | ||
| 375 | + raise Refusal(3) | ||
| 376 | + | ||
| 377 | + | ||
| 361 | def cmd_record(a): | 378 | def cmd_record(a): |
| 362 | """One candidate evaluated inside local refinement of action `parent`.""" | 379 | """One candidate evaluated inside local refinement of action `parent`.""" |
| 363 | st = load(a.op_dir) | 380 | st = load(a.op_dir) |
| 364 | pr = st["progress"] | 381 | pr = st["progress"] |
| 382 | + op_file = op_file_path(st, a.op_dir) | ||
| 383 | + _check_staged_measurement(a, op_file) | ||
| 365 | if _record_handled_elsewhere(a, st, pr): | 384 | if _record_handled_elsewhere(a, st, pr): |
| 366 | return | 385 | return |
| 367 | m_rec = record_metrics(a, st) | 386 | m_rec = record_metrics(a, st) |
| @@ -386,7 +405,6 @@ def cmd_record(a): | |||
| 386 | # value for a program it did not propose would poison the surrogate with a | 405 | # value for a program it did not propose would poison the surrogate with a |
| 387 | # point the search never actually visited. | 406 | # point the search never actually visited. |
| 388 | _tile_bayes_tell(st, a.op_dir, a.parent, a.s, a.p) | 407 | _tile_bayes_tell(st, a.op_dir, a.parent, a.s, a.p) |
| 389 | - op_file = op_file_path(st, a.op_dir) | ||
| 390 | accepted, acceptance = _record_acceptance(a, st, pr, op_file, m_eval) | 408 | accepted, acceptance = _record_acceptance(a, st, pr, op_file, m_eval) |
| 391 | measured = RatchetMeasurement(j, m_eval, accepted, (acceptance or {}).get("clarity")) | 409 | measured = RatchetMeasurement(j, m_eval, accepted, (acceptance or {}).get("clarity")) |
| 392 | r, improved, bar, chain_error = _apply_ratchet(a, st, op_file, measured) | 410 | r, improved, bar, chain_error = _apply_ratchet(a, st, op_file, measured) |
| @@ -1125,9 +1143,17 @@ def _cmd_remeasure(a, st): | |||
| 1125 | cache = st.setdefault("eval_cache", {}) | 1143 | cache = st.setdefault("eval_cache", {}) |
| 1126 | samples = cli_samples(a) | 1144 | samples = cli_samples(a) |
| 1127 | entry, point = _remeasure_target(a, st, cache, samples) | 1145 | entry, point = _remeasure_target(a, st, cache, samples) |
| 1146 | + if getattr(a, "remeasurement_profile", None): | ||
| 1147 | + entry.setdefault("remeasurement_profiles", []).append(a.remeasurement_profile) | ||
| 1128 | pooled = list(entry.get("samples") or []) + samples | 1148 | pooled = list(entry.get("samples") or []) + samples |
| 1149 | + readings = pooled | ||
| 1150 | + backend = current() | ||
| 1151 | + if backend is not None: | ||
| 1152 | + # Use the backend's comparison units for both the headline and the Pareto row. | ||
| 1153 | + readings = backend.entry_reads(entry) + backend.entry_reads({"samples": samples}) | ||
| 1154 | + entry["reads"] = point["reads"] = readings | ||
| 1129 | entry["samples"] = pooled | 1155 | entry["samples"] = pooled |
| 1130 | - entry["p"] = median_of(pooled) | 1156 | + entry["p"] = median_of(readings or pooled) |
| 1131 | entry["remeasured"] = int(entry.get("remeasured", 0)) + 1 | 1157 | entry["remeasured"] = int(entry.get("remeasured", 0)) + 1 |
| 1132 | observe_noise(st, samples, SEARCH_PROTOCOL) | 1158 | observe_noise(st, samples, SEARCH_PROTOCOL) |
| 1133 | objs = objectives_of(st) | 1159 | objs = objectives_of(st) |
| @@ -22,6 +22,7 @@ import random | |||
| 22 | 22 | ||
| 23 | from .config import (DEFAULT_CONFIG, NOISE_WINDOW, OBJECTIVE_ALIASES, PIPE_METRICS, VERIFY_ALPHA, VERIFY_BOOT, | 23 | from .config import (DEFAULT_CONFIG, NOISE_WINDOW, OBJECTIVE_ALIASES, PIPE_METRICS, VERIFY_ALPHA, VERIFY_BOOT, |
| 24 | VERIFY_SEED, _MEASUREMENT_NOT_METRICS, feasibility) | 24 | VERIFY_SEED, _MEASUREMENT_NOT_METRICS, feasibility) |
| 25 | +from .state import occupancy_options | ||
| 25 | 26 | ||
| 26 | 27 | ||
| 27 | def compute_j(s, p, p_ref): | 28 | def compute_j(s, p, p_ref): |
| @@ -52,7 +53,7 @@ def metrics(util, bubble, fallback=None, pipes=None): | |||
| 52 | return m | 53 | return m |
| 53 | 54 | ||
| 54 | 55 | ||
| 55 | -def _occupancies(op_file): | 56 | +def _occupancies(op_file, st): |
| 56 | """(UB fraction, L1 fraction) for the kernel currently on disk; either may be | 57 | """(UB fraction, L1 fraction) for the kernel currently on disk; either may be |
| 57 | None. Never raises: a symptom that can fail the run is worse than a symptom | 58 | None. Never raises: a symptom that can fail the run is worse than a symptom |
| 58 | that stays quiet. | 59 | that stays quiet. |
| @@ -67,8 +68,9 @@ def _occupancies(op_file): | |||
| 67 | if not op_file or not os.path.exists(op_file): | 68 | if not op_file or not os.path.exists(op_file): |
| 68 | return None, None | 69 | return None, None |
| 69 | try: | 70 | try: |
| 70 | - return (feasibility.ub_occupancy(op_file), | 71 | + options = occupancy_options(st) |
| 71 | - feasibility.l1_occupancy(op_file)) | 72 | + return (feasibility.ub_occupancy(op_file, **options), |
| 73 | + feasibility.l1_occupancy(op_file, **options)) | ||
| 72 | except Exception: | 74 | except Exception: |
| 73 | return None, None | 75 | return None, None |
| 74 | 76 | ||
| @@ -612,7 +614,7 @@ def record_metrics(a, st): | |||
| 612 | 614 | ||
| 613 | 615 | ||
| 614 | def incumbent_latency(st, src): | 616 | def incumbent_latency(st, src): |
| 615 | - """The measured `p` of the program this source text IS, or None. | 617 | + """Return the cached latency for these source bytes (or UTF-8 text), if measured. |
| 616 | 618 | ||
| 617 | A tile study's `current` seed is recorded as a COMPLETED observation at the | 619 | A tile study's `current` seed is recorded as a COMPLETED observation at the |
| 618 | tile configuration the file holds (`lever._fill_seeds`), so the number | 620 | tile configuration the file holds (`lever._fill_seeds`), so the number |
| @@ -626,8 +628,8 @@ def incumbent_latency(st, src): | |||
| 626 | a seed with no value to be measured, so an unmeasured base costs one device | 628 | a seed with no value to be measured, so an unmeasured base costs one device |
| 627 | trial instead of poisoning the surrogate. | 629 | trial instead of poisoning the surrogate. |
| 628 | """ | 630 | """ |
| 629 | - entry = (st.get("eval_cache") or {}).get( | 631 | + data = src.encode("utf-8") if isinstance(src, str) else src |
| 630 | - hashlib.sha256(src.encode("utf-8")).hexdigest()) or {} | 632 | + entry = (st.get("eval_cache") or {}).get(hashlib.sha256(data).hexdigest()) or {} |
| 631 | p = entry.get("p") | 633 | p = entry.get("p") |
| 632 | if not entry.get("s") or not isinstance(p, (int, float)) or p <= 0: | 634 | if not entry.get("s") or not isinstance(p, (int, float)) or p <= 0: |
| 633 | return None | 635 | return None |
| @@ -643,3 +645,100 @@ def _preopt_metrics(a): | |||
| 643 | m.update(_cli_workspace(a, "preopt_")) | 645 | m.update(_cli_workspace(a, "preopt_")) |
| 644 | m.update(_cli_extra_metrics(a, "preopt_")) | 646 | m.update(_cli_extra_metrics(a, "preopt_")) |
| 645 | return m | 647 | return m |
| 648 | + | ||
| 649 | + | ||
| 650 | +def _confirmation_pair(objective, arms, out): | ||
| 651 | + """Acquire one ordered pair and retain partial evidence on a failure.""" | ||
| 652 | + reading = {} | ||
| 653 | + for name, cfg in arms: | ||
| 654 | + try: | ||
| 655 | + result = objective(cfg) | ||
| 656 | + verdict, latency = result[:2] | ||
| 657 | + except Exception as exc: # noqa: BLE001 | ||
| 658 | + out["error"] = "%s: %s" % (name, exc) | ||
| 659 | + return False | ||
| 660 | + out["trials"] += 1 | ||
| 661 | + reading[name] = { | ||
| 662 | + "s": int(verdict or 0), "p": latency, | ||
| 663 | + "samples": list(getattr(objective, "last_samples", None) or []), | ||
| 664 | + "detail": (getattr(objective, "last_detail", "") or "")[:200]} | ||
| 665 | + trial_metrics = getattr(objective, "last_metrics", None) or {} | ||
| 666 | + a = (reading.get("winner") or {}).get("p") | ||
| 667 | + b = (reading.get("incumbent") or {}).get("p") | ||
| 668 | + if not all(item.get("s") for item in reading.values()): | ||
| 669 | + out["error"] = "a confirmation candidate failed correctness" | ||
| 670 | + return False | ||
| 671 | + if not (a and b and a > 0 and b > 0): | ||
| 672 | + out["error"] = "a confirmation reading has no latency" | ||
| 673 | + return False | ||
| 674 | + reading["log_ratio"] = round(math.log(a / b), 6) | ||
| 675 | + out["pairs"].append(reading) | ||
| 676 | + return True | ||
| 677 | + | ||
| 678 | + | ||
| 679 | +def confirm_block_winner(objective, incumbent, winner, seed=0, *, pairs): | ||
| 680 | + """ | ||
| 681 | + Confirm the selected winner against fresh, paired incumbent readings. | ||
| 682 | + | ||
| 683 | + Randomize adjacent measurement order to reduce drift and selection bias. | ||
| 684 | + Confirmation evaluates no new candidate and does not charge ``max_trials``; | ||
| 685 | + its readings remain visible in the trial record. Workspace bytes are not | ||
| 686 | + measured again because they are determined by the candidate configuration. | ||
| 687 | + A failed confirmation retains the selection readings and reports an error. | ||
| 688 | + """ | ||
| 689 | + if not winner or not incumbent: | ||
| 690 | + return {} | ||
| 691 | + k = int(pairs) | ||
| 692 | + if k < 1: | ||
| 693 | + return {} | ||
| 694 | + rng = random.Random(seed) | ||
| 695 | + out = {"pairs": [], "orders": [], "trials": 0} | ||
| 696 | + for _ in range(k): | ||
| 697 | + arms = [("incumbent", incumbent), ("winner", winner)] | ||
| 698 | + # Per PAIR, not once for the whole confirmation: a single order repeated | ||
| 699 | + # k times is a fixed order, and a fixed order turns a drift into an | ||
| 700 | + # effect exactly as it would with k=1. | ||
| 701 | + if rng.random() < 0.5: | ||
| 702 | + arms.reverse() | ||
| 703 | + out["orders"].append("".join("I" if n == "incumbent" else "W" | ||
| 704 | + for n, _ in arms)) | ||
| 705 | + if not _confirmation_pair(objective, arms, out): | ||
| 706 | + return _confirm_summary(out) | ||
| 707 | + return _confirm_summary(out) | ||
| 708 | + | ||
| 709 | + | ||
| 710 | +def _confirm_summary(out): | ||
| 711 | + """ | ||
| 712 | + The mean paired difference over however many pairs completed. | ||
| 713 | + | ||
| 714 | + A confirmation that broke part way is summarised over the pairs it did | ||
| 715 | + finish rather than discarded: two pairs are worse than three and far better | ||
| 716 | + than the selection reading alone. With none finished the caller keeps the | ||
| 717 | + selection reading, which `block_apply_winner` does when `p` is absent. | ||
| 718 | + """ | ||
| 719 | + diffs = [p["log_ratio"] for p in out.get("pairs") or ()] | ||
| 720 | + if not diffs: | ||
| 721 | + return out | ||
| 722 | + mean = sum(diffs) / len(diffs) | ||
| 723 | + out["log_ratio"] = round(mean, 6) | ||
| 724 | + out["speedup"] = round(math.exp(-mean), 4) | ||
| 725 | + out["agrees"] = mean < 0 | ||
| 726 | + out["n_pairs"] = len(diffs) | ||
| 727 | + if len(diffs) > 1: | ||
| 728 | + var = sum((d - mean) ** 2 for d in diffs) / (len(diffs) - 1) | ||
| 729 | + out["sd_log_ratio"] = round(math.sqrt(var), 6) | ||
| 730 | + last = out["pairs"][-1] | ||
| 731 | + # The reading the caller carries: the winner's mean over the pairs, so the | ||
| 732 | + # number recorded is the same estimator the verdict was taken on. | ||
| 733 | + ps = [(p.get("winner") or {}).get("p") for p in out["pairs"]] | ||
| 734 | + ps = [x for x in ps if x] | ||
| 735 | + out["readings"] = { | ||
| 736 | + "winner": dict(last.get("winner") or {}, | ||
| 737 | + p=round(sum(ps) / len(ps), 6) if ps else None), | ||
| 738 | + "incumbent": last.get("incumbent") or {}} | ||
| 739 | + out["order"] = out.get("orders") or [] | ||
| 740 | + return out | ||
| 741 | + | ||
| 742 | +# Public service API used by the shared core and DSL adapters. | ||
| 743 | +confirm_summary = _confirm_summary | ||
| 744 | +confirmation_pair = _confirmation_pair | ||
| @@ -13,18 +13,20 @@ The learned prior and its store, the Thompson draw, the symptom boost, and | |||
| 13 | the tile lever that proposes numbers the model cannot. | 13 | the tile lever that proposes numbers the model cannot. |
| 14 | """ | 14 | """ |
| 15 | 15 | ||
| 16 | -import hashlib | 16 | +import io |
| 17 | import json | 17 | import json |
| 18 | import math | 18 | import math |
| 19 | import os | 19 | import os |
| 20 | import shutil | 20 | import shutil |
| 21 | import time | 21 | import time |
| 22 | +import tokenize | ||
| 23 | +from pathlib import Path | ||
| 22 | 24 | ||
| 23 | import action_posterior | 25 | import action_posterior |
| 24 | import prior_store | 26 | import prior_store |
| 25 | 27 | ||
| 26 | from .config import DEFAULT_CATALOG, DEFAULT_CONFIG, SYMPTOM_ACTIONS, SYMPTOM_THRESH, bayesian, w_stage | 28 | from .config import DEFAULT_CATALOG, DEFAULT_CONFIG, SYMPTOM_ACTIONS, SYMPTOM_THRESH, bayesian, w_stage |
| 27 | -from .state import _domain_state, chip_envelope, op_file_path, open_node, read_text, sdir | 29 | +from .state import _domain_state, chip_envelope, file_hash, op_file_path, open_node, sdir |
| 28 | from .measurement import _occupancies, incumbent_latency, objectives_of | 30 | from .measurement import _occupancies, incumbent_latency, objectives_of |
| 29 | from .front import demand_hint_text | 31 | from .front import demand_hint_text |
| 30 | from .log import log_open_action | 32 | from .log import log_open_action |
| @@ -133,7 +135,7 @@ def _symptom_reboost(st, util, bubble, op_file=None, pipes=None): | |||
| 133 | util = bubble = 0.0 | 135 | util = bubble = 0.0 |
| 134 | 136 | ||
| 135 | active = [] | 137 | active = [] |
| 136 | - occ, l1 = _occupancies(op_file) | 138 | + occ, l1 = _occupancies(op_file, st) |
| 137 | if occ is not None and occ < SYMPTOM_THRESH["occupancy"]: | 139 | if occ is not None and occ < SYMPTOM_THRESH["occupancy"]: |
| 138 | active.append("occupancy") | 140 | active.append("occupancy") |
| 139 | if l1 is not None and l1 < SYMPTOM_THRESH["l1_occupancy"]: | 141 | if l1 is not None and l1 < SYMPTOM_THRESH["l1_occupancy"]: |
| @@ -187,6 +189,13 @@ def _retune_verdict(st, op_file): | |||
| 187 | "resident."} | 189 | "resident."} |
| 188 | 190 | ||
| 189 | 191 | ||
| 192 | +def _read_tile_source(op_file): | ||
| 193 | + """Read one artifact for its cache identity and decode it for Python analysis.""" | ||
| 194 | + data = Path(op_file).read_bytes() | ||
| 195 | + encoding, _ = tokenize.detect_encoding(io.BytesIO(data).readline) | ||
| 196 | + return data, data.decode(encoding), encoding | ||
| 197 | + | ||
| 198 | + | ||
| 190 | def _tile_bayes_tell(st, op_dir, parent_id, s, p): | 199 | def _tile_bayes_tell(st, op_dir, parent_id, s, p): |
| 191 | """Report the measurement to the study that proposed it. Silent when the | 200 | """Report the measurement to the study that proposed it. Silent when the |
| 192 | action is not a BO lever: every other action still goes through the model. | 201 | action is not a BO lever: every other action still goes through the model. |
| @@ -200,8 +209,10 @@ def _tile_bayes_tell(st, op_dir, parent_id, s, p): | |||
| 200 | op_file = op_file_path(st, op_dir) | 209 | op_file = op_file_path(st, op_dir) |
| 201 | if not op_file or not os.path.exists(op_file): | 210 | if not op_file or not os.path.exists(op_file): |
| 202 | return | 211 | return |
| 203 | - src = read_text(op_file) | 212 | + _, src, _ = _read_tile_source(op_file) |
| 204 | - bayesian.lever.tell(st.setdefault("bayesian_optimization_studies", {}), cid, src, s, p) | 213 | + from .backend import current |
| 214 | + context = current().tile_constants(st, op_file, src) if current() else {} | ||
| 215 | + bayesian.lever.tell(st.setdefault("bayesian_optimization_studies", {}), cid, src, s, p, **context) | ||
| 205 | 216 | ||
| 206 | 217 | ||
| 207 | def _expansion_demand(st, demand): | 218 | def _expansion_demand(st, demand): |
| @@ -261,10 +272,13 @@ def _log_selection(op_dir, st, best, rec, sel): | |||
| 261 | + f" · of {len(rec['candidates'])} candidates") | 272 | + f" · of {len(rec['candidates'])} candidates") |
| 262 | 273 | ||
| 263 | 274 | ||
| 264 | -def _selects_path(op_dir): | 275 | +def selects_path(op_dir): |
| 265 | return os.path.join(sdir(op_dir), "selects.jsonl") | 276 | return os.path.join(sdir(op_dir), "selects.jsonl") |
| 266 | 277 | ||
| 267 | 278 | ||
| 279 | +_selects_path = selects_path | ||
| 280 | + | ||
| 281 | + | ||
| 268 | def record_select(op_dir, st, frontier, chosen, sel): | 282 | def record_select(op_dir, st, frontier, chosen, sel): |
| 269 | """ | 283 | """ |
| 270 | One JSON line per selection: every candidate with the factors it was | 284 | One JSON line per selection: every candidate with the factors it was |
| @@ -448,6 +462,9 @@ def _record_outcome(st, a, outcome, arc_verdict=None, accepted=None): | |||
| 448 | "code_version": st.get("code_version")} | 462 | "code_version": st.get("code_version")} |
| 449 | shared = os.path.join(prior_store.store_dir(soc=_soc(st)), | 463 | shared = os.path.join(prior_store.store_dir(soc=_soc(st)), |
| 450 | f"{_campaign_id(st)}.jsonl") | 464 | f"{_campaign_id(st)}.jsonl") |
| 465 | + from .backend import current | ||
| 466 | + if current() is not None and not current().EXPORT_OUTCOMES: | ||
| 467 | + shared = None | ||
| 451 | errs = prior_store.append_outcome( | 468 | errs = prior_store.append_outcome( |
| 452 | row, os.path.join(sdir(a.op_dir), "action_outcomes.jsonl"), shared) | 469 | row, os.path.join(sdir(a.op_dir), "action_outcomes.jsonl"), shared) |
| 453 | if errs: | 470 | if errs: |
| @@ -589,7 +606,7 @@ def tile_bayes_propose(st, op_dir, node): | |||
| 589 | return {"applied": False, | 606 | return {"applied": False, |
| 590 | "reason": f"op_file not found: {op_file!r} (cwd={os.getcwd()!r}). " | 607 | "reason": f"op_file not found: {op_file!r} (cwd={os.getcwd()!r}). " |
| 591 | f"bayesian_optimization_tile_search is ON but the lever cannot read the kernel."} | 608 | f"bayesian_optimization_tile_search is ON but the lever cannot read the kernel."} |
| 592 | - src = read_text(op_file) | 609 | + source_bytes, src, encoding = _read_tile_source(op_file) |
| 593 | studies = st.setdefault("bayesian_optimization_studies", {}) | 610 | studies = st.setdefault("bayesian_optimization_studies", {}) |
| 594 | # The same 2x `cmd_block` threads below, in the one path that never got it. | 611 | # The same 2x `cmd_block` threads below, in the one path that never got it. |
| 595 | # `bayesian.space.HW` defaults `dtype_bytes` to 4 and so does `bayesian.lever.ask`, while | 612 | # `bayesian.space.HW` defaults `dtype_bytes` to 4 and so does `bayesian.lever.ask`, while |
| @@ -607,7 +624,9 @@ def tile_bayes_propose(st, op_dir, node): | |||
| 607 | # which it can then never climb back to. Meanwhile the block path, correct | 624 | # which it can then never climb back to. Meanwhile the block path, correct |
| 608 | # at 2 B, kept working: the same search_state.json says "at 2B" under | 625 | # at 2 B, kept working: the same search_state.json says "at 2B" under |
| 609 | # `blocks` and "at 4B" under `bayesian_optimization_studies`. | 626 | # `blocks` and "at 4B" under `bayesian_optimization_studies`. |
| 610 | - hw, domain = bayesian.block.hw_for(op_file, st.get("live_tiles"), chip_envelope(st)) | 627 | + from .backend import current |
| 628 | + context = current().tile_constants(st, op_file, src) if current() else {} | ||
| 629 | + hw, domain = bayesian.block.hw_for(op_file, st.get("live_tiles"), chip_envelope(st), **context) | ||
| 611 | cfg, meta = bayesian.lever.ask( | 630 | cfg, meta = bayesian.lever.ask( |
| 612 | studies, node["catalog_id"], src, hw, | 631 | studies, node["catalog_id"], src, hw, |
| 613 | bayesian.lever.AskOptions( | 632 | bayesian.lever.AskOptions( |
| @@ -617,16 +636,22 @@ def tile_bayes_propose(st, op_dir, node): | |||
| 617 | # The incumbent is the program ON DISK, which `select` has just | 636 | # The incumbent is the program ON DISK, which `select` has just |
| 618 | # restored -- the front base, not necessarily the global best. Same | 637 | # restored -- the front base, not necessarily the global best. Same |
| 619 | # clock as the trials it seeds, and the same rule as `_block_search`. | 638 | # clock as the trials it seeds, and the same rule as `_block_search`. |
| 620 | - current_latency=incumbent_latency(st, src))) | 639 | + current_latency=incumbent_latency(st, source_bytes))) |
| 621 | if cfg is None: | 640 | if cfg is None: |
| 622 | return {"applied": False, "reason": meta.get("reason", "no candidate")} | 641 | return {"applied": False, "reason": meta.get("reason", "no candidate")} |
| 623 | - new_src, n = bayesian.apply.apply(src, cfg) | 642 | + new_src, n = bayesian.apply.apply(src, cfg, **context) |
| 624 | if not n or new_src == src: | 643 | if not n or new_src == src: |
| 644 | + if current() is not None: | ||
| 645 | + return {"applied": True, "requires_measurement": True, "config": cfg, | ||
| 646 | + "label": meta.get("label"), "trial": meta.get("trial"), "sites": 0, | ||
| 647 | + "code_hash": file_hash(op_file)} | ||
| 625 | return {"applied": False, "reason": "no site rewritten"} | 648 | return {"applied": False, "reason": "no site rewritten"} |
| 626 | - with open(op_file, "w", encoding="utf-8") as f: | 649 | + if current() is not None: |
| 627 | - f.write(new_src) | 650 | + current().write_source(op_file, new_src) |
| 651 | + else: | ||
| 652 | + Path(op_file).write_bytes(new_src.encode(encoding)) | ||
| 628 | return {"applied": True, "config": cfg, "label": meta.get("label"), | 653 | return {"applied": True, "config": cfg, "label": meta.get("label"), |
| 629 | "trial": meta.get("trial"), "sites": n, | 654 | "trial": meta.get("trial"), "sites": n, |
| 630 | - "code_hash": hashlib.sha256(new_src.encode("utf-8")).hexdigest(), | 655 | + "code_hash": file_hash(op_file), |
| 631 | "note": "already written to the kernel; do NOT dispatch the coder, " | 656 | "note": "already written to the kernel; do NOT dispatch the coder, " |
| 632 | "just evaluate and record"} | 657 | "just evaluate and record"} |
| @@ -19,7 +19,9 @@ import json | |||
| 19 | import os | 19 | import os |
| 20 | import shutil | 20 | import shutil |
| 21 | import subprocess | 21 | import subprocess |
| 22 | +import tempfile | ||
| 22 | import time | 23 | import time |
| 24 | +from pathlib import Path | ||
| 23 | 25 | ||
| 24 | from .config import (CHIP_ENVELOPE, DEFAULT_CONFIG, OPTIONAL_ENVELOPE, REFUSAL_GLOBAL_AFTER, SCRIPTS_DIR, | 26 | from .config import (CHIP_ENVELOPE, DEFAULT_CONFIG, OPTIONAL_ENVELOPE, REFUSAL_GLOBAL_AFTER, SCRIPTS_DIR, |
| 25 | _RENAMED_CONFIG_KEYS, _RENAMED_STATE_KEYS, bayesian, chip_profile, clamp_prior) | 27 | _RENAMED_CONFIG_KEYS, _RENAMED_STATE_KEYS, bayesian, chip_profile, clamp_prior) |
| @@ -48,6 +50,17 @@ def chip_envelope(st=None): | |||
| 48 | return env | 50 | return env |
| 49 | 51 | ||
| 50 | 52 | ||
| 53 | +def occupancy_options(st): | ||
| 54 | + """Bind Classic occupancy probes to this run's UB and L1 capacities.""" | ||
| 55 | + from .backend import current | ||
| 56 | + from .config import feasibility | ||
| 57 | + | ||
| 58 | + if current() is not None: | ||
| 59 | + return {} # Registered frontends provide their own occupancy probes. | ||
| 60 | + env = chip_envelope(st) | ||
| 61 | + return {"hw": feasibility.HW(ub_budget_kb=env["ub_kb"], l1_budget_kb=env["l1_kb"])} | ||
| 62 | + | ||
| 63 | + | ||
| 51 | # --------------------------------------------------------------------------- I/O | 64 | # --------------------------------------------------------------------------- I/O |
| 52 | def sdir(op_dir): | 65 | def sdir(op_dir): |
| 53 | return os.path.join(op_dir, "optimization") | 66 | return os.path.join(op_dir, "optimization") |
| @@ -137,6 +150,9 @@ def _pypto_defaults(): | |||
| 137 | handled by degrading rather than by guessing: with no defaults the semantic | 150 | handled by degrading rather than by guessing: with no defaults the semantic |
| 138 | comparison still catches reformatting and comment edits and folds nothing. | 151 | comparison still catches reformatting and comment edits and folds nothing. |
| 139 | """ | 152 | """ |
| 153 | + from .backend import current | ||
| 154 | + if current() is not None: | ||
| 155 | + return {} | ||
| 140 | global _PYPTO_DEFAULTS | 156 | global _PYPTO_DEFAULTS |
| 141 | if _PYPTO_DEFAULTS is None: | 157 | if _PYPTO_DEFAULTS is None: |
| 142 | if bayesian is None: | 158 | if bayesian is None: |
| @@ -221,6 +237,16 @@ def snapshot(op_dir, op_file, code_hash): | |||
| 221 | return True | 237 | return True |
| 222 | 238 | ||
| 223 | 239 | ||
| 240 | +def snapshot_source(op_dir, code_hash, data): | ||
| 241 | + """Publish the measured tile program bytes under their content hash.""" | ||
| 242 | + dest = Path(npath(op_dir, code_hash)) | ||
| 243 | + dest.parent.mkdir(parents=True, exist_ok=True) | ||
| 244 | + with tempfile.TemporaryDirectory(dir=dest.parent) as stage: | ||
| 245 | + candidate = Path(stage) / dest.name | ||
| 246 | + candidate.write_bytes(data) | ||
| 247 | + candidate.replace(dest) | ||
[P2] 候选快照写入失败会丢失已完成试次的账目 问题描述 依据 在第一条候选的快照目标位置预置同名目录,评估读数使用合成值。 建议 处理快照写入的 ![]() ![]() | |||
| 248 | + | ||
| 249 | + | ||
| 224 | def restore(op_dir, op_file, code_hash): | 250 | def restore(op_dir, op_file, code_hash): |
| 225 | """Restore nodes/<code_hash>.py -> op_file (deterministic roll-back to a known-good state).""" | 251 | """Restore nodes/<code_hash>.py -> op_file (deterministic roll-back to a known-good state).""" |
| 226 | if not op_file or not code_hash: | 252 | if not op_file or not code_hash: |
| @@ -229,8 +255,13 @@ def restore(op_dir, op_file, code_hash): | |||
| 229 | if not os.path.exists(snap): | 255 | if not os.path.exists(snap): |
| 230 | return False | 256 | return False |
| 231 | try: | 257 | try: |
| 232 | - shutil.copyfile(snap, op_file) | 258 | + from .backend import current |
| 233 | - except OSError: | 259 | + if current() is not None: |
| 260 | + current().write_source(op_file, _read_bytes(snap).decode("utf-8")) | ||
[P2] 注册前端的 问题描述 依据 在 建议 统一试次暂存、快照、winner 和恢复的字节规则。用实际参与评估的字节计算 hash,并验证恢复后得到同一 hash。 ![]() ![]() | |||
| 261 | + return file_hash(op_file) == code_hash | ||
| 262 | + else: | ||
| 263 | + shutil.copyfile(snap, op_file) | ||
| 264 | + except (OSError, ValueError): | ||
| 234 | return False | 265 | return False |
| 235 | return True | 266 | return True |
| 236 | 267 | ||
| @@ -241,6 +272,9 @@ def _code_version(): | |||
| 241 | come from a build with or without symptom anchoring, greedy accumulation, | 272 | come from a build with or without symptom anchoring, greedy accumulation, |
| 242 | or the frozen evaluator, and nothing in the state says which. | 273 | or the frozen evaluator, and nothing in the state says which. |
| 243 | """ | 274 | """ |
| 275 | + from .backend import current | ||
| 276 | + if current() is not None: | ||
| 277 | + return current().revision() | ||
| 244 | here = SCRIPTS_DIR | 278 | here = SCRIPTS_DIR |
| 245 | rev = "" | 279 | rev = "" |
| 246 | git = shutil.which("git") | 280 | git = shutil.which("git") |
| @@ -285,7 +319,9 @@ def _domain_state(st, op_file, live_tiles=None): | |||
| 285 | return None | 319 | return None |
| 286 | if not op_file or not os.path.exists(op_file): | 320 | if not op_file or not os.path.exists(op_file): |
| 287 | return None | 321 | return None |
| 288 | - return bayesian.domain.derive(op_file, live_tiles or st.get("live_tiles")) | 322 | + from .backend import current |
| 323 | + options = {"ub_budget_kb": chip_envelope(st)["ub_kb"]} if current() is None else {} | ||
| 324 | + return bayesian.domain.derive(op_file, live_tiles or st.get("live_tiles"), **options) | ||
| 289 | 325 | ||
| 290 | 326 | ||
| 291 | def _structure(st, op_dir): | 327 | def _structure(st, op_dir): |
| @@ -434,6 +470,9 @@ def wrapper_signature(src): | |||
| 434 | Returns None when the file does not parse -- callers treat that as "cannot | 470 | Returns None when the file does not parse -- callers treat that as "cannot |
| 435 | tell" and say so, rather than passing a candidate the check never ran on. | 471 | tell" and say so, rather than passing a candidate the check never ran on. |
| 436 | """ | 472 | """ |
| 473 | + from .backend import current | ||
| 474 | + if current() is not None: | ||
| 475 | + return current().wrapper_signature(src) | ||
| 437 | try: | 476 | try: |
| 438 | tree = ast.parse(src) | 477 | tree = ast.parse(src) |
| 439 | except SyntaxError: | 478 | except SyntaxError: |
| @@ -462,13 +501,24 @@ def decorated_jit(node): | |||
| 462 | 501 | ||
| 463 | def _wrapper_drift(st, path): | 502 | def _wrapper_drift(st, path): |
| 464 | """"" 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"): | ||
| 505 | + return "" | ||
| 506 | + try: | ||
| 507 | + source = read_text(path) | ||
| 508 | + except OSError: | ||
| 509 | + return "the candidate source could not be read to check the frozen wrapper" | ||
| 510 | + return _source_wrapper_drift(st, source) | ||
| 511 | + | ||
| 512 | + | ||
| 513 | +def _source_wrapper_drift(st, source): | ||
| 465 | want = st.get("wrapper_signature") | 514 | want = st.get("wrapper_signature") |
| 466 | if not want: | 515 | if not want: |
| 467 | return "" # pre-dates the check; nothing to compare | 516 | return "" # pre-dates the check; nothing to compare |
| 468 | - try: | 517 | + from .backend import current |
| 469 | - got = wrapper_signature(read_text(path)) | 518 | + if current() is not None and "wrapper_owned_bindings" in st: |
| 470 | - except OSError: | 519 | + got = current().wrapper_signature(source, st.get("case_context"), st["wrapper_owned_bindings"]) |
| 471 | - return "" | 520 | + else: |
| 521 | + got = wrapper_signature(source) | ||
| 472 | if got is None: | 522 | if got is None: |
| 473 | return "the candidate does not parse, so the wrapper freeze could not be checked" | 523 | return "the candidate does not parse, so the wrapper freeze could not be checked" |
| 474 | if got != want: | 524 | if got != want: |
| @@ -478,7 +528,7 @@ def _wrapper_drift(st, path): | |||
| 478 | "wrapper leaves the measured region and scores as a win without " | 528 | "wrapper leaves the measured region and scores as a win without " |
| 479 | "being one. Restore the wrapper and put the change inside the " | 529 | "being one. Restore the wrapper and put the change inside the " |
| 480 | "kernel, or run this as a different experiment") | 530 | "kernel, or run this as a different experiment") |
| 481 | - return _debug_options_drift(st, path) | 531 | + return _debug_options_drift(st, source) |
| 482 | 532 | ||
| 483 | 533 | ||
| 484 | def _resolve_envelope(a): | 534 | def _resolve_envelope(a): |
| @@ -622,6 +672,9 @@ def debug_options_signature(src): | |||
| 622 | 672 | ||
| 623 | Returns None when the file does not parse. | 673 | Returns None when the file does not parse. |
| 624 | """ | 674 | """ |
| 675 | + from .backend import current | ||
| 676 | + if current() is not None: | ||
| 677 | + return current().debug_options_signature(src) | ||
| 625 | try: | 678 | try: |
| 626 | tree = ast.parse(src) | 679 | tree = ast.parse(src) |
| 627 | except SyntaxError: | 680 | except SyntaxError: |
| @@ -647,15 +700,12 @@ def _jit_debug_options(node): | |||
| 647 | return dumped | 700 | return dumped |
| 648 | 701 | ||
| 649 | 702 | ||
| 650 | -def _debug_options_drift(st, path): | 703 | +def _debug_options_drift(st, source): |
| 651 | """"" if the kernels' `debug_options` still match the baseline's.""" | 704 | """"" if the kernels' `debug_options` still match the baseline's.""" |
| 652 | want = st.get("debug_options_signature") | 705 | want = st.get("debug_options_signature") |
| 653 | if not want: | 706 | if not want: |
| 654 | return "" # pre-dates the check; nothing to compare | 707 | return "" # pre-dates the check; nothing to compare |
| 655 | - try: | 708 | + got = debug_options_signature(source) |
| 656 | - got = debug_options_signature(read_text(path)) | ||
| 657 | - except OSError: | ||
| 658 | - return "" | ||
| 659 | if got is None or got == want: | 709 | if got is None or got == want: |
| 660 | return "" | 710 | return "" |
| 661 | return ("the kernels' `debug_options` differ from the baseline. That is the " | 711 | return ("the kernels' `debug_options` differ from the baseline. That is the " |
| @@ -17,7 +17,7 @@ faults ends the run on the device, not on the search. | |||
| 17 | import evaluation_session | 17 | import evaluation_session |
| 18 | 18 | ||
| 19 | from .config import DEFAULT_CONFIG, FREE, Refusal, UNMEASURED_FIELDS, _bound, bayesian, out, predicates | 19 | from .config import DEFAULT_CONFIG, FREE, Refusal, UNMEASURED_FIELDS, _bound, bayesian, out, predicates |
| 20 | -from .state import _structure, live_frontier, op_file_path, ratchet_best_hash, restore, save | 20 | +from .state import _structure, live_frontier, occupancy_options, op_file_path, ratchet_best_hash, restore, save |
| 21 | from .measurement import objective_values, objectives_of | 21 | from .measurement import objective_values, objectives_of |
| 22 | from .front import delivery_point | 22 | from .front import delivery_point |
| 23 | 23 | ||
| @@ -48,7 +48,7 @@ def _admit(st, op_dir): | |||
| 48 | """ | 48 | """ |
| 49 | if predicates is None or not st["config"].get("action_preconditions", True): | 49 | if predicates is None or not st["config"].get("action_preconditions", True): |
| 50 | return [] | 50 | return [] |
| 51 | - preds = predicates.compute(op_file_path(st, op_dir) or "", op_dir) | 51 | + preds = predicates.compute(op_file_path(st, op_dir) or "", op_dir, **occupancy_options(st)) |
| 52 | st["predicates"] = preds | 52 | st["predicates"] = preds |
| 53 | pruned = set(st["nodes"].get("pruned", [])) | 53 | pruned = set(st["nodes"].get("pruned", [])) |
| 54 | admitted = [] | 54 | admitted = [] |
| @@ -455,7 +455,7 @@ def stop_condition(st, a): | |||
| 455 | return None | 455 | return None |
| 456 | 456 | ||
| 457 | 457 | ||
| 458 | -def block_budget(pr, cfg, a): | 458 | +def block_budget(pr, cfg, a, *, share_floor=None): |
| 459 | """How many device trials this block may spend. | 459 | """How many device trials this block may spend. |
| 460 | 460 | ||
| 461 | Three limits, and the block gets the smallest: what is left of the run | 461 | Three limits, and the block gets the smallest: what is left of the run |
| @@ -486,8 +486,9 @@ def block_budget(pr, cfg, a): | |||
| 486 | # left: `max(remaining, cap)` would top up a block that had already | 486 | # left: `max(remaining, cap)` would top up a block that had already |
| 487 | # overspent, and the share could then never bind. | 487 | # overspent, and the share could then never bind. |
| 488 | total_allowed = int(share * pr["evals_used"]) | 488 | total_allowed = int(share * pr["evals_used"]) |
| 489 | - if cap: | 489 | + floor = cap if share_floor is None else share_floor |
| 490 | - total_allowed = max(total_allowed, cap) | 490 | + if floor: |
| 491 | + total_allowed = max(total_allowed, floor) | ||
| 491 | limits.append(max(0, total_allowed - spent)) | 492 | limits.append(max(0, total_allowed - spent)) |
| 492 | if cap: | 493 | if cap: |
| 493 | limits.append(cap) | 494 | limits.append(cap) |
| @@ -257,7 +257,16 @@ def _parser_report(sub): | |||
| 257 | q.add_argument("--op-dir", required=True) | 257 | q.add_argument("--op-dir", required=True) |
| 258 | 258 | ||
| 259 | 259 | ||
| 260 | -def main(): | 260 | +def main(argv=None, before_command=None, configure=None): |
| 261 | + """Dispatch one command from argv (arguments after the program name, or sys.argv[1:]). | ||
| 262 | + | ||
| 263 | + After installing the built-in commands, call configure(subparsers) so the | ||
| 264 | + frontend can add commands or extend their arguments. Parse argv, then call | ||
| 265 | + before_command(args) with the parsed argparse.Namespace. It may validate or | ||
| 266 | + modify args, including replacing args.fn. Finally call args.fn(args) with | ||
| 267 | + that same namespace. Both hooks are optional and their return values are ignored. | ||
| 268 | + A Refusal from before_command or the command exits with the refusal's code. | ||
| 269 | + """ | ||
| 261 | p = argparse.ArgumentParser(description="Deterministic PANKO control core.") | 270 | p = argparse.ArgumentParser(description="Deterministic PANKO control core.") |
| 262 | sub = p.add_subparsers(dest="cmd", required=True) | 271 | sub = p.add_subparsers(dest="cmd", required=True) |
| 263 | 272 | ||
| @@ -275,8 +284,12 @@ def main(): | |||
| 275 | _parser_pareto(sub) | 284 | _parser_pareto(sub) |
| 276 | _parser_report(sub) | 285 | _parser_report(sub) |
| 277 | 286 | ||
| 278 | - a = p.parse_args() | 287 | + if configure is not None: |
| 288 | + configure(sub) | ||
| 289 | + a = p.parse_args(argv) | ||
| 279 | try: | 290 | try: |
| 291 | + if before_command is not None: | ||
| 292 | + before_command(a) | ||
| 280 | a.fn(a) | 293 | a.fn(a) |
| 281 | except Refusal as refusal: | 294 | except Refusal as refusal: |
| 282 | sys.exit(refusal.code) | 295 | sys.exit(refusal.code) |
| @@ -33,18 +33,26 @@ Usage: | |||
| 33 | python3 predicates.py <impl.py> [--op-dir <dir>] | 33 | python3 predicates.py <impl.py> [--op-dir <dir>] |
| 34 | """ | 34 | """ |
| 35 | 35 | ||
| 36 | +from dataclasses import dataclass | ||
| 37 | +from typing import Callable | ||
| 38 | + | ||
| 36 | import argparse | 39 | import argparse |
| 37 | import ast | 40 | import ast |
| 41 | +from importlib import import_module | ||
| 38 | import os | 42 | import os |
| 39 | import re | 43 | import re |
| 40 | import sys | 44 | import sys |
| 41 | 45 | ||
| 42 | -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | 46 | +# Structural event analysis is independent of the DSL. Delay only the DSL |
| 43 | -import feasibility # noqa: E402 same directory | 47 | +# dependencies for the namespaced library import; the Classic entry keeps its |
| 44 | -from pypto_ast import pypto_roots # noqa: E402 same directory | 48 | +# established module bindings. |
| 45 | - | 49 | +if __package__: |
| 46 | -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | 50 | + jsonio = import_module(__package__ + ".jsonio") |
| 47 | -import jsonio # noqa: E402 | 51 | + pypto_roots = import_module(__package__ + ".pypto_ast").pypto_roots |
| 52 | +else: | ||
| 53 | + import feasibility | ||
| 54 | + from pypto_ast import pypto_roots | ||
| 55 | + import jsonio | ||
| 48 | 56 | ||
| 49 | # Calls that can only exist if the kernel really has a Cube/matmul operation. | 57 | # Calls that can only exist if the kernel really has a Cube/matmul operation. |
| 50 | CUBE_CALLS = { | 58 | CUBE_CALLS = { |
| @@ -64,7 +72,7 @@ BROADCAST_CALLS = { | |||
| 64 | "combine_axis", | 72 | "combine_axis", |
| 65 | } | 73 | } |
| 66 | # Calls that write a tile back out to global memory. | 74 | # Calls that write a tile back out to global memory. |
| 67 | -WRITEBACK_CALLS = {"assemble", "copy_out", "store", "scatter"} | 75 | +WRITEBACK_CALLS = frozenset(("assemble", "copy_out", "store", "scatter")) |
| 68 | # Layout work the kernel does per tile that the host could do once. A pypto | 76 | # Layout work the kernel does per tile that the host could do once. A pypto |
| 69 | # reshape of a view-generated tensor is forced inplace=False -- a physical copy | 77 | # reshape of a view-generated tensor is forced inplace=False -- a physical copy |
| 70 | # on every tile -- and the others are the same trade in a different shape. | 78 | # on every tile -- and the others are the same trade in a different shape. |
| @@ -79,7 +87,7 @@ def _read_text(path, errors="replace"): | |||
| 79 | return f.read() | 87 | return f.read() |
| 80 | 88 | ||
| 81 | 89 | ||
| 82 | -def pypto_calls(tree): | 90 | +def pypto_calls(tree, roots=None): |
| 83 | """Every PyPTO call name in the file, attribute or bare. | 91 | """Every PyPTO call name in the file, attribute or bare. |
| 84 | 92 | ||
| 85 | PyPTO only. `<op>_impl.py` holds the kernel AND the host-side torch wrapper, | 93 | PyPTO only. `<op>_impl.py` holds the kernel AND the host-side torch wrapper, |
| @@ -92,7 +100,7 @@ def pypto_calls(tree): | |||
| 92 | `_is_pypto_call` was already the boundary test in this file -- the layout | 100 | `_is_pypto_call` was already the boundary test in this file -- the layout |
| 93 | and residency predicates use it -- and this is the one place that did not. | 101 | and residency predicates use it -- and this is the one place that did not. |
| 94 | """ | 102 | """ |
| 95 | - roots = pypto_roots(tree) | 103 | + roots = pypto_roots(tree) if roots is None else roots |
| 96 | return { | 104 | return { |
| 97 | _call_name(node) | 105 | _call_name(node) |
| 98 | for node in ast.walk(tree) | 106 | for node in ast.walk(tree) |
| @@ -100,41 +108,6 @@ def pypto_calls(tree): | |||
| 100 | } | 108 | } |
| 101 | 109 | ||
| 102 | 110 | ||
| 103 | -def _chunk_loop(node): | ||
| 104 | - """Is this call a chunk-shaped `pypto.loop`? | ||
| 105 | - | ||
| 106 | - Two pieces of evidence are accepted: a name= argument that mentions a chunk, | ||
| 107 | - or a `pypto.loop(start, stop, step)` whose step is not the literal 1, because | ||
| 108 | - a strided loop's step IS the chunk width. | ||
| 109 | - | ||
| 110 | - The strided form was added because the name test alone misses every chunked | ||
| 111 | - scan in this repo. `chunked_gated_delta_rule_impl.py:379` writes | ||
| 112 | - `pypto.loop(0, s, l, name="LOOP_S_TND")` and | ||
| 113 | - `qkv_rms_norm_rope_cache_impl.py:234` writes | ||
| 114 | - `pypto.loop(0, params.tokens, params.token_tile, ...)` -- `l` and `token_tile` | ||
| 115 | - are the chunk sizes F-19 retunes, and neither loop is called a chunk. Step 1 | ||
| 116 | - is excluded because it is an ordinary range, which is how the sparse-attention | ||
| 117 | - and grouped-GEMM kernels use the same three-argument form. | ||
| 118 | - """ | ||
| 119 | - fn = node.func | ||
| 120 | - if (fn.attr if isinstance(fn, ast.Attribute) else getattr(fn, "id", "")) != "loop": | ||
| 121 | - return False | ||
| 122 | - for kw in node.keywords or []: | ||
| 123 | - if kw.arg == "name" and isinstance(kw.value, ast.Constant): | ||
| 124 | - if re.search(r"chunk|_bt\b|\bbt\b", str(kw.value.value), re.I): | ||
| 125 | - return True | ||
| 126 | - if len(node.args) < 3: | ||
| 127 | - return False | ||
| 128 | - # A SYMBOL, or an integer other than 1. Every real chunk step in this repo is | ||
| 129 | - # a name (`l`, `L`, `params.token_tile`); requiring one rather than "anything | ||
| 130 | - # but 1" keeps out `pypto.loop(n, 0, -1)`, which is reverse iteration and | ||
| 131 | - # parses as a UnaryOp rather than a Constant. | ||
| 132 | - step = node.args[2] | ||
| 133 | - named_step = isinstance(step, (ast.Name, ast.Attribute)) | ||
| 134 | - literal_step = isinstance(step, ast.Constant) and isinstance(step.value, int) | ||
| 135 | - return bool(named_step or (literal_step and step.value != 1)) | ||
| 136 | - | ||
| 137 | - | ||
| 138 | def _chunk_assign(node): | 111 | def _chunk_assign(node): |
| 139 | """An assignment to a chunk-size constant that a loop then uses.""" | 112 | """An assignment to a chunk-size constant that a loop then uses.""" |
| 140 | return any( | 113 | return any( |
| @@ -143,7 +116,7 @@ def _chunk_assign(node): | |||
| 143 | ) | 116 | ) |
| 144 | 117 | ||
| 145 | 118 | ||
| 146 | -def _chunk_constant(tree): | 119 | +def _chunk_constant(tree, chunk_loop): |
| 147 | """Is there a chunk-shaped loop or constant? Necessary, not sufficient. | 120 | """Is there a chunk-shaped loop or constant? Necessary, not sufficient. |
| 148 | 121 | ||
| 149 | Three pieces of evidence are accepted, and anything weaker is treated as | 122 | Three pieces of evidence are accepted, and anything weaker is treated as |
| @@ -151,7 +124,7 @@ def _chunk_constant(tree): | |||
| 151 | named constant. | 124 | named constant. |
| 152 | """ | 125 | """ |
| 153 | for node in ast.walk(tree): | 126 | for node in ast.walk(tree): |
| 154 | - if isinstance(node, ast.Call) and _chunk_loop(node): | 127 | + if isinstance(node, ast.Call) and chunk_loop(node): |
| 155 | return True | 128 | return True |
| 156 | if isinstance(node, ast.Assign) and _chunk_assign(node): | 129 | if isinstance(node, ast.Assign) and _chunk_assign(node): |
| 157 | return True | 130 | return True |
| @@ -341,26 +314,6 @@ def _loop_carried_dependency(tree): | |||
| 341 | return False | 314 | return False |
| 342 | 315 | ||
| 343 | 316 | ||
| 344 | -def _has_chunked_scan(tree, src): | ||
| 345 | - """A chunked SCAN: a chunk constant AND a recurrence to chunk. | ||
| 346 | - | ||
| 347 | - The chunk constant alone is not enough. A predicate can read False at init | ||
| 348 | - and True at close, so F-19 -- "retune the chunked-scan granularity (chunk | ||
| 349 | - size bt)" -- is admitted to the frontier of a pure elementwise map that | ||
| 350 | - contains no scan of any kind. What flips it is the SEARCH ITSELF: a winning | ||
| 351 | - 1-D flatten introduces a `CHUNK` constant, and the predicate matches the | ||
| 352 | - name. | ||
| 353 | - | ||
| 354 | - That is the general hazard, and it is worth stating in one place. Predicates | ||
| 355 | - are re-derived from the OPTIMISED source, so a search can manufacture its own | ||
| 356 | - preconditions and then admit actions that were correctly held back from the | ||
| 357 | - kernel it started with. Requiring the recurrence closes this instance: | ||
| 358 | - chunking an axis creates a chunk constant, and cannot create a loop-carried | ||
| 359 | - dependency that the program did not already have. | ||
| 360 | - """ | ||
| 361 | - return _chunk_constant(tree) and _loop_carried_dependency(tree) | ||
| 362 | - | ||
| 363 | - | ||
| 364 | def _module_count(op_dir): | 317 | def _module_count(op_dir): |
| 365 | """From DESIGN.md if it says so, else from the modules directory. | 318 | """From DESIGN.md if it says so, else from the modules directory. |
| 366 | 319 | ||
| @@ -383,12 +336,15 @@ def _module_count(op_dir): | |||
| 383 | return None | 336 | return None |
| 384 | 337 | ||
| 385 | 338 | ||
| 386 | -def _call_name(call): | 339 | +def call_name(call): |
| 387 | fn = call.func | 340 | fn = call.func |
| 388 | return fn.attr if isinstance(fn, ast.Attribute) else getattr(fn, "id", "") | 341 | return fn.attr if isinstance(fn, ast.Attribute) else getattr(fn, "id", "") |
| 389 | 342 | ||
| 390 | 343 | ||
| 391 | -def _is_pypto_call(call, roots=frozenset({"pypto"})): | 344 | +_call_name = call_name |
| 345 | + | ||
| 346 | + | ||
| 347 | +def is_pypto_call(call, roots=frozenset({"pypto"})): | ||
| 392 | """Is this a call on the pypto module? | 348 | """Is this a call on the pypto module? |
| 393 | 349 | ||
| 394 | The distinction matters: the same file holds the tile-level kernel and the | 350 | The distinction matters: the same file holds the tile-level kernel and the |
| @@ -405,27 +361,10 @@ def _is_pypto_call(call, roots=frozenset({"pypto"})): | |||
| 405 | return isinstance(node, ast.Name) and node.id in roots | 361 | return isinstance(node, ast.Name) and node.id in roots |
| 406 | 362 | ||
| 407 | 363 | ||
| 408 | -def _tile_producers(tree, roots): | 364 | +_is_pypto_call = is_pypto_call |
| 409 | - """Names assigned the result of a pypto call that is not a write-back. | ||
| 410 | - | ||
| 411 | - Host-side torch/numpy locals are not tiles, and a write-back produces no | ||
| 412 | - value to keep alive, so neither is counted. | ||
| 413 | - """ | ||
| 414 | - produced = set() | ||
| 415 | - for node in ast.walk(tree): | ||
| 416 | - if not isinstance(node, ast.Assign) or not isinstance(node.value, ast.Call): | ||
| 417 | - continue | ||
| 418 | - if not _is_pypto_call(node.value, roots): | ||
| 419 | - continue | ||
| 420 | - if _call_name(node.value) in WRITEBACK_CALLS: | ||
| 421 | - continue | ||
| 422 | - for t in node.targets: | ||
| 423 | - if isinstance(t, ast.Name): | ||
| 424 | - produced.add(t.id) | ||
| 425 | - return produced | ||
| 426 | 365 | ||
| 427 | 366 | ||
| 428 | -def _materializes_large_intermediate(tree): | 367 | +def _materializes_large_intermediate(tree, roots=None, writebacks=WRITEBACK_CALLS): |
| 429 | """Does the kernel hold a value it could instead recompute or not store? | 368 | """Does the kernel hold a value it could instead recompute or not store? |
| 430 | 369 | ||
| 431 | Two independent pieces of evidence, either sufficient: | 370 | Two independent pieces of evidence, either sufficient: |
| @@ -445,8 +384,8 @@ def _materializes_large_intermediate(tree): | |||
| 445 | intermediate to trade. Such a kernel used to cost a real evaluation to | 384 | intermediate to trade. Such a kernel used to cost a real evaluation to |
| 446 | discover the same thing at run time. | 385 | discover the same thing at run time. |
| 447 | """ | 386 | """ |
| 448 | - roots = pypto_roots(tree) | 387 | + roots = pypto_roots(tree) if roots is None else roots |
| 449 | - produced = _tile_producers(tree, roots) | 388 | + produced = tile_producers(tree, roots, is_call=_is_pypto_call, writebacks=writebacks) |
| 450 | loads = {} | 389 | loads = {} |
| 451 | for node in ast.walk(tree): | 390 | for node in ast.walk(tree): |
| 452 | if ( | 391 | if ( |
| @@ -462,21 +401,13 @@ def _materializes_large_intermediate(tree): | |||
| 462 | return ( | 401 | return ( |
| 463 | isinstance(node, ast.Call) | 402 | isinstance(node, ast.Call) |
| 464 | and _is_pypto_call(node, roots) | 403 | and _is_pypto_call(node, roots) |
| 465 | - and _call_name(node) in WRITEBACK_CALLS | 404 | + and _call_name(node) in writebacks |
| 466 | ) | 405 | ) |
| 467 | 406 | ||
| 468 | - writebacks = sum(1 for node in ast.walk(tree) if _is_writeback(node)) | 407 | + return sum(1 for node in ast.walk(tree) if _is_writeback(node)) > 1 |
| 469 | - return writebacks > 1 | ||
| 470 | 408 | ||
| 471 | 409 | ||
| 472 | -def _is_pypto_loop_for(node): | 410 | +def _has_nested_pypto_loop(tree, loop_for): |
| 473 | - """`for x in pypto.loop(...):` -> the loop Call, else None.""" | ||
| 474 | - if not isinstance(node, ast.For) or not isinstance(node.iter, ast.Call): | ||
| 475 | - return None | ||
| 476 | - return node.iter if _call_name(node.iter) == "loop" else None | ||
| 477 | - | ||
| 478 | - | ||
| 479 | -def _has_nested_pypto_loop(tree): | ||
| 480 | """Is there a pypto.loop with another pypto.loop inside it? | 411 | """Is there a pypto.loop with another pypto.loop inside it? |
| 481 | 412 | ||
| 482 | Necessary for any transform that folds an outer axis into an inner loop: a | 413 | Necessary for any transform that folds an outer axis into an inner loop: a |
| @@ -485,10 +416,10 @@ def _has_nested_pypto_loop(tree): | |||
| 485 | has_cube_op does. | 416 | has_cube_op does. |
| 486 | """ | 417 | """ |
| 487 | for node in ast.walk(tree): | 418 | for node in ast.walk(tree): |
| 488 | - if _is_pypto_loop_for(node) is None: | 419 | + if not loop_for(node): |
| 489 | continue | 420 | continue |
| 490 | if any( | 421 | if any( |
| 491 | - _is_pypto_loop_for(inner) is not None | 422 | + loop_for(inner) |
| 492 | for stmt in node.body | 423 | for stmt in node.body |
| 493 | for inner in ast.walk(stmt) | 424 | for inner in ast.walk(stmt) |
| 494 | ): | 425 | ): |
| @@ -496,19 +427,21 @@ def _has_nested_pypto_loop(tree): | |||
| 496 | return False | 427 | return False |
| 497 | 428 | ||
| 498 | 429 | ||
| 499 | -def _has_inkernel_layout_op(tree): | 430 | +@dataclass(frozen=True) |
| 500 | - """Does the kernel reshape / expand / transpose / concat a tile itself?""" | 431 | +class PredicateRules: |
| 501 | - roots = pypto_roots(tree) | 432 | + roots: Callable |
| 502 | - return any( | 433 | + cube_calls: set |
| 503 | - isinstance(n, ast.Call) | 434 | + broadcasts: set |
| 504 | - and _is_pypto_call(n, roots) | 435 | + writebacks: set |
| 505 | - and _call_name(n) in LAYOUT_CALLS | 436 | + is_loop: Callable |
| 506 | - for n in ast.walk(tree) | 437 | + declares_cube: Callable = None |
| 507 | - ) | ||
| 508 | 438 | ||
| 509 | 439 | ||
| 510 | -def compute(impl_path, op_dir=None): | 440 | +def compute(impl_path, op_dir=None, *, rules=None, gate=None, hw=None): |
| 511 | - """Predicate dict. Unknown values are reported as True / None (admissive).""" | 441 | + """Evaluate catalog preconditions; unreadable source leaves actions eligible.""" |
| 442 | + if gate is None: | ||
| 443 | + gate = import_module(__package__ + ".feasibility") if __package__ else feasibility | ||
| 444 | + options = {"hw": hw} if hw is not None else {} | ||
| 512 | try: | 445 | try: |
| 513 | src = _read_text(impl_path) | 446 | src = _read_text(impl_path) |
| 514 | tree = ast.parse(src) | 447 | tree = ast.parse(src) |
| @@ -532,14 +465,26 @@ def compute(impl_path, op_dir=None): | |||
| 532 | "determined": False, | 465 | "determined": False, |
| 533 | } | 466 | } |
| 534 | 467 | ||
| 535 | - calls = pypto_calls(tree) | 468 | + if rules is None: |
| 469 | + rules = PredicateRules(pypto_roots, CUBE_CALLS, BROADCAST_CALLS, WRITEBACK_CALLS, | ||
| 470 | + lambda call, roots: _call_name(call) == "loop") | ||
| 471 | + roots = rules.roots(tree) | ||
| 472 | + calls = pypto_calls(tree, roots) | ||
| 473 | + | ||
| 474 | + def chunk_loop(call): | ||
| 475 | + return rules.is_loop(call, roots) and chunk_shape(call) | ||
| 476 | + | ||
| 477 | + def loop_for(node): | ||
| 478 | + return (isinstance(node, ast.For) and isinstance(node.iter, ast.Call) | ||
| 479 | + and rules.is_loop(node.iter, roots)) | ||
| 480 | + | ||
| 536 | return { | 481 | return { |
| 537 | - "has_cube_op": bool(calls & CUBE_CALLS), | 482 | + "has_cube_op": bool(calls & rules.cube_calls) or bool(rules.declares_cube and rules.declares_cube(src)), |
| 538 | - "has_broadcast": bool(calls & BROADCAST_CALLS), | 483 | + "has_broadcast": bool(calls & rules.broadcasts), |
| 539 | - "has_chunked_scan": _has_chunked_scan(tree, src), | 484 | + "has_chunked_scan": _chunk_constant(tree, chunk_loop) and _loop_carried_dependency(tree), |
| 540 | - "has_inkernel_layout_op": _has_inkernel_layout_op(tree), | 485 | + "has_inkernel_layout_op": bool(calls & LAYOUT_CALLS), |
| 541 | - "has_nested_pypto_loop": _has_nested_pypto_loop(tree), | 486 | + "has_nested_pypto_loop": _has_nested_pypto_loop(tree, loop_for), |
| 542 | - "materializes_large_intermediate": _materializes_large_intermediate(tree), | 487 | + "materializes_large_intermediate": _materializes_large_intermediate(tree, roots, rules.writebacks), |
| 543 | "module_count": _module_count(op_dir), | 488 | "module_count": _module_count(op_dir), |
| 544 | # How much of the unified buffer the vector tiles are estimated to hold. | 489 | # How much of the unified buffer the vector tiles are estimated to hold. |
| 545 | # Unlike the booleans above this is a ratio, and unlike everything the | 490 | # Unlike the booleans above this is a ratio, and unlike everything the |
| @@ -547,11 +492,11 @@ def compute(impl_path, op_dir=None): | |||
| 547 | # four times smaller than the buffer affords costs latency on every | 492 | # four times smaller than the buffer affords costs latency on every |
| 548 | # iteration and says nothing about itself in a trace: the kernel is | 493 | # iteration and says nothing about itself in a trace: the kernel is |
| 549 | # simply, quietly, slow. None when it cannot be estimated. | 494 | # simply, quietly, slow. None when it cannot be estimated. |
| 550 | - "ub_occupancy": feasibility.ub_occupancy(impl_path), | 495 | + "ub_occupancy": gate.ub_occupancy(impl_path, **options), |
| 551 | # The cube counterpart, over L1 rather than the unified buffer. None for | 496 | # The cube counterpart, over L1 rather than the unified buffer. None for |
| 552 | # a kernel with no matmul, which is the honest answer: a vector operator | 497 | # a kernel with no matmul, which is the honest answer: a vector operator |
| 553 | # has no L1 symptom rather than a bad one. | 498 | # has no L1 symptom rather than a bad one. |
| 554 | - "l1_occupancy": feasibility.l1_occupancy(impl_path), | 499 | + "l1_occupancy": gate.l1_occupancy(impl_path, **options), |
| 555 | "determined": True, | 500 | "determined": True, |
| 556 | } | 501 | } |
| 557 | 502 | ||
| @@ -587,5 +532,43 @@ def main(): | |||
| 587 | jsonio.emit(compute(a.impl, a.op_dir or os.path.dirname(a.impl)), indent=2) | 532 | jsonio.emit(compute(a.impl, a.op_dir or os.path.dirname(a.impl)), indent=2) |
| 588 | 533 | ||
| 589 | 534 | ||
| 535 | +def chunk_shape(node): | ||
| 536 | + """Detect chunk naming or a symbolic/non-unit forward step.""" | ||
| 537 | + for kw in node.keywords or []: | ||
| 538 | + if kw.arg == "name" and isinstance(kw.value, ast.Constant): | ||
| 539 | + if re.search(r"chunk|_bt\b|\bbt\b", str(kw.value.value), re.I): | ||
| 540 | + return True | ||
| 541 | + if len(node.args) < 3: | ||
| 542 | + return False | ||
| 543 | + # A SYMBOL, or an integer other than 1. Every real chunk step in this repo is | ||
| 544 | + # a name (`l`, `L`, `params.token_tile`); requiring one rather than "anything | ||
| 545 | + # but 1" keeps out `pypto.loop(n, 0, -1)`, which is reverse iteration and | ||
| 546 | + # parses as a UnaryOp rather than a Constant. | ||
| 547 | + step = node.args[2] | ||
| 548 | + named_step = isinstance(step, (ast.Name, ast.Attribute)) | ||
| 549 | + literal_step = isinstance(step, ast.Constant) and isinstance(step.value, int) | ||
| 550 | + return bool(named_step or (literal_step and step.value != 1)) | ||
| 551 | + | ||
| 552 | + | ||
| 553 | +def tile_producers(tree, roots, *, is_call, writebacks): | ||
| 554 | + """Names assigned the result of a pypto call that is not a write-back. | ||
| 555 | + | ||
| 556 | + Host-side torch/numpy locals are not tiles, and a write-back produces no | ||
| 557 | + value to keep alive, so neither is counted. | ||
| 558 | + """ | ||
| 559 | + produced = set() | ||
| 560 | + for node in ast.walk(tree): | ||
| 561 | + if not isinstance(node, ast.Assign) or not isinstance(node.value, ast.Call): | ||
| 562 | + continue | ||
| 563 | + if not is_call(node.value, roots): | ||
| 564 | + continue | ||
| 565 | + if _call_name(node.value) in writebacks: | ||
| 566 | + continue | ||
| 567 | + for t in node.targets: | ||
| 568 | + if isinstance(t, ast.Name): | ||
| 569 | + produced.add(t.id) | ||
| 570 | + return produced | ||
| 571 | + | ||
| 572 | + | ||
| 590 | if __name__ == "__main__": | 573 | if __name__ == "__main__": |
| 591 | main() | 574 | main() |
| @@ -21,26 +21,39 @@ taking on each other's dependencies. | |||
| 21 | import ast | 21 | import ast |
| 22 | 22 | ||
| 23 | 23 | ||
| 24 | -def _pypto_aliases(node): | 24 | +def pypto_roots(tree, *, packages=("pypto",), seeds=("pypto",), include_from=False): |
| 25 | - """The names one `import pypto ...` statement binds to the pypto module.""" | 25 | + """Names bound by DSL imports, including any aliases conventional for this dialect.""" |
| 26 | - out = set() | 26 | + roots = set(seeds) |
| 27 | - for alias in node.names: | ||
| 28 | - if alias.name == "pypto" or alias.name.startswith("pypto."): | ||
| 29 | - out.add((alias.asname or alias.name).split(".")[0]) | ||
| 30 | - return out | ||
| 31 | - | ||
| 32 | - | ||
| 33 | -def pypto_roots(tree): | ||
| 34 | - """Names bound to the pypto module in this file, `pypto` always among them. | ||
| 35 | - | ||
| 36 | - `import pypto as pp` is legal Python and kernels are written that way, so a | ||
| 37 | - boundary test hard-coded to the literal `pypto` would answer "not pypto" for | ||
| 38 | - an aliased kernel. That is the opposite error from counting the wrapper and | ||
| 39 | - just as wrong: it would hold every cube and broadcast action on a kernel that | ||
| 40 | - has them. | ||
| 41 | - """ | ||
| 42 | - roots = {"pypto"} | ||
| 43 | for node in ast.walk(tree): | 27 | for node in ast.walk(tree): |
| 44 | if isinstance(node, ast.Import): | 28 | if isinstance(node, ast.Import): |
| 45 | - roots |= _pypto_aliases(node) | 29 | + names = (alias for alias in node.names if alias.name.split(".")[0] in packages) |
| 30 | + elif include_from and isinstance(node, ast.ImportFrom) and (node.module or "").split(".")[0] in packages: | ||
| 31 | + names = node.names | ||
| 32 | + else: | ||
| 33 | + continue | ||
| 34 | + roots.update((alias.asname or alias.name).split(".")[0] for alias in names) | ||
| 46 | return frozenset(roots) | 35 | return frozenset(roots) |
| 36 | + | ||
| 37 | + | ||
| 38 | +def parent_map(tree): | ||
| 39 | + """Index an AST by child node, including nodes inside nested definitions.""" | ||
| 40 | + return {child: node for node in ast.walk(tree) for child in ast.iter_child_nodes(node)} | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +def function_name(node): | ||
| 44 | + if isinstance(node, ast.Attribute): | ||
| 45 | + return node.attr | ||
| 46 | + if isinstance(node, ast.Name): | ||
| 47 | + return node.id | ||
| 48 | + return None | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def jit_decorators(fn): | ||
| 52 | + for decorator in getattr(fn, "decorator_list", ()): | ||
| 53 | + target = decorator.func if isinstance(decorator, ast.Call) else decorator | ||
| 54 | + if function_name(target) == "jit": | ||
| 55 | + yield decorator | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +def keyword_value(call, name): | ||
| 59 | + return next((kw.value for kw in call.keywords if kw.arg == name), None) | ||
| @@ -0,0 +1,84 @@ | |||
| 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 | +"""Host-only CLI frontend for the registered-backend campaign test.""" | ||
| 10 | +import shutil | ||
| 11 | +import statistics | ||
| 12 | +import sys | ||
| 13 | +from pathlib import Path | ||
| 14 | + | ||
| 15 | +SCRIPTS = Path(__file__).resolve().parents[1] | ||
| 16 | +sys.path.insert(0, str(SCRIPTS)) | ||
| 17 | +from panko import backend | ||
| 18 | +import feasibility | ||
| 19 | +import predicates | ||
| 20 | + | ||
| 21 | +catalog = str(SCRIPTS.parent / "references/action_catalog.json") | ||
| 22 | +defaults = {"bayesian_optimization_tile_search": False, "success_stop": False} | ||
[P2] Cover default INIT and sampled Pareto records in the registered frontend The registered test frontend crashes on two ordinary CLI paths. Please implement the two hooks in this test frontend and exercise these paths in the end-to-end contract test. The existing test passes ![]() ![]() | |||
| 23 | +default_reference = (1.0, "no_target:1us") | ||
| 24 | +EXPORT_OUTCOMES = False | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def bayesian(): | ||
| 28 | + import bayesian_optimization | ||
| 29 | + return bayesian_optimization | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def revision(): | ||
| 33 | + return "host-test" | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def state_metadata(args): | ||
| 37 | + return {"backend": "registered-host"} | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +def verify_initialization(args, state): | ||
| 41 | + if state.get("backend") != "registered-host": | ||
| 42 | + raise ValueError("Expected the registered-host backend after initialization") | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +def wrapper_signature(source): | ||
| 46 | + return source.split("@pypto.frontend.jit()", 1)[0] | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +def debug_options_signature(source): | ||
| 50 | + return None | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +def tile_constants(state, path, source): | ||
| 54 | + return {} | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +def entry_reads(entry): | ||
| 58 | + samples = entry.get("samples") or [] | ||
| 59 | + return list(entry.get("reads") or ([statistics.median(samples)] if samples else [])) | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +def write_source(path, source): | ||
| 63 | + Path(path).write_bytes(source.encode("utf-8")) | ||
| 64 | + | ||
| 65 | + | ||
| 66 | +export_source = shutil.copyfile | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def reading_interval(xs, ys, alpha=None): | ||
| 70 | + from panko.measurement import bootstrap_speedup | ||
| 71 | + return bootstrap_speedup(xs, ys, alpha=alpha) | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +def verification_policy(): | ||
| 75 | + from panko.delivery import VerificationPolicy | ||
| 76 | + from panko.state import file_hash | ||
| 77 | + return VerificationPolicy(warmup=3, readings=lambda arm: arm.get("samples", []), interval=reading_interval, | ||
| 78 | + matches=lambda op_dir, path, expected: file_hash(path) == expected) | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +if __name__ == "__main__": | ||
| 82 | + backend.register(sys.modules[__name__]) | ||
| 83 | + import panko_harness | ||
| 84 | + panko_harness.main() | ||
| @@ -72,6 +72,16 @@ class PointTest(unittest.TestCase): | |||
| 72 | st = self._st([("a" * 64, 90.0, None), ("b" * 64, 90.0, 1000)]) | 72 | st = self._st([("a" * 64, 90.0, None), ("b" * 64, 90.0, 1000)]) |
| 73 | self.assertEqual(self._pick(st), "b" * 64) | 73 | self.assertEqual(self._pick(st), "b" * 64) |
| 74 | 74 | ||
| 75 | + def test_faster_incomplete_measurement_cannot_outrank_measured_zero_workspace(self): | ||
| 76 | + fast, complete = "a" * 64, "b" * 64 | ||
| 77 | + st = self._st([(fast, 70, 0), (complete, 80, 0)]) | ||
| 78 | + st["eval_cache"][complete]["m"]["workspace_state"] = "zero" | ||
| 79 | + for metrics in ({"workspace_state": "unknown", "workspace_b": 0}, | ||
| 80 | + {"workspace_state": "measured", "workspace_b": float("nan")}): | ||
| 81 | + with self.subTest(metrics=metrics): | ||
| 82 | + st["eval_cache"][fast]["m"] = metrics | ||
| 83 | + self.assertEqual(self._pick(st), complete) | ||
| 84 | + | ||
| 75 | def test_nothing_deliverable_is_no_point(self): | 85 | def test_nothing_deliverable_is_no_point(self): |
| 76 | st = self._st([], on_disk=set()) | 86 | st = self._st([], on_disk=set()) |
| 77 | h, detail = harness.delivery_point(st, str(self.op_dir)) | 87 | h, detail = harness.delivery_point(st, str(self.op_dir)) |
| @@ -26,15 +26,20 @@ The way to settle a pair that matters is more readings of the same program -- | |||
| 26 | `record --remeasure`, which is not charged, because `eval_budget` counts | 26 | `record --remeasure`, which is not charged, because `eval_budget` counts |
| 27 | distinct programs measured. | 27 | distinct programs measured. |
| 28 | """ | 28 | """ |
| 29 | +import hashlib | ||
| 29 | import json | 30 | import json |
| 30 | import sys | 31 | import sys |
| 31 | import tempfile | 32 | import tempfile |
| 32 | import unittest | 33 | import unittest |
| 34 | +from unittest.mock import patch | ||
| 33 | from types import SimpleNamespace | 35 | from types import SimpleNamespace |
| 34 | from pathlib import Path | 36 | from pathlib import Path |
| 35 | 37 | ||
| 36 | sys.path.insert(0, str(Path(__file__).parents[2])) | 38 | sys.path.insert(0, str(Path(__file__).parents[2])) |
| 37 | -from _support import CHIP_ARGS, DEMO_KERNEL as KERNEL, file_hash, harness, new_op_dir, read_state, run_cli # noqa: E402 | 39 | +from _support import ( # noqa: E402 |
| 40 | + CHIP_ARGS, DEMO_KERNEL as KERNEL, file_hash, harness, init_argv, new_op_dir, | ||
| 41 | + read_state, record_argv, run_cli, | ||
| 42 | +) | ||
| 38 | 43 | ||
| 39 | LW = {"objectives": ["aicore_e2e", "workspace"]} | 44 | LW = {"objectives": ["aicore_e2e", "workspace"]} |
| 40 | OBJS = harness.parse_objectives(LW) | 45 | OBJS = harness.parse_objectives(LW) |
| @@ -163,7 +168,8 @@ class BlockSamplesTest(unittest.TestCase): | |||
| 163 | a = SimpleNamespace(parent="u1", op_dir=str(op_dir)) | 168 | a = SimpleNamespace(parent="u1", op_dir=str(op_dir)) |
| 164 | ctx = {"faults": [], "trials": [], "meter": {"device_trials": 0}, | 169 | ctx = {"faults": [], "trials": [], "meter": {"device_trials": 0}, |
| 165 | "winners": {}, "base_src": KERNEL} | 170 | "winners": {}, "base_src": KERNEL} |
| 166 | - harness.block_recorder(a, st, ctx)( | 171 | + record = harness.block_recorder(a, st, ctx) |
| 172 | + record( | ||
| 167 | {"status": "ok", | 173 | {"status": "ok", |
| 168 | # What the trial was RANKED on, which is `p`. | 174 | # What the trial was RANKED on, which is `p`. |
| 169 | "objective_us": 90.0, | 175 | "objective_us": 90.0, |
| @@ -174,6 +180,73 @@ class BlockSamplesTest(unittest.TestCase): | |||
| 174 | self.assertEqual(entry["samples"], [89.0, 90.0, 91.0]) | 180 | self.assertEqual(entry["samples"], [89.0, 90.0, 91.0]) |
| 175 | self.assertEqual(st["archive"][0]["samples"], [89.0, 90.0, 91.0], | 181 | self.assertEqual(st["archive"][0]["samples"], [89.0, 90.0, 91.0], |
| 176 | "and they reach the point the front judges") | 182 | "and they reach the point the front judges") |
| 183 | + record({"status": "ok", "objective_us": 110.0, "config": {"vec#0": {"d0": 16, "d1": 128}}, | ||
| 184 | + "metrics": {"workspace_b": 1 << 19, "workspace_state": "measured"}}) | ||
| 185 | + self.assertEqual(len(st["archive"]), 2) | ||
| 186 | + for point in st["archive"]: | ||
| 187 | + h = point["code_hash"] | ||
| 188 | + self.assertEqual(file_hash(Path(harness.npath(str(op_dir), h))), h) | ||
| 189 | + | ||
| 190 | + def test_tile_snapshots_follow_retention_setting(self): | ||
| 191 | + for keep_all in (False, True): | ||
| 192 | + with self.subTest(snapshot_all_candidates=keep_all): | ||
| 193 | + kernel = new_op_dir(self, KERNEL) | ||
| 194 | + config = {"objectives": ["aicore_e2e"], "snapshot_all_candidates": keep_all} | ||
| 195 | + args = init_argv(self.op_dir, kernel, *CHIP_ARGS, "--preopt-hash", self.pre, | ||
| 196 | + "--config", json.dumps(config)) | ||
| 197 | + reply, status = run_cli(*args) | ||
| 198 | + self.assertEqual(status, 0, reply) | ||
| 199 | + st = read_state(self.op_dir) | ||
| 200 | + ctx = {"base_src": KERNEL, "op_file": kernel, "meter": {"device_trials": 0}, | ||
| 201 | + "trials": [], "winners": {}} | ||
| 202 | + record = harness.block_recorder(SimpleNamespace(parent="u1", op_dir=self.op_dir), st, ctx) | ||
| 203 | + tiles = {us: {"vec#0": {"d0": dim, "d1": 128}} for us, dim in ((90, 32), (80, 16), (95, 8))} | ||
| 204 | + for latency, tile in tiles.items(): | ||
| 205 | + record({"status": "ok", "objective_us": latency, "config": tile}) | ||
| 206 | + self.assertEqual(len(ctx["winners"]), len(tiles)) | ||
| 207 | + winner, = st["archive"] | ||
| 208 | + self.assertEqual(winner["aicore_e2e_us"], 80) | ||
| 209 | + for digest in ctx["winners"]: | ||
| 210 | + self.assertEqual(Path(harness.npath(self.op_dir, digest)).exists(), keep_all) | ||
| 211 | + harness.block_apply_winner(st, ctx, {"best_config": tiles[80]}) | ||
| 212 | + digest = file_hash(kernel) | ||
| 213 | + self.assertEqual(digest, winner["code_hash"]) | ||
| 214 | + harness.save(self.op_dir, st) | ||
| 215 | + reply, status = run_cli(*record_argv(self.op_dir, digest, "80")) | ||
| 216 | + self.assertEqual(status, 0, reply) | ||
| 217 | + restored = self.op_dir / "restored.py" | ||
| 218 | + self.assertTrue(harness.restore(self.op_dir, restored, digest)) | ||
| 219 | + self.assertEqual(file_hash(restored), digest) | ||
| 220 | + | ||
| 221 | + def test_failed_tile_snapshot_preserves_completed_trials(self): | ||
| 222 | + kernel = new_op_dir(self, KERNEL) | ||
| 223 | + config = {"objectives": ["aicore_e2e"], "bayesian_optimization_tile_search": True} | ||
| 224 | + reply, status = run_cli(*init_argv(self.op_dir, kernel, *CHIP_ARGS, "--preopt-hash", | ||
| 225 | + self.pre, "--config", json.dumps(config))) | ||
| 226 | + self.assertEqual(status, 0, reply) | ||
| 227 | + shapes = (32, 16) | ||
| 228 | + digests = [hashlib.sha256(KERNEL.replace("64, 128", f"{dim}, 128").encode()).hexdigest() | ||
| 229 | + for dim in shapes] | ||
| 230 | + Path(harness.npath(self.op_dir, digests[0])).mkdir() | ||
| 231 | + | ||
| 232 | + def measure_trials(filename, evaluator, hw, options): | ||
| 233 | + for dim, latency in zip(shapes, (600, 550)): | ||
| 234 | + options.on_trial({"status": "ok", "objective_us": latency, | ||
| 235 | + "config": {"vec#0": {"d0": dim, "d1": 128}}}) | ||
| 236 | + return {"n_trials": 2, "n_feasible": 2, "best_was_incumbent": True} | ||
| 237 | + | ||
| 238 | + args = SimpleNamespace(op_dir=str(self.op_dir), parent="u1", reason="", live_tiles=0, | ||
| 239 | + max_trials=2, test_command="true", lint_root=None) | ||
| 240 | + with patch("bayesian_optimization.block.run", side_effect=measure_trials): | ||
| 241 | + harness.cmd_block(args) | ||
| 242 | + state = read_state(self.op_dir) | ||
| 243 | + self.assertEqual(state["progress"]["snapshot_misses"], 1) | ||
| 244 | + self.assertEqual(state["progress"]["evals_used"], 3) | ||
| 245 | + saved, = state["blocks"] | ||
| 246 | + self.assertEqual(saved["charged_now"], 2) | ||
| 247 | + self.assertEqual([t["objective_us"] for t in saved["trials"]], [600, 550]) | ||
| 248 | + self.assertEqual([state["eval_cache"][h]["p"] for h in digests], [600, 550]) | ||
| 249 | + self.assertEqual(file_hash(Path(harness.npath(self.op_dir, digests[1]))), digests[1]) | ||
| 177 | 250 | ||
| 178 | def test_promoting_the_winner_does_not_destroy_its_readings(self): | 251 | def test_promoting_the_winner_does_not_destroy_its_readings(self): |
| 179 | """The winner is promoted by a `record` with no `--samples`. | 252 | """The winner is promoted by a `record` with no `--samples`. |
| @@ -289,7 +289,7 @@ class TestOneClock(unittest.TestCase): | |||
| 289 | self.assertNotIn("current_latency=st[", src) | 289 | self.assertNotIn("current_latency=st[", src) |
| 290 | self.assertNotIn("current_latency=(st[", src) | 290 | self.assertNotIn("current_latency=(st[", src) |
| 291 | self.assertEqual(src.count('current_latency=incumbent_latency(st, ctx["base_src"])'), 1) | 291 | self.assertEqual(src.count('current_latency=incumbent_latency(st, ctx["base_src"])'), 1) |
| 292 | - self.assertEqual(src.count("current_latency=incumbent_latency(st, src)"), 1) | 292 | + self.assertEqual(src.count("current_latency=incumbent_latency(st, source_bytes)"), 1) |
| 293 | 293 | ||
| 294 | 294 | ||
| 295 | class _GrantKnobs(NamedTuple): | 295 | class _GrantKnobs(NamedTuple): |
| @@ -28,6 +28,7 @@ import hashlib | |||
| 28 | import sys | 28 | import sys |
| 29 | import tempfile | 29 | import tempfile |
| 30 | import unittest | 30 | import unittest |
| 31 | +from unittest.mock import patch | ||
| 31 | from pathlib import Path | 32 | from pathlib import Path |
| 32 | 33 | ||
| 33 | sys.path.insert(0, str(Path(__file__).parents[2])) | 34 | sys.path.insert(0, str(Path(__file__).parents[2])) |
| @@ -77,6 +78,18 @@ class SeedIncumbentTest(unittest.TestCase): | |||
| 77 | self.assertEqual(self._pending(st), "current") | 78 | self.assertEqual(self._pending(st), "current") |
| 78 | self.assertFalse(res.get("applied"), "the current config is what is on disk") | 79 | self.assertFalse(res.get("applied"), "the current config is what is on disk") |
| 79 | 80 | ||
| 81 | + def test_unmeasured_registered_incumbent_keeps_staged_crlf_identity(self): | ||
| 82 | + import _registered_backend | ||
| 83 | + | ||
| 84 | + original = KERNEL.replace("\n", "\r\n").encode() | ||
| 85 | + self.f.write_bytes(original) | ||
| 86 | + with patch("panko.backend.current", return_value=_registered_backend): | ||
| 87 | + proposal = self._propose(self._state({})) | ||
| 88 | + self.assertTrue(proposal["requires_measurement"]) | ||
| 89 | + self.assertEqual(proposal["sites"], 0) | ||
| 90 | + self.assertEqual(proposal["code_hash"], hashlib.sha256(original).hexdigest()) | ||
| 91 | + self.assertEqual(self.f.read_bytes(), original) | ||
| 92 | + | ||
| 80 | def test_an_incorrect_measurement_is_not_an_incumbent(self): | 93 | def test_an_incorrect_measurement_is_not_an_incumbent(self): |
| 81 | st = self._state({self.base: {"s": 0, "p": FRONT_BASE_US, "m": {}}, | 94 | st = self._state({self.base: {"s": 0, "p": FRONT_BASE_US, "m": {}}, |
| 82 | "a" * 64: {"s": 1, "p": GLOBAL_BEST_US, "m": {}}}) | 95 | "a" * 64: {"s": 1, "p": GLOBAL_BEST_US, "m": {}}}) |
| @@ -87,6 +87,19 @@ class OneEnvelopeTest(unittest.TestCase): | |||
| 87 | _, domain = bayesian.block.hw_for(str(self.op_file), None, env) | 87 | _, domain = bayesian.block.hw_for(str(self.op_file), None, env) |
| 88 | self.assertEqual(domain.get("ub_bytes"), 248 * 1024) | 88 | self.assertEqual(domain.get("ub_bytes"), 248 * 1024) |
| 89 | 89 | ||
| 90 | + def test_vector_seed_uses_hardware_capacity_without_a_domain(self): | ||
| 91 | + tile = {"vec#0": {"d0": 16, "d1": 32}} | ||
| 92 | + hw = bayesian.space.HW(ub_budget_kb=64, dtype_bytes=4) | ||
| 93 | + self.assertEqual(bayesian.seed.features(tile, hw)["vec#0.ub"], 2048 / 65536) | ||
| 94 | + domain = {"ub_bytes": 32768} | ||
| 95 | + self.assertEqual(bayesian.seed.features(tile, hw, domain)["vec#0.ub"], 2048 / 32768) | ||
| 96 | + | ||
| 97 | + def test_vector_seed_omits_unknown_occupancy_but_keeps_trip_count(self): | ||
| 98 | + tile = {"vec#0": {"d0": 16, "d1": 32}} | ||
| 99 | + features = bayesian.seed.features(tile, bayesian.space.HW(), {"capacity_elems": 1024}) | ||
| 100 | + self.assertNotIn("vec#0.ub", features) | ||
| 101 | + self.assertEqual(features["vec#0.trips"], 2) | ||
| 102 | + | ||
| 90 | def test_a_run_carries_its_own_envelope(self): | 103 | def test_a_run_carries_its_own_envelope(self): |
| 91 | """A resumed campaign keeps validating against what it started with.""" | 104 | """A resumed campaign keeps validating against what it started with.""" |
| 92 | env = harness.chip_envelope({"chip_envelope": {"ub_kb": 248, "l0c_kb": 256}}) | 105 | env = harness.chip_envelope({"chip_envelope": {"ub_kb": 248, "l0c_kb": 256}}) |
| @@ -225,8 +238,8 @@ class ShadowedCallsRunTest(unittest.TestCase): | |||
| 225 | 238 | ||
| 226 | def test_hw_for_runs(self): | 239 | def test_hw_for_runs(self): |
| 227 | hw, domain = bayesian.block.hw_for(str(self.op_file)) | 240 | hw, domain = bayesian.block.hw_for(str(self.op_file)) |
| 228 | - self.assertTrue(hw.ub_budget_kb) | 241 | + self.assertEqual(hw.ub_budget_kb, 0) |
| 229 | - self.assertIsInstance(domain, dict) | 242 | + self.assertEqual(domain["ub_bytes"], 0) |
| 230 | 243 | ||
| 231 | def test_memory_key_runs(self): | 244 | def test_memory_key_runs(self): |
| 232 | _, domain = bayesian.block.hw_for(str(self.op_file)) | 245 | _, domain = bayesian.block.hw_for(str(self.op_file)) |
| @@ -250,6 +250,12 @@ class InitResolutionTest(unittest.TestCase): | |||
| 250 | self.assertTrue(st["chip_envelope"]["source"].endswith(f"{SOC_A}.ini")) | 250 | self.assertTrue(st["chip_envelope"]["source"].endswith(f"{SOC_A}.ini")) |
| 251 | self.assertEqual(st["chip_envelope"]["soc"], SOC_A) | 251 | self.assertEqual(st["chip_envelope"]["soc"], SOC_A) |
| 252 | 252 | ||
| 253 | + def test_small_ub_sets_the_domain_and_action_occupancy(self): | ||
| 254 | + self._check_search_capacity(SOC_A, 32, 0.5) | ||
| 255 | + | ||
| 256 | + def test_large_ub_sets_the_domain_and_action_occupancy(self): | ||
| 257 | + self._check_search_capacity(SOC_C, 64, 0.25) | ||
| 258 | + | ||
| 253 | def test_an_explicit_envelope_is_recorded_as_explicit(self): | 259 | def test_an_explicit_envelope_is_recorded_as_explicit(self): |
| 254 | """So a report cannot read as derived when the numbers were supplied.""" | 260 | """So a report cannot read as derived when the numbers were supplied.""" |
| 255 | res, rc = self._init( | 261 | res, rc = self._init( |
| @@ -263,6 +269,15 @@ class InitResolutionTest(unittest.TestCase): | |||
| 263 | self.assertEqual(rc, 3) | 269 | self.assertEqual(rc, 3) |
| 264 | self.assertIn("missing", res["reason"]) | 270 | self.assertIn("missing", res["reason"]) |
| 265 | 271 | ||
| 272 | + def _check_search_capacity(self, soc, kb, occupancy): | ||
| 273 | + (self.op_dir / "demo_impl.py").write_text(KERNEL.replace("64, 128", "32, 128")) | ||
| 274 | + result, rc = self._init({"ASCEND_TOOLKIT_HOME": str(self.root / "cann"), "PANKO_SOC_NAME": soc}) | ||
| 275 | + self.assertEqual(rc, 0, result) | ||
| 276 | + state = read_state(self.op_dir) | ||
| 277 | + self.assertEqual(state["domain_fingerprint"]["ub_bytes"], kb * KB) | ||
| 278 | + self.assertEqual(state["predicates"]["ub_occupancy"], occupancy) | ||
| 279 | + self.assertEqual("occupancy" in result["seeded_symptoms"], occupancy < 0.5) | ||
| 280 | + | ||
| 266 | def _init(self, env=None, extra=()): | 281 | def _init(self, env=None, extra=()): |
| 267 | # The real environment minus anything that would resolve a chip for us, | 282 | # The real environment minus anything that would resolve a chip for us, |
| 268 | # so the CANN variables are the only thing under test. A stripped env | 283 | # so the CANN variables are the only thing under test. A stripped env |
| @@ -0,0 +1,428 @@ | |||
| 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 | +"""Adapter contracts exercised without installing a second frontend.""" | ||
| 10 | +import hashlib | ||
| 11 | +import json | ||
| 12 | +import sys | ||
| 13 | +import tempfile | ||
| 14 | +import unittest | ||
| 15 | +from dataclasses import replace | ||
| 16 | +from functools import partial | ||
| 17 | +from pathlib import Path | ||
| 18 | +from unittest.mock import Mock, patch | ||
| 19 | + | ||
| 20 | +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | ||
| 21 | +from panko import config, delivery | ||
| 22 | +import panko_harness | ||
| 23 | +from bayesian_optimization import apply, driver, evaluator, space | ||
| 24 | +import _registered_backend | ||
| 25 | +import _support | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +class FrontendContractTest(unittest.TestCase): | ||
| 29 | + def test_remeasurement_keeps_one_backend_reading_per_acquisition(self): | ||
| 30 | + kernel = _support.new_op_dir(self, _support.DEMO_KERNEL) | ||
| 31 | + with patch.object(_support, "HARNESS", Path(__file__).with_name("_registered_backend.py")): | ||
| 32 | + def cli(*args): | ||
| 33 | + reply, rc = _support.run_cli(*args, "--op-dir", str(self.op_dir)) | ||
| 34 | + self.assertEqual(rc, 0, reply) | ||
| 35 | + return reply | ||
| 36 | + | ||
| 37 | + cli("init", "--op", "demo", "--op-file", str(kernel), "--p-ref", "50", | ||
| 38 | + "--preopt-p", "100", "--preopt-hash", self.pre, "--preopt-samples", "99,100,101", | ||
| 39 | + *_support.INIT_ARGS) | ||
| 40 | + for _ in range(3): | ||
| 41 | + result = cli("record", "--remeasure", "--code-hash", self.pre, "--parent", "root", | ||
| 42 | + "--s", "1", "--p", "10", "--samples", "9,10,11") | ||
| 43 | + state = _support.read_state(self.op_dir) | ||
| 44 | + point, = state["archive"] | ||
| 45 | + self.assertEqual(result["aicore_e2e_us"], 10) | ||
| 46 | + self.assertEqual(point["reads"], [100, 10, 10, 10]) | ||
| 47 | + self.assertEqual(state["eval_cache"][self.pre]["reads"], point["reads"]) | ||
| 48 | + | ||
| 49 | + def test_registered_backend_restores_and_verifies_the_accepted_candidate(self): | ||
| 50 | + source = _support.DEMO_KERNEL | ||
| 51 | + kernel = _support.new_op_dir(self, source) | ||
| 52 | + baseline_bytes = source.replace("\n", "\r\n").encode("utf-8") | ||
| 53 | + kernel.write_bytes(baseline_bytes) | ||
| 54 | + self.pre = _support.file_hash(kernel) | ||
| 55 | + frontend = Path(__file__).with_name("_registered_backend.py") | ||
| 56 | + with patch.object(_support, "HARNESS", frontend): | ||
| 57 | + def cli(cmd, *args): | ||
| 58 | + reply, rc = _support.run_cli(cmd, "--op-dir", str(self.op_dir), *args) | ||
| 59 | + self.assertEqual(rc, 0, reply) | ||
| 60 | + return reply | ||
| 61 | + | ||
| 62 | + cli("init", "--op", "demo", "--op-file", str(kernel), "--preopt-samples", "99,100,101", | ||
| 63 | + "--preopt-p", "100", "--preopt-hash", self.pre, *_support.INIT_ARGS, | ||
| 64 | + "--config", json.dumps({"eval_budget": 3, "objectives": ["aicore_e2e", "workspace"]})) | ||
| 65 | + state = _support.read_state(self.op_dir) | ||
| 66 | + self.assertEqual(state["backend"], "registered-host") | ||
| 67 | + self.assertEqual((state["target"]["P_ref"], state["target"]["P_ref_via"]), | ||
| 68 | + (1.0, "no_target:1us")) | ||
| 69 | + kernel.write_bytes(b"# pending edit") | ||
| 70 | + selected = cli("select")["selected"] | ||
| 71 | + self.assertTrue(selected["restored"]) | ||
| 72 | + self.assertEqual(_support.file_hash(kernel), selected["restore_code_hash"]) | ||
| 73 | + self.assertEqual(kernel.read_bytes(), baseline_bytes) | ||
| 74 | + action = selected["id"] | ||
| 75 | + | ||
| 76 | + def record(tile, latency, workspace): | ||
| 77 | + kernel.write_text(source.replace("64, 128", tile), encoding="utf-8") | ||
| 78 | + digest = _support.file_hash(kernel) | ||
| 79 | + reply = cli("record", "--parent", action, "--code-hash", digest, | ||
| 80 | + "--s", "1", "--p", str(latency), "--workspace-b", str(workspace), | ||
| 81 | + "--samples", f"{latency - 1},{latency},{latency + 1}") | ||
| 82 | + return digest, reply | ||
| 83 | + | ||
| 84 | + winner, kept = record("128, 128", 80, 1 << 19) | ||
| 85 | + self.assertTrue(kept["improved"], kept) | ||
| 86 | + self.assertFalse(cli("stop")["stop"]) | ||
| 87 | + loser, rejected = record("32, 128", 120, 1 << 20) | ||
| 88 | + self.assertFalse(rejected["improved"], rejected) | ||
| 89 | + self.assertNotEqual(winner, loser) | ||
| 90 | + self.assertEqual(_support.file_hash(kernel), winner) | ||
| 91 | + stop = cli("stop") | ||
| 92 | + self.assertTrue(stop["stop"]) | ||
| 93 | + self.assertEqual(stop["reason"], "eval_budget") | ||
| 94 | + state = _support.read_state(self.op_dir) | ||
| 95 | + self.assertEqual(state["progress"]["evals_used"], 3) | ||
| 96 | + point, = state["archive"] | ||
| 97 | + self.assertEqual((point["code_hash"], point["reads"], point["workspace_b"]), | ||
| 98 | + (winner, [80], 1 << 19)) | ||
| 99 | + self.assertEqual(state["progress"]["delivered_code_hash"], winner) | ||
| 100 | + self.assertEqual(state["verification"]["arms"]["delivered"]["code_hash"], winner) | ||
| 101 | + self.assertIn("warmup=3,", state["verification"]["protocol"]) | ||
| 102 | + for arm in ("preopt", "delivered", "delivered", "preopt"): | ||
| 103 | + stage = cli("verify") | ||
| 104 | + self.assertEqual(stage["arm"], arm) | ||
| 105 | + self.assertIn("--warmup 3 --runs 15 --agg median", stage["measure"]) | ||
| 106 | + baseline = arm == "preopt" | ||
| 107 | + self.assertEqual(_support.file_hash(kernel), self.pre if baseline else winner) | ||
| 108 | + samples = ["100" if baseline else "80"] * stage["runs"] | ||
| 109 | + result = cli("verify", "--samples", ",".join(samples)) | ||
| 110 | + self.assertEqual(result["status"], "confirmed") | ||
| 111 | + self.assertEqual(_support.file_hash(kernel), winner) | ||
| 112 | + | ||
| 113 | + def test_stop_skips_block_snapshots_that_fail_record_gates(self): | ||
| 114 | + for error in ("objective_unmeasured", "wrapper_drift"): | ||
| 115 | + with self.subTest(error=error): | ||
| 116 | + kernel = _support.new_op_dir(self, _support.DEMO_KERNEL) | ||
| 117 | + | ||
| 118 | + def cli(cmd, *args): | ||
| 119 | + argv = [cmd, "--op-dir", str(self.op_dir), *args] | ||
| 120 | + return config.call_transition(panko_harness.main, argv) | ||
| 121 | + | ||
| 122 | + cli("init", "--op", "demo", "--op-file", str(kernel), "--p-ref", "50", | ||
| 123 | + "--preopt-p", "100", "--allow-unversioned", *_support.INIT_ARGS, | ||
| 124 | + "--config", '{"objectives":["aicore_e2e","workspace"],"eval_budget":3,"wall_clock_limit_s":0}') | ||
| 125 | + src = _support.DEMO_KERNEL.replace("64, 128", "32, 128") | ||
| 126 | + metrics = {} | ||
| 127 | + if error == "wrapper_drift": | ||
| 128 | + src += "\nHOST_WORK = 1\n" | ||
| 129 | + metrics = {"workspace_b": 0, "workspace_state": "zero"} | ||
| 130 | + kernel.write_text(src) | ||
| 131 | + with (patch.object(evaluator.RealEvaluator, "_run_test", return_value=0), | ||
| 132 | + patch.object(evaluator.RealEvaluator, "_measure", | ||
| 133 | + side_effect=[dict(metrics, p=p) for p in (80, 70)])): | ||
| 134 | + block = cli("block", "--parent", "u1", "--test-command", "true", "--max-trials", "2") | ||
| 135 | + self.assertEqual(block["device_trials"], 2, block) | ||
| 136 | + reply, rc = _support.run_cli("record", "--op-dir", str(self.op_dir), "--parent", "u1", | ||
| 137 | + "--code-hash", block["code_hash"], "--s", "1", "--p", "70", | ||
| 138 | + "--workspace-state", "zero" if metrics else "unavailable") | ||
| 139 | + self.assertNotEqual(rc, 0, reply) | ||
| 140 | + self.assertEqual(reply["error"], error) | ||
| 141 | + reply = cli("stop") | ||
| 142 | + self.assertEqual(reply["reason"], "wall_clock") | ||
| 143 | + self.assertEqual(reply["best_code_hash"], self.pre) | ||
| 144 | + self.assertEqual(kernel.read_bytes(), _support.DEMO_KERNEL.encode()) | ||
| 145 | + state = _support.read_state(self.op_dir) | ||
| 146 | + self.assertEqual([row["code_hash"] for row in state["archive"]], [self.pre]) | ||
| 147 | + trials = state["blocks"][0]["trials"] | ||
| 148 | + self.assertEqual([trial["objective_us"] for trial in trials], [80, 70]) | ||
| 149 | + self.assertIn(trials[0]["code_hash"], state["eval_cache"]) | ||
| 150 | + for trial in trials: | ||
| 151 | + snap = Path(_support.harness.npath(self.op_dir, trial["code_hash"])) | ||
| 152 | + self.assertEqual(_support.file_hash(snap), trial["code_hash"]) | ||
| 153 | + | ||
| 154 | + def test_registered_block_preserves_measured_bytes_through_stop(self): | ||
| 155 | + source = _support.DEMO_KERNEL | ||
| 156 | + kernel = _support.new_op_dir(self, source) | ||
| 157 | + staged = [] | ||
| 158 | + | ||
| 159 | + def write_crlf(path, text): | ||
| 160 | + # The extra space makes the staged candidate differ even for a CRLF base. | ||
| 161 | + text = text.replace("32, 128", "32, 128").replace("\r\n", "\n") | ||
| 162 | + Path(path).write_bytes(text.replace("\n", "\r\n").encode()) | ||
| 163 | + | ||
| 164 | + write_crlf(kernel, source) | ||
| 165 | + base = kernel.read_bytes() | ||
| 166 | + | ||
| 167 | + def measure(): | ||
| 168 | + staged.append(kernel.read_bytes()) | ||
| 169 | + return {"p": 80} | ||
| 170 | + | ||
| 171 | + def search(filename, objective, hw, options): | ||
| 172 | + tile = {"vec#0": {"d0": 32, "d1": 128}} | ||
| 173 | + self.assertEqual(objective(tile)[:2], (1, 80)) | ||
| 174 | + self.assertEqual(kernel.read_bytes(), base) | ||
| 175 | + options.on_trial({"status": "ok", "objective_us": 80, "config": tile}) | ||
| 176 | + return {"best_config": tile, "best_objective_us": 80, "n_trials": 1, "n_feasible": 1} | ||
| 177 | + | ||
| 178 | + def cli(command, *args): | ||
| 179 | + argv = [command, "--op-dir", str(self.op_dir), *args] | ||
| 180 | + return config.call_transition(panko_harness.main, argv) | ||
| 181 | + | ||
| 182 | + with (patch("panko.backend._frontend", _registered_backend), | ||
| 183 | + patch.object(_registered_backend, "write_source", side_effect=write_crlf) as writer, | ||
| 184 | + patch.object(evaluator.RealEvaluator, "_run_test", return_value=0), | ||
| 185 | + patch.object(evaluator.RealEvaluator, "_measure", side_effect=measure), | ||
| 186 | + patch("bayesian_optimization.block.run", side_effect=search)): | ||
| 187 | + cli("init", "--op", "demo", "--op-file", str(kernel), "--p-ref", "50", "--preopt-p", "100", | ||
| 188 | + "--preopt-hash", _support.file_hash(kernel), *_support.INIT_ARGS, | ||
| 189 | + "--config", '{"bayesian_optimization_tile_search":true,"eval_budget":2,"objectives":["aicore_e2e"]}') | ||
| 190 | + action = cli("select")["selected"]["id"] | ||
| 191 | + writer.reset_mock() | ||
| 192 | + block = cli("block", "--parent", action, "--test-command", "true") | ||
| 193 | + measured, = staged | ||
| 194 | + digest = hashlib.sha256(measured).hexdigest() | ||
| 195 | + self.assertIn(b"\r\n", measured) | ||
| 196 | + self.assertEqual(measured, base.replace(b"64, 128", b"32, 128")) | ||
| 197 | + self.assertTrue(writer.called) | ||
| 198 | + self.assertEqual(block["code_hash"], digest) | ||
| 199 | + saved_block, = _support.read_state(self.op_dir)["blocks"] | ||
| 200 | + self.assertEqual(saved_block["trials"][0]["code_hash"], digest) | ||
| 201 | + self.assertEqual(kernel.read_bytes(), measured) | ||
| 202 | + self.assertEqual(Path(_support.harness.npath(self.op_dir, digest)).read_bytes(), measured) | ||
| 203 | + cli("record", "--parent", action, "--code-hash", digest, "--s", "1", "--p", "80") | ||
| 204 | + kernel.write_bytes(b"# interrupted edit") | ||
| 205 | + self.assertTrue(cli("stop")["stop"]) | ||
| 206 | + self.assertEqual(kernel.read_bytes(), measured) | ||
| 207 | + | ||
| 208 | + def test_classic_tile_selection_records_latin1_kernel(self): | ||
| 209 | + kernel = _support.new_op_dir(self, _support.DEMO_KERNEL) | ||
| 210 | + header = b"# coding: latin-1\r\n# caf\xe9\r\n" | ||
| 211 | + kernel.write_bytes(header + _support.DEMO_KERNEL.replace("\n", "\r\n").encode()) | ||
| 212 | + catalog = self.op_dir / "catalog.json" | ||
| 213 | + actions = json.loads(_support.CATALOG.read_text()) | ||
| 214 | + catalog.write_text(json.dumps([a for a in actions if a["id"] == "F-10"])) | ||
| 215 | + | ||
| 216 | + def cli(*args): | ||
| 217 | + reply, rc = _support.run_cli(*args, "--op-dir", str(self.op_dir)) | ||
| 218 | + self.assertEqual(rc, 0, reply) | ||
| 219 | + return reply | ||
| 220 | + | ||
| 221 | + cli("init", "--op", "demo", "--op-file", str(kernel), "--catalog", str(catalog), | ||
| 222 | + "--allow-unversioned", "--p-ref", "50", "--preopt-p", "100", "--preopt-hash", | ||
| 223 | + _support.file_hash(kernel), *_support.INIT_ARGS, | ||
| 224 | + "--config", '{"bayesian_optimization_tile_search":true,"eval_budget":2}') | ||
| 225 | + selection = cli("select") | ||
| 226 | + proposal = selection["bayesian_optimization"] | ||
| 227 | + self.assertTrue(proposal["applied"], proposal) | ||
| 228 | + candidate = kernel.read_bytes() | ||
| 229 | + self.assertTrue(candidate.startswith(header)) | ||
| 230 | + self.assertNotIn(b"\n", candidate.replace(b"\r\n", b"")) | ||
| 231 | + compile(candidate, str(kernel), "exec") | ||
| 232 | + digest = _support.file_hash(kernel) | ||
| 233 | + self.assertEqual(proposal["code_hash"], digest) | ||
| 234 | + cli("record", "--parent", selection["selected"]["id"], "--s", "1", "--p", "80", | ||
| 235 | + "--code-hash", digest) | ||
| 236 | + state = _support.read_state(self.op_dir) | ||
| 237 | + self.assertEqual(state["progress"]["evals_used"], 2) | ||
| 238 | + self.assertEqual(state["eval_cache"][digest]["p"], 80) | ||
| 239 | + study, = state["bayesian_optimization_studies"].values() | ||
| 240 | + self.assertEqual([t["value"] for t in study["trials"] if t["label"] == "current"], [100]) | ||
| 241 | + | ||
| 242 | + def test_registered_tile_selection_records_staged_crlf_bytes(self): | ||
| 243 | + kernel = _support.new_op_dir(self, _support.DEMO_KERNEL.replace("\n", "\r\n")) | ||
| 244 | + catalog = self.op_dir / "catalog.json" | ||
| 245 | + actions = json.loads(_support.CATALOG.read_text()) | ||
| 246 | + catalog.write_text(json.dumps([a for a in actions if a["id"] == "F-10"])) | ||
| 247 | + frontend = Path(__file__).with_name("_registered_backend.py") | ||
| 248 | + with patch.object(_support, "HARNESS", frontend): | ||
| 249 | + def cli(*args, status=0): | ||
| 250 | + reply, rc = _support.run_cli(*args, "--op-dir", str(self.op_dir)) | ||
| 251 | + self.assertEqual(rc, status, reply) | ||
| 252 | + return reply | ||
| 253 | + | ||
| 254 | + cli("init", "--op", "demo", "--op-file", str(kernel), "--catalog", str(catalog), | ||
| 255 | + "--preopt-p", "100", "--preopt-hash", self.pre, *_support.INIT_ARGS, | ||
| 256 | + "--config", '{"bayesian_optimization_tile_search":true,"eval_budget":2}') | ||
| 257 | + selection = cli("select") | ||
| 258 | + proposal = selection["bayesian_optimization"] | ||
| 259 | + self.assertTrue(proposal["applied"], proposal) | ||
| 260 | + staged = kernel.read_bytes() | ||
| 261 | + digest = _support.file_hash(kernel) | ||
| 262 | + self.assertEqual(proposal["code_hash"], digest) | ||
| 263 | + self.assertNotEqual(digest, self.pre) | ||
| 264 | + state = _support.read_state(self.op_dir) | ||
| 265 | + study, = state["bayesian_optimization_studies"].values() | ||
| 266 | + self.assertEqual([t["value"] for t in study["trials"] if t["label"] == "current"], [100]) | ||
| 267 | + record = ("record", "--parent", selection["selected"]["id"], "--s", "1", "--p", "80", "--code-hash") | ||
| 268 | + wrong = hashlib.sha256(staged.replace(b"\r\n", b"\n")).hexdigest() | ||
| 269 | + self.assertNotEqual(wrong, digest) | ||
| 270 | + refused = cli(*record, wrong, status=3) | ||
| 271 | + self.assertEqual(refused["error"], "code_hash_mismatch") | ||
| 272 | + self.assertEqual(_support.read_state(self.op_dir), state) | ||
| 273 | + self.assertTrue(cli(*record, digest)["improved"]) | ||
| 274 | + self.assertTrue(cli("stop")["stop"]) | ||
| 275 | + self.assertEqual(kernel.read_bytes(), staged) | ||
| 276 | + state = _support.read_state(self.op_dir) | ||
| 277 | + self.assertEqual(state["progress"]["delivered_code_hash"], digest) | ||
| 278 | + self.assertEqual(state["progress"]["evals_used"], 2) | ||
| 279 | + | ||
| 280 | + def test_namespaced_tile_block_runs_one_trial_with_the_default_policy(self): | ||
| 281 | + skill = Path(__file__).resolve().parents[2] | ||
| 282 | + with patch.object(sys, "path", [str(skill), *sys.path]): | ||
| 283 | + from scripts.bayesian_optimization import block, space as tile_space | ||
| 284 | + | ||
| 285 | + with tempfile.TemporaryDirectory() as directory: | ||
| 286 | + kernel = Path(directory) / "kernel.py" | ||
| 287 | + kernel.write_text("def kernel(a):\n pypto.set_vec_tile_shapes(64, 128)\n", encoding="utf-8") | ||
| 288 | + result = block.run(kernel, lambda cfg: (1, 10.0), tile_space.HW(calibrated=False), | ||
| 289 | + block.BlockOptions(max_trials=1)) | ||
| 290 | + | ||
| 291 | + self.assertEqual(result["n_trials"], 1) | ||
| 292 | + self.assertEqual(result["best_objective_us"], 10.0) | ||
| 293 | + | ||
| 294 | + def test_device_budget_charges_only_evaluator_calls_after_static_rejection(self): | ||
| 295 | + source = "def kernel(a):\n pypto.set_vec_tile_shapes(16, {})\n" | ||
| 296 | + sites = apply.tunable_sites(source.format(17)) | ||
| 297 | + seeds = [apply.current_config(source.format(width)) for width in (17, 32, 32, 64, 128)] | ||
| 298 | + opts = driver.SearchOptions(n_trials=2, warm_start=seeds, repair=False) | ||
| 299 | + policy = replace(driver.classic_search_policy(), | ||
| 300 | + optimize=partial(driver.optimize, device_budget=True)) | ||
| 301 | + calls = [] | ||
| 302 | + | ||
| 303 | + def measure(cfg): | ||
| 304 | + calls.append(cfg) | ||
| 305 | + return 1, 10.0 | ||
| 306 | + | ||
| 307 | + result = driver.run_bo(measure, sites, space.HW(calibrated=False), opts, policy=policy) | ||
| 308 | + self.assertEqual(calls, [seeds[1], seeds[3]]) | ||
| 309 | + self.assertEqual([r["status"] for r in result["history"]], | ||
| 310 | + ["infeasible_static", "ok", "duplicate_config", "ok"]) | ||
| 311 | + | ||
| 312 | + def test_device_budget_reports_exhaustion_when_all_draws_are_static_refusals(self): | ||
| 313 | + source = "def kernel(a):\n pypto.set_vec_tile_shapes(16, 17)\n" | ||
| 314 | + limit = driver.DEFAULT_FREE_RUN_LIMIT | ||
| 315 | + opts = driver.SearchOptions(n_trials=2, warm_start=[apply.current_config(source)] * (limit + 1), | ||
| 316 | + repair=False) | ||
| 317 | + policy = replace(driver.classic_search_policy(), | ||
| 318 | + optimize=partial(driver.optimize, device_budget=True), | ||
| 319 | + result=lambda study, ctx, memory, replayed: ctx["stag"]["draws_exhausted"]) | ||
| 320 | + measure = Mock(side_effect=AssertionError("static rejection reached evaluator")) | ||
| 321 | + result = driver.run_bo(measure, apply.tunable_sites(source), space.HW(calibrated=False), | ||
| 322 | + opts, policy=policy) | ||
| 323 | + measure.assert_not_called() | ||
| 324 | + self.assertEqual((result["draws"], result["device_trials"], result["budget"]), (limit, 0, 2)) | ||
| 325 | + | ||
| 326 | + def test_device_budget_stops_on_faults_and_failures_with_stagnation_disabled(self): | ||
| 327 | + opts = driver.SearchOptions(n_trials=5, fault_limit=2, failure_limit=2, | ||
| 328 | + stagnation_limit=0, startup_min_feasible=1) | ||
| 329 | + | ||
| 330 | + def device_fault(cfg): | ||
| 331 | + raise evaluator.EnvironmentFault("synthetic device fault", kind="device") | ||
| 332 | + | ||
| 333 | + sites = apply.tunable_sites("def kernel(a):\n pypto.set_vec_tile_shapes(64, 128)\n") | ||
| 334 | + hw = space.HW(calibrated=False, dtype_bytes=4) | ||
| 335 | + | ||
| 336 | + def run_device_budget(study, ctx, options): | ||
| 337 | + measure = ctx["objective"] | ||
| 338 | + | ||
| 339 | + def counted(cfg): | ||
| 340 | + ctx["state"]["device"] += 1 | ||
| 341 | + return measure(cfg) | ||
| 342 | + | ||
| 343 | + ctx["state"]["device"] = 0 | ||
| 344 | + ctx["objective"] = counted | ||
| 345 | + driver.optimize(study, ctx, options, device_budget=True, free_run_limit=lambda ctx: 32, | ||
| 346 | + exhausted=lambda *args: "draws exhausted") | ||
| 347 | + | ||
| 348 | + policy = replace(driver.classic_search_policy(), optimize=run_device_budget) | ||
| 349 | + | ||
| 350 | + for measure, attempts, reason in ( | ||
| 351 | + (device_fault, 2, "2 consecutive environment faults (device)"), | ||
| 352 | + (lambda cfg: (0, None), 2, "2 consecutive candidates the device would not run"), | ||
| 353 | + (lambda cfg: (1, 10.), 5, None), | ||
| 354 | + ): | ||
| 355 | + with self.subTest(reason=reason): | ||
| 356 | + counted = Mock(side_effect=measure, last_detail="") | ||
| 357 | + result = driver.run_bo(counted, sites, hw, opts, policy=policy) | ||
| 358 | + self.assertEqual(counted.call_count, attempts) | ||
| 359 | + self.assertEqual(result["aborted"], reason) | ||
| 360 | + self.assertFalse(result["stopped_early"]) | ||
| 361 | + | ||
| 362 | + def test_search_policy_can_project_the_same_budgeted_trials(self): | ||
| 363 | + sites = apply.tunable_sites("def kernel(a):\n pypto.set_vec_tile_shapes(64, 128)\n") | ||
| 364 | + self.assertTrue(sites) | ||
| 365 | + hw = space.HW(calibrated=False, dtype_bytes=4) | ||
| 366 | + opts = driver.SearchOptions(seed=3, n_trials=4) | ||
| 367 | + | ||
| 368 | + def objective(cfg): | ||
| 369 | + return 1, 10.0 | ||
| 370 | + | ||
| 371 | + expected = driver.run_bo(objective, sites, hw, opts) | ||
| 372 | + policy = replace(driver.classic_search_policy(), | ||
| 373 | + result=lambda study, ctx, memory, replayed: ctx["history"]) | ||
| 374 | + actual = driver.run_bo(objective, sites, hw, opts, policy=policy) | ||
| 375 | + self.assertEqual(len(actual), 4) | ||
| 376 | + self.assertEqual(actual, expected["history"]) | ||
| 377 | + | ||
| 378 | + def test_cli_extension_runs_validation_before_dispatch(self): | ||
| 379 | + calls = [] | ||
| 380 | + | ||
| 381 | + def configure(commands): | ||
| 382 | + cmd = commands.add_parser("custom") | ||
| 383 | + cmd.add_argument("--value", type=int, required=True) | ||
| 384 | + cmd.set_defaults(fn=lambda args: calls.append(("run", args.value))) | ||
| 385 | + | ||
| 386 | + panko_harness.main(["custom", "--value", "7"], configure=configure, | ||
| 387 | + before_command=lambda args: calls.append(("validate", args.value))) | ||
| 388 | + self.assertEqual(calls, [("validate", 7), ("run", 7)]) | ||
| 389 | + | ||
| 390 | + def test_refused_transition_preserves_its_reply_and_exit_code(self): | ||
| 391 | + def refuse(_): | ||
| 392 | + config.out({"refused": True}) | ||
| 393 | + raise config.Refusal(2) | ||
| 394 | + | ||
| 395 | + with self.assertRaises(config.Refusal) as caught: | ||
| 396 | + config.call_transition(refuse, None) | ||
| 397 | + self.assertEqual(caught.exception.code, 2) | ||
| 398 | + self.assertEqual(caught.exception.reply, {"refused": True}) | ||
| 399 | + self.assertEqual(config.call_transition(config.out, {"ok": True}), {"ok": True}) | ||
| 400 | + | ||
| 401 | + def test_verification_policy_schedules_the_front_when_delivery_is_baseline(self): | ||
| 402 | + state = {"nodes": {"closed": [{"code_hash": "base"}]}, | ||
| 403 | + "progress": {"delivered_code_hash": "base"}, | ||
| 404 | + "archive": [{"code_hash": h} for h in ("base", "a", "b")], | ||
| 405 | + "config": {"end_verify": True, "verify_front": True, "verify_runs": 8}} | ||
| 406 | + delivery.open_verification(state) | ||
| 407 | + self.assertEqual(state.pop("verification")["status"], "no_change") | ||
| 408 | + policy = replace(_registered_backend.verification_policy(), strict_restore=True) | ||
| 409 | + delivery.open_verification(state, policy=policy) | ||
| 410 | + record = state.get("verification") | ||
| 411 | + self.assertIsInstance(record, dict) | ||
| 412 | + self.assertEqual(record["point"], "a") | ||
| 413 | + self.assertEqual(state.get("verify_queue"), ["b"]) | ||
| 414 | + self.assertEqual(record["schedule"], ["preopt", "delivered", "delivered", "preopt"]) | ||
| 415 | + self.assertEqual(record["runs_per_step"], 4) | ||
| 416 | + self.assertEqual(record["warmup"], 3) | ||
| 417 | + delivery.next_verification(state, ".", policy=replace(policy, warmup=0)) | ||
| 418 | + self.assertEqual(state.get("verification", {}).get("warmup"), 3) | ||
| 419 | + | ||
| 420 | + def test_verify_defaults_to_one_warmup_for_legacy_state(self): | ||
| 421 | + record = {"status": "pending", "step": 0, "runs_per_step": 4, "schedule": ["preopt"], | ||
| 422 | + "arms": {"preopt": {"code_hash": "baseline"}}} | ||
| 423 | + state = {"op_file": "demo.py", "progress": {"stop_reason": "budget"}, "verification": record} | ||
| 424 | + with (patch.object(delivery, "load", return_value=state), patch.object(delivery, "restore", return_value=True), | ||
| 425 | + patch.object(delivery, "out") as emit): | ||
| 426 | + delivery.cmd_verify(Mock(op_dir=".", skip="", samples=None), | ||
| 427 | + policy=_registered_backend.verification_policy()) | ||
| 428 | + self.assertIn("--warmup 1 --runs 4", emit.call_args.args[0]["measure"]) | ||


[P3] Document the shared frontend entry points
CONTRIBUTING.mdasks for docstrings on key interfaces. Please document the required frontend hooks and registration timing onregister, the arguments and order ofconfigureandbefore_commandonpanko_harness.main, and the callback arguments and expected state mutations onTrialPolicy. A frontend author currently has to infer these contracts from the callers.