File size: 30,779 Bytes
cde594b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
#!/usr/bin/env python3
"""Train, freeze, and evaluate learned executable solver/acquisition controllers."""
from __future__ import annotations
import os
for _variable in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS"):
    os.environ[_variable] = "1"
import argparse
import copy
import hashlib
import json
import multiprocessing as mp
import platform
import sys
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
import pandas as pd
import scipy
import sklearn
from controller_core import (ACTION_NAMES, FEATURE_NAMES, TRAIN_FAMILIES, FINAL_FAMILIES,
    acquisition_features, array_digest, assess, default_classical, digest, export_policy_python, export_selector_python,
    fit_policy, fit_selector, initial_policy, padded_curve, policy_action, policy_predictions,
    random_classical, run_solver, solve_policy, tasks_for, tree_predict, without_pool)

META_SEEDS = [190101, 190102, 190103, 190104, 190105]
GENERATIONS, LABELS_PER_GENERATION, TRAIN_BUDGET, LOOKAHEAD_BUDGET = 6, 48, 64, 12
DEVELOPMENT_BUDGET, FINAL_BUDGET = 128, 128
ACQUISITION_METHODS = ["learned_acquisition", "random_acquisition", "fixed_disagreement"]
CLASSICAL_METHODS = ["tuned_bfgs", "tuned_lbfgs", "tuned_spg", "tuned_trust_sr1"]


def utc(): return datetime.now(timezone.utc).isoformat()


def file_hash(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def source_hashes():
    root = Path(__file__).resolve().parent
    return {name: file_hash(root / name) for name in ("controller_core.py", "run_controller.py")}


def dump(path, value):
    Path(path).write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")


def source_cap(train_count=12, generations=GENERATIONS, labels=LABELS_PER_GENERATION):
    return generations * (train_count * TRAIN_BUDGET + labels * len(ACTION_NAMES) * LOOKAHEAD_BUDGET)


def select_pool_index(method, selector, policy, pool, available, rng):
    if method == "random_acquisition" or selector is None:
        return int(rng.choice(available)), "random", None
    if rng.random() < .2:
        return int(rng.choice(available)), "exploration", None
    scores = []
    for index in available:
        if "acquisition_features" not in pool[index]:
            pool[index]["acquisition_features"] = acquisition_features(policy, pool[index]["features"])
        z = pool[index]["acquisition_features"]
        if method == "learned_acquisition":
            score = max(float(tree_predict(selector["tree"], z)[0]), 0.)
        elif method == "fixed_disagreement":
            # A fixed, prespecified uncertainty rule; this comparator does not learn a selector.
            score = float(z[-1] + z[-3])
        else:
            raise ValueError(method)
        scores.append(score + float(rng.uniform(0, 1e-10)))
    offset = int(np.argmax(scores))
    return int(available[offset]), "predicted_regret" if method == "learned_acquisition" else "fixed_uncertainty", float(scores[offset])


def acquisition_job(method, seed, output, pilot=False):
    output = Path(output); output.mkdir(parents=True, exist_ok=True)
    started_wall, started_cpu = time.perf_counter(), time.process_time()
    train, development = tasks_for("train", pilot), tasks_for("development", pilot)
    generations = 2 if pilot else GENERATIONS
    label_count = 12 if pilot else LABELS_PER_GENERATION
    budget = source_cap(len(train), generations, label_count)
    rng = np.random.default_rng(seed)
    policy, selector = initial_policy(), None
    initial_development = without_pool(assess(policy, development, DEVELOPMENT_BUDGET))
    checkpoints = [{"generation": 0, "policy": policy, "policy_sha256": digest(policy), "selector": None,
                    "development": initial_development, "source_calls_to_date": 0, "labels_to_date": 0}]
    feature_rows, labels, acquisition_rows, regrets, label_records = [], [], [], [], []
    source_calls = state_collection_calls = counterfactual_calls = 0
    development_calls = initial_development["calls"]
    for generation in range(1, generations + 1):
        before_policy = copy.deepcopy(policy)
        source = assess(before_policy, train, TRAIN_BUDGET, collect=True)
        pool = source.pop("pool")
        state_collection_calls += source["calls"]; source_calls += source["calls"]
        available = list(range(len(pool)))
        pool_metadata = [{"family": item["task"].family, "task_seed": item["task"].seed,
                          "dimension": item["task"].dimension, "query_prefix": item["query_prefix"],
                          "state_sha256": item["state_sha256"]} for item in pool]
        dump(output / f"pool_{generation:02d}.json", pool_metadata)
        np.savez_compressed(output / f"pool_{generation:02d}_features.npz",
                            features=np.asarray([item["features"] for item in pool]))
        generation_labels = []
        for label_index in range(min(label_count, len(available))):
            index, selection_rule, selection_score = select_pool_index(method, selector, before_policy, pool, available, rng)
            available.remove(index)
            item = pool[index]
            features = item["features"]
            z = item.get("acquisition_features")
            if z is None:
                z = acquisition_features(before_policy, features)
            branches = []
            for action in range(len(ACTION_NAMES)):
                branch = solve_policy(item["task"], before_policy, LOOKAHEAD_BUDGET,
                                      start_state=item["state"], first_action=action)
                curve = padded_curve(branch, LOOKAHEAD_BUDGET)
                branches.append({"action": action, "calls": branch["calls"],
                    "score": float(np.log10(max(curve[-1], 1e-12))),
                    "trace_sha256": array_digest(curve), "best_curve": curve.tolist(),
                    "cpu_seconds": branch["cpu_seconds"], "wall_seconds": branch["wall_seconds"],
                    "nonfinite": branch["nonfinite"]})
                counterfactual_calls += branch["calls"]; source_calls += branch["calls"]
            target = [row["score"] for row in branches]
            original_action = policy_action(before_policy, features)
            regret = max(target[original_action] - min(target), 0.)
            feature_rows.append(features.tolist()); labels.append(target)
            acquisition_rows.append(z.tolist()); regrets.append(regret)
            record = {"generation": generation, "within_generation": label_index, "pool_index": index,
                **pool_metadata[index], "source_policy_sha256": digest(before_policy),
                "selection_rule": selection_rule, "selection_score": selection_score,
                "features": features.tolist(), "acquisition_features": z.tolist(),
                "prior_action": original_action, "observed_decision_regret": regret, "branches": branches}
            label_records.append(record); generation_labels.append(record)
        if labels:
            policy = fit_policy(feature_rows, labels, seed + 1000 * generation)
            if method == "learned_acquisition":
                selector = fit_selector(acquisition_rows, regrets, seed + 2000 * generation)
            elif method == "fixed_disagreement":
                selector = {"kind": "fixed_uncertainty", "rule": "max predictive standard deviation plus action disagreement"}
            else:
                selector = None
        development_result = without_pool(assess(policy, development, DEVELOPMENT_BUDGET))
        development_calls += development_result["calls"]
        checkpoint = {"generation": generation, "policy": policy, "policy_sha256": digest(policy),
            "selector": selector, "selector_sha256": digest(selector),
            "development": development_result, "source_calls_to_date": source_calls,
            "labels_to_date": len(labels), "labels_this_generation": len(generation_labels),
            "source_rollout_policy_sha256": digest(before_policy), "source_rollout_assessment": source,
            "pool_states": len(pool), "pool_features_sha256": array_digest(np.asarray([x["features"] for x in pool]))}
        checkpoints.append(checkpoint)
        dump(output / f"generation_{generation:02d}.json", checkpoint)
        export_policy_python(policy, output / f"controller_{generation:02d}.py")
        export_selector_python(selector, output / f"selector_{generation:02d}.py")
        dump(output / f"labels_{generation:02d}.json", generation_labels)
    assert source_calls <= budget
    selected = min(checkpoints, key=lambda row: (row["development"]["fitness"], row["generation"]))
    summary = {"method": method, "meta_seed": seed, "source_query_cap": budget,
        "source_calls": source_calls, "state_collection_calls": state_collection_calls,
        "counterfactual_calls": counterfactual_calls, "development_calls": development_calls,
        "labels": len(labels), "generations": generations, "selected_generation": selected["generation"],
        "selected_policy": selected["policy"], "selected_policy_sha256": selected["policy_sha256"],
        "selected_development_fitness": selected["development"]["fitness"],
        "policy_changes": sum(checkpoints[i]["policy_sha256"] != checkpoints[i-1]["policy_sha256"] for i in range(1, len(checkpoints))),
        "selector_is_learned": method == "learned_acquisition",
        "selector_target_is_decision_regret_not_measured_training_benefit": True,
        "wall_seconds": time.perf_counter() - started_wall, "cpu_seconds": time.process_time() - started_cpu}
    dump(output / "checkpoints.json", checkpoints)
    dump(output / "all_labels.json", label_records)
    dump(output / "search_summary.json", summary)
    export_policy_python(selected["policy"], output / "selected_controller.py")
    return summary


def classical_job(method, seed, output, pilot=False):
    output = Path(output); output.mkdir(parents=True, exist_ok=True)
    started_wall, started_cpu = time.perf_counter(), time.process_time()
    train, development = tasks_for("train", pilot), tasks_for("development", pilot)
    generations = 2 if pilot else GENERATIONS
    labels = 12 if pilot else LABELS_PER_GENERATION
    budget = source_cap(len(train), generations, labels)
    maximum_candidate_cost = len(train) * TRAIN_BUDGET
    rng = np.random.default_rng(seed + 50000)
    default = default_classical(method)
    default_development = without_pool(assess(default, development, DEVELOPMENT_BUDGET))
    checkpoints = [{"generation": 0, "policy": default, "policy_sha256": digest(default),
                    "development": default_development, "source_calls_to_date": 0}]
    source_calls = 0; development_calls = default_development["calls"]
    candidates = []; incumbent = None
    for generation in range(1, generations + 1):
        stage_cap = budget * generation // generations
        while source_calls < stage_cap and source_calls + maximum_candidate_cost <= budget:
            config = default if not candidates else random_classical(method, rng)
            training = without_pool(assess(config, train, TRAIN_BUDGET))
            source_calls += training["calls"]
            row = {"candidate": len(candidates), "program": config, "program_sha256": digest(config),
                   "training": training}
            candidates.append(row)
            if incumbent is None or training["fitness"] < incumbent["training"]["fitness"]:
                incumbent = row
        development_result = without_pool(assess(incumbent["program"], development, DEVELOPMENT_BUDGET))
        development_calls += development_result["calls"]
        checkpoint = {"generation": generation, "policy": incumbent["program"],
                      "policy_sha256": incumbent["program_sha256"], "development": development_result,
                      "training": incumbent["training"], "source_calls_to_date": source_calls,
                      "evaluated_candidates": len(candidates)}
        checkpoints.append(checkpoint)
        dump(output / f"generation_{generation:02d}.json", checkpoint)
    selected = min(checkpoints, key=lambda row: (row["development"]["fitness"], row["generation"]))
    summary = {"method": method, "meta_seed": seed, "source_query_cap": budget,
        "source_calls": source_calls, "development_calls": development_calls,
        "candidate_evaluations": len(candidates), "selected_generation": selected["generation"],
        "selected_policy": selected["policy"], "selected_policy_sha256": selected["policy_sha256"],
        "selected_development_fitness": selected["development"]["fitness"],
        "wall_seconds": time.perf_counter() - started_wall, "cpu_seconds": time.process_time() - started_cpu}
    dump(output / "checkpoints.json", checkpoints); dump(output / "all_candidates.json", candidates)
    dump(output / "search_summary.json", summary)
    return summary


def protocol():
    return {"created_utc": utc(), "source_hashes": source_hashes(), "meta_seeds": META_SEEDS,
        "training_families": TRAIN_FAMILIES, "final_families": FINAL_FAMILIES,
        "training_tasks": 12, "development_tasks": 12, "final_tasks_per_family": 24,
        "training_dimensions": [8, 16, 32], "final_dimensions": [16, 32, 64],
        "training_seed_base": 7100000, "development_seed_base": 7200000, "final_seed_base": 7900000,
        "learned_checkpoints": GENERATIONS, "initial_reference_checkpoint": True,
        "labels_per_generation_cap": LABELS_PER_GENERATION, "counterfactual_query_cap_per_action": LOOKAHEAD_BUDGET,
        "source_rollout_queries_per_task": TRAIN_BUDGET, "development_queries_per_task": DEVELOPMENT_BUDGET,
        "final_queries_per_task": FINAL_BUDGET, "source_cap_per_method_and_seed": source_cap(),
        "action_library": ACTION_NAMES, "state_features": FEATURE_NAMES,
        "learned_selector": "depth-three tree predicting observed finite-horizon decision regret; 20% exploration",
        "controller_regression_target": "terminal log-loss contrast against BFGS action under the same continuation policy",
        "fixed_training_scaffold": True, "controller_rewrites_training_scaffold": False,
        "counterfactual_continuation": "the pre-generation controller, using the same inherited state",
        "same_label_passive": "identical learner and acquired labels imply identical exported policy; inherits acquisition cost",
        "classical_controls": CLASSICAL_METHODS, "cap_not_flop_or_walltime_equality": True,
        "primary_metric": "mean log10 best objective ratio at128, floor1e-12",
        "secondary_metrics": ["restricted time to1e-6, censored at129", "success fraction", "actual oracle calls", "process CPU seconds"],
        "primary_comparisons": ["learned_acquisition vs random_acquisition", "learned_acquisition vs tuned_bfgs", "learned_acquisition vs static_portfolio"],
        "generation_selection": "lowest development fitness, earliest generation on ties, initial BFGS included",
        "final_family_generators_called": False,
        "success_criteria": "held-out gains over initial and strongest tuned classical control, acquisition ablation gain, and affordable amortization",
        "negative_criteria": "no held-out gain, random acquisition parity, label-only explanation, or no practical amortization"}


def gradient_checks(tasks):
    checks = []
    for task in tasks:
        rng = np.random.default_rng(task.seed + 33)
        x = rng.normal(scale=.1, size=task.dimension)
        _, gradient = task.value_gradient(x)
        numerical = np.zeros(task.dimension); step = 1e-5
        for i in range(task.dimension):
            direction = np.zeros(task.dimension); direction[i] = step
            numerical[i] = (task.value_gradient(x + direction)[0] - task.value_gradient(x - direction)[0]) / (2 * step)
        error = float(np.max(np.abs(numerical - gradient)) / max(1., np.max(np.abs(gradient))))
        minimum, optimum_gradient = task.value_gradient(task.target)
        checks.append({"family": task.family, "seed": task.seed, "normalized_gradient_error": error,
                       "known_minimum_value": minimum, "known_minimum_gradient_norm": float(np.linalg.norm(optimum_gradient)),
                       "oracle_equivalent_checks": 2 * task.dimension + 2})
    return checks


def pilot_stage(output):
    output.mkdir(parents=True, exist_ok=True)
    started = time.perf_counter()
    tasks = tasks_for("train", pilot=True)
    gradients = gradient_checks(tasks)
    if max(row["normalized_gradient_error"] for row in gradients) > 1e-5:
        raise AssertionError("Pilot analytic-gradient check failed")
    jobs = [acquisition_job("learned_acquisition", META_SEEDS[0], output / "learned_acquisition", pilot=True)]
    for method in CLASSICAL_METHODS:
        jobs.append(classical_job(method, META_SEEDS[0], output / method, pilot=True))
    result = {"stage": "training_and_development_pilot_only", "final_generators_called": False,
        "source_hashes": source_hashes(), "gradient_checks": gradients, "jobs": jobs,
        "wall_seconds": time.perf_counter() - started,
        "pilot_can_inform_protocol_before_full_search": True}
    dump(output / "pilot_results.json", result)
    print(json.dumps({"pilot_seconds": result["wall_seconds"], "max_gradient_error": max(x["normalized_gradient_error"] for x in gradients),
                      "jobs": [{k: row[k] for k in ["method", "source_calls", "development_calls", "selected_generation", "selected_development_fitness", "wall_seconds"]} for row in jobs]}, indent=2), flush=True)


def meta_stage(output, workers):
    output.mkdir(parents=True, exist_ok=True)
    declaration = protocol()
    dump(output / "protocol_before_search.json", declaration)
    jobs = []
    with ProcessPoolExecutor(max_workers=workers, mp_context=mp.get_context("spawn")) as executor:
        futures = {}
        for seed in META_SEEDS:
            for method in ACQUISITION_METHODS + CLASSICAL_METHODS:
                fn = acquisition_job if method in ACQUISITION_METHODS else classical_job
                future = executor.submit(fn, method, seed, str(output / "search" / f"{method}_{seed}"), False)
                futures[future] = (method, seed)
        for future in as_completed(futures):
            row = future.result(); jobs.append(row)
            print(f"Completed {row['method']} seed{row['meta_seed']} source={row['source_calls']} dev={row['development_calls']} generation={row['selected_generation']} fitness={row['selected_development_fitness']:.6f}", flush=True)
    jobs.sort(key=lambda row: (row["meta_seed"], row["method"]))
    selected = {}; all_checkpoint_hashes = {}; passive_retraining = []
    for seed in META_SEEDS:
        seed_jobs = [row for row in jobs if row["meta_seed"] == seed]
        selected[str(seed)] = {row["method"]: row["selected_policy"] for row in seed_jobs}
        classical = [row for row in seed_jobs if row["method"] in CLASSICAL_METHODS]
        best = min(classical, key=lambda row: row["selected_development_fitness"])
        selected[str(seed)]["static_portfolio"] = best["selected_policy"]
        selected[str(seed)]["initial_bfgs"] = initial_policy()
        learned_job = next(row for row in seed_jobs if row["method"] == "learned_acquisition")
        chosen_generation = learned_job["selected_generation"]
        acquired = json.loads((output / "search" / f"learned_acquisition_{seed}" / "all_labels.json").read_text())
        acquired = [row for row in acquired if row["generation"] <= chosen_generation]
        retrain_started = time.process_time()
        passive = fit_policy([row["features"] for row in acquired],
                             [[b["score"] for b in row["branches"]] for row in acquired],
                             seed + 1000 * chosen_generation) if acquired else initial_policy()
        if passive != selected[str(seed)]["learned_acquisition"]:
            raise AssertionError("Same-label passive refit did not reproduce the active fitted controller")
        selected[str(seed)]["same_label_passive"] = passive
        passive_retraining.append({"meta_seed": seed, "selected_generation": chosen_generation,
            "labels": len(acquired), "independently_refitted": True, "policy_exactly_identical": True,
            "policy_sha256": digest(passive), "extra_oracle_calls": 0,
            "inherited_source_calls": learned_job["source_calls"], "inherited_development_calls": learned_job["development_calls"],
            "refitting_cpu_seconds": time.process_time() - retrain_started})
        for method in ACQUISITION_METHODS:
            checkpoints = json.loads((output / "search" / f"{method}_{seed}" / "checkpoints.json").read_text())
            all_checkpoint_hashes[f"{method}_{seed}"] = [row["policy_sha256"] for row in checkpoints]
    freeze = {"frozen_utc": utc(), "source_hashes": source_hashes(), "protocol_sha256": digest(declaration),
        "selected_programs": selected, "search_summaries": jobs, "all_checkpoint_program_hashes": all_checkpoint_hashes,
        "final_family_generators_have_not_been_called": True,
        "same_label_passive_cost": "inherits the complete learned-acquisition source/development expenditure",
        "static_portfolio_cost": "sum all four classical searches and development selection costs"}
    dump(output / "search_summaries.json", jobs); dump(output / "freeze_manifest.json", freeze)
    dump(output / "same_label_passive_retraining.json", passive_retraining)
    print("Freeze written before any final-family generation.", flush=True)


def bootstrap_comparison(frame, reference, metric="log10_relative_objective", repetitions=4000):
    active = frame[frame.method == "learned_acquisition"]
    other = frame[frame.method == reference]
    pair = active.merge(other, on=["meta_seed", "family", "task_seed", "dimension", "query_budget"], suffixes=("_active", "_reference"))
    differences = pair[f"{metric}_active"].to_numpy() - pair[f"{metric}_reference"].to_numpy()
    arrays = []
    for seed in META_SEEDS:
        arrays.append([pair[(pair.meta_seed == seed) & (pair.family == family)][f"{metric}_active"].to_numpy() -
                       pair[(pair.meta_seed == seed) & (pair.family == family)][f"{metric}_reference"].to_numpy()
                       for family in FINAL_FAMILIES])
    arrays = np.asarray(arrays)
    rng = np.random.default_rng(81811)
    samples = []
    for _ in range(repetitions):
        chosen_seeds = rng.integers(len(META_SEEDS), size=len(META_SEEDS))
        values = []
        for seed in chosen_seeds:
            for family_index in range(len(FINAL_FAMILIES)):
                indices = rng.integers(arrays.shape[2], size=arrays.shape[2])
                values.extend(arrays[seed, family_index, indices])
        samples.append(np.mean(values))
    return {"reference": reference, "metric": metric, "mean_paired_difference": float(np.mean(differences)),
            "hierarchical_bootstrap95": np.quantile(samples, [.025, .975]).tolist(),
            "active_strictly_better_fraction": float(np.mean(differences < 0)),
            "meta_seeds": len(META_SEEDS), "paired_program_task_cases": len(pair),
            "interpretation": "negative favors learned acquisition; families fixed, meta seeds and paired instances resampled"}


def evaluate_record(task, program, budget, seed, method, trajectories, prefix_label=""):
    result = run_solver(task, program, budget)
    curve = padded_curve(result, budget)
    key = f"s{seed}_{method}_{task.family}_{task.seed}" + prefix_label
    trajectories[key] = curve
    rows = []
    for prefix in [64, 128]:
        value = float(curve[prefix - 1])
        hits = np.flatnonzero(curve[:prefix] <= 1e-6)
        rows.append({"meta_seed": seed, "method": method, "family": task.family, "task_seed": task.seed,
            "dimension": task.dimension, "query_budget": prefix,
            "actual_oracle_calls_within_prefix": min(prefix, result["calls"]),
            "relative_objective": value, "log10_relative_objective": math_log(value),
            "success_1e_minus_6": int(value <= 1e-6), "restricted_queries_to_1e_minus_6": int(hits[0] + 1) if len(hits) else prefix + 1,
            "nonfinite_attempts": result["nonfinite"], "policy_sha256": digest(program),
            "whole128_cpu_seconds": result["cpu_seconds"], "whole128_wall_seconds": result["wall_seconds"],
            "action_counts": json.dumps(result.get("action_counts", []), separators=(",", ":"))})
    return rows, result["calls"]


def math_log(value): return float(np.log10(max(value, 1e-12)))


def final_stage(output):
    freeze_path = output / "freeze_manifest.json"
    freeze_bytes = freeze_path.read_bytes(); freeze = json.loads(freeze_bytes)
    if freeze["source_hashes"] != source_hashes():
        raise RuntimeError("Experimental source changed after freeze")
    started_utc = utc(); started_wall = time.perf_counter()
    tasks = tasks_for("final")
    arrays = {}
    for task in tasks:
        prefix = f"{task.family}_{task.seed}"
        arrays[prefix + "_matrix"] = task.matrix; arrays[prefix + "_target"] = task.target
        arrays[prefix + "_offset"] = task.offset
    np.savez_compressed(output / "final_task_arrays.npz", **arrays)
    task_manifest = [{"family": t.family, "seed": t.seed, "dimension": t.dimension,
                      "ridge": t.ridge, "parameter": t.parameter} for t in tasks]
    dump(output / "final_task_manifest.json", task_manifest)
    rows, generation_rows, trajectories, generation_trajectories = [], [], {}, {}
    final_calls = generation_calls = 0
    for seed in META_SEEDS:
        for method, program in freeze["selected_programs"][str(seed)].items():
            for task in tasks:
                records, calls = evaluate_record(task, program, FINAL_BUDGET, seed, method, trajectories)
                rows.extend(records); final_calls += calls
        print(f"Final selected controllers complete: seed{seed}", flush=True)
        for method in ACQUISITION_METHODS:
            checkpoints = json.loads((output / "search" / f"{method}_{seed}" / "checkpoints.json").read_text())
            expected = freeze["all_checkpoint_program_hashes"][f"{method}_{seed}"]
            if [row["policy_sha256"] for row in checkpoints] != expected:
                raise RuntimeError("Checkpoint list differs from frozen hashes")
            for checkpoint in checkpoints[1:]:
                for task in tasks:
                    records, calls = evaluate_record(task, checkpoint["policy"], FINAL_BUDGET, seed,
                                                    method, generation_trajectories, f"_g{checkpoint['generation']}")
                    for record in records:
                        record["generation"] = checkpoint["generation"]
                    generation_rows.extend(records); generation_calls += calls
        print(f"Final frozen-generation replay complete: seed{seed}", flush=True)
    frame = pd.DataFrame(rows); frame.to_csv(output / "final_results.csv", index=False)
    generation_frame = pd.DataFrame(generation_rows); generation_frame.to_csv(output / "generation_final_results.csv", index=False)
    np.savez_compressed(output / "final_trajectories.npz", **trajectories)
    np.savez_compressed(output / "generation_final_trajectories.npz", **generation_trajectories)
    final = frame[frame.query_budget == 128]
    metrics = final.groupby("method").agg(mean_log10_relative_objective=("log10_relative_objective", "mean"),
        success_fraction=("success_1e_minus_6", "mean"), mean_actual_calls=("actual_oracle_calls_within_prefix", "mean"),
        mean_restricted_queries=("restricted_queries_to_1e_minus_6", "mean"),
        mean_cpu_seconds=("whole128_cpu_seconds", "mean"), median_cpu_seconds=("whole128_cpu_seconds", "median"))
    family_metrics = final.groupby(["method", "family"]).agg(mean_log10_relative_objective=("log10_relative_objective", "mean"),
        success_fraction=("success_1e_minus_6", "mean"), mean_restricted_queries=("restricted_queries_to_1e_minus_6", "mean"))
    metrics.to_csv(output / "summary_by_method.csv"); family_metrics.to_csv(output / "summary_by_family.csv")
    comparisons = [bootstrap_comparison(final, method) for method in ["random_acquisition", "fixed_disagreement", "initial_bfgs", "tuned_bfgs", "static_portfolio"]]
    costs = {"source_search_calls": sum(row["source_calls"] for row in freeze["search_summaries"]),
             "development_calls": sum(row["development_calls"] for row in freeze["search_summaries"]),
             "final_selected_policy_calls": final_calls, "final_all_frozen_generation_calls": generation_calls}
    costs["total_before_independent_audit"] = sum(costs.values())
    summary = {"source_hashes": source_hashes(), "methods": metrics.reset_index().to_dict(orient="records"),
        "families": family_metrics.reset_index().to_dict(orient="records"), "paired_comparisons": comparisons,
        "query_ledger": costs, "final_rows": len(rows), "final_trajectories": len(trajectories),
        "generation_rows": len(generation_rows), "generation_trajectories": len(generation_trajectories),
        "claim_scope": "finite learned solver/action and labeling policies inside a fixed training scaffold; no general RSI claim"}
    dump(output / "summary.json", summary)
    provenance = {"final_started_utc": started_utc, "final_finished_utc": utc(),
        "source_hashes": source_hashes(), "freeze_file_sha256": hashlib.sha256(freeze_bytes).hexdigest(),
        "freeze_file_unchanged": freeze_bytes == freeze_path.read_bytes(), "final_selection_performed": False,
        "wall_seconds": time.perf_counter() - started_wall,
        "environment": {"python": platform.python_version(), "numpy": np.__version__, "scipy": scipy.__version__,
                        "sklearn": sklearn.__version__, "pandas": pd.__version__, "platform": platform.platform(), "blas_threads": 1}}
    dump(output / "final_provenance.json", provenance)
    print(metrics.to_string(), flush=True)
    print(json.dumps({"comparisons": comparisons, "query_ledger": costs}, indent=2), flush=True)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--stage", choices=["pilot", "meta", "final", "all"], default="pilot")
    parser.add_argument("--output", type=Path, default=Path("results"))
    parser.add_argument("--workers", type=int, default=3)
    args = parser.parse_args()
    if args.stage == "pilot": pilot_stage(args.output)
    if args.stage in ("meta", "all"): meta_stage(args.output, args.workers)
    if args.stage in ("final", "all"): final_stage(args.output)


if __name__ == "__main__":
    main()