File size: 14,971 Bytes
49f646d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Post-freeze replay, executable-export, gradient, and cost-ledger audit."""
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 hashlib
import importlib.util
import json
import multiprocessing as mp
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
import numpy as np
import pandas as pd
from controller_core import (ACTION_NAMES, acquisition_features, array_digest, assess, digest,
    fit_policy, fit_selector, padded_curve, policy_action, solve_policy, tasks_for, tree_predict)
from run_controller import (ACQUISITION_METHODS, CLASSICAL_METHODS, DEVELOPMENT_BUDGET,
    LOOKAHEAD_BUDGET, META_SEEDS, TRAIN_BUDGET, gradient_checks, select_pool_index, source_hashes)


def read(path): return json.loads(Path(path).read_text())


def load_export(path, name):
    spec = importlib.util.spec_from_file_location(name, path)
    module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
    return module


def replay_job(method, seed, directory):
    directory = Path(directory)
    checkpoints = read(directory / "checkpoints.json")
    labels = read(directory / "all_labels.json")
    train, development = tasks_for("train"), tasks_for("development")
    rng = np.random.default_rng(seed)
    source_calls = counterfactual_calls = development_calls = 0
    replay_records, export_records = [], []
    all_features, all_targets, acquisition_rows, regrets = [], [], [], []
    selector = None
    for checkpoint in checkpoints:
        generation = checkpoint["generation"]
        dev = assess(checkpoint["policy"], development, DEVELOPMENT_BUDGET)
        development_calls += dev["calls"]
        if dev["trace_sha256"] != checkpoint["development"]["trace_sha256"] or dev["fitness"] != checkpoint["development"]["fitness"]:
            raise AssertionError(f"Development replay mismatch {method} {seed} generation{generation}")
        if generation == 0:
            continue
        previous = checkpoints[generation - 1]["policy"]
        source = assess(previous, train, TRAIN_BUDGET, collect=True)
        source_calls += source["calls"]
        pool = source["pool"]
        if source["trace_sha256"] != checkpoint["source_rollout_assessment"]["trace_sha256"]:
            raise AssertionError("Source trajectory mismatch")
        if array_digest(np.asarray([row["features"] for row in pool])) != checkpoint["pool_features_sha256"]:
            raise AssertionError("Source pool features mismatch")
        available = list(range(len(pool)))
        current = [row for row in labels if row["generation"] == generation]
        for label in current:
            index, rule, score = select_pool_index(method, selector, previous, pool, available, rng)
            available.remove(index)
            if index != label["pool_index"] or rule != label["selection_rule"] or score != label["selection_score"]:
                raise AssertionError("Acquisition selection did not replay exactly")
            item = pool[index]
            if item["state_sha256"] != label["state_sha256"]:
                raise AssertionError("Inherited numerical state mismatch")
            z = item.get("acquisition_features")
            if z is None: z = acquisition_features(previous, item["features"])
            if not np.array_equal(z, label["acquisition_features"]):
                raise AssertionError("Acquisition features mismatch")
            targets = []
            for branch_record in label["branches"]:
                branch = solve_policy(item["task"], previous, LOOKAHEAD_BUDGET,
                                      start_state=item["state"], first_action=branch_record["action"])
                counterfactual_calls += branch["calls"]
                curve = padded_curve(branch, LOOKAHEAD_BUDGET)
                score_value = float(np.log10(max(curve[-1], 1e-12)))
                if branch["calls"] != branch_record["calls"] or array_digest(curve) != branch_record["trace_sha256"] or score_value != branch_record["score"]:
                    raise AssertionError("Counterfactual branch mismatch")
                targets.append(score_value)
            prior_action = policy_action(previous, item["features"])
            regret = max(targets[prior_action] - min(targets), 0.)
            if regret != label["observed_decision_regret"]:
                raise AssertionError("Regret target mismatch")
            all_features.append(item["features"].tolist()); all_targets.append(targets)
            acquisition_rows.append(z.tolist()); regrets.append(regret)
        refit = fit_policy(all_features, all_targets, seed + 1000 * generation)
        if digest(refit) != checkpoint["policy_sha256"]:
            raise AssertionError("Independent controller refit mismatch")
        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
        if selector != checkpoint["selector"]:
            raise AssertionError("Independent selector refit mismatch")
        exported = load_export(directory / f"controller_{generation:02d}.py", f"controller_{method}_{seed}_{generation}")
        test_rng = np.random.default_rng(seed + generation * 777)
        feature_tests = list(np.asarray(all_features)[-32:]) + list(test_rng.normal(size=(32, 16)) * 4)
        vector_checks = 0
        for features in feature_tests:
            if exported.choose_action(features) != policy_action(refit, features):
                raise AssertionError("Exported action differs")
            for tree_index, tree in enumerate(refit["trees"]):
                if not np.array_equal(getattr(exported, f"tree_{tree_index}")(features), tree_predict(tree, features)):
                    raise AssertionError("Exported tree predictions differ")
                vector_checks += 1
        selector_checks = 0
        if method == "learned_acquisition":
            exported_selector = load_export(directory / f"selector_{generation:02d}.py", f"selector_{seed}_{generation}")
            for z in acquisition_rows[-64:]:
                if exported_selector.score_acquisition(z) != max(float(tree_predict(selector["tree"], z)[0]), 0.):
                    raise AssertionError("Exported learned selector differs")
                selector_checks += 1
        export_records.append({"method": method, "meta_seed": seed, "generation": generation,
            "action_checks": len(feature_tests), "tree_vector_checks": vector_checks,
            "selector_score_checks": selector_checks, "all_bitwise_identical": True})
        replay_records.append({"method": method, "meta_seed": seed, "generation": generation,
            "source_trace_identical": True, "development_trace_identical": True,
            "acquisition_decisions_identical": True, "counterfactual_labels_identical": True,
            "controller_refit_identical": True, "selector_refit_identical": True,
            "labels": len(current), "counterfactual_branches": len(current) * len(ACTION_NAMES)})
    return {"method": method, "meta_seed": seed, "source_collection_replay_calls": source_calls,
            "counterfactual_replay_calls": counterfactual_calls, "development_replay_calls": development_calls,
            "replay_records": replay_records, "export_records": export_records}


def main():
    parser = argparse.ArgumentParser(); parser.add_argument("--output", type=Path, default=Path("results"))
    parser.add_argument("--workers", type=int, default=3); args = parser.parse_args()
    output = args.output; started = time.perf_counter()
    freeze_path = output / "freeze_manifest.json"; freeze_bytes = freeze_path.read_bytes(); freeze = json.loads(freeze_bytes)
    if freeze["source_hashes"] != source_hashes(): raise AssertionError("Source differs from freeze")
    provenance = read(output / "final_provenance.json")
    if provenance["freeze_file_sha256"] != hashlib.sha256(freeze_bytes).hexdigest(): raise AssertionError("Freeze hash chain failed")
    summaries = freeze["search_summaries"]
    accounting = []
    for summary in summaries:
        directory = output / "search" / f"{summary['method']}_{summary['meta_seed']}"
        checkpoints = read(directory / "checkpoints.json")
        dev_calls = sum(row["development"]["calls"] for row in checkpoints)
        if summary["method"] in ACQUISITION_METHODS:
            labels = read(directory / "all_labels.json")
            collection = sum(row["source_rollout_assessment"]["calls"] for row in checkpoints[1:])
            counterfactual = sum(branch["calls"] for label in labels for branch in label["branches"])
            source_calls = collection + counterfactual
        else:
            candidates = read(directory / "all_candidates.json")
            source_calls = sum(row["training"]["calls"] for row in candidates)
        chosen = min(checkpoints, key=lambda row: (row["development"]["fitness"], row["generation"]))
        exact = source_calls == summary["source_calls"] and dev_calls == summary["development_calls"]
        exact = exact and chosen["generation"] == summary["selected_generation"] and chosen["policy"] == summary["selected_policy"]
        exact = exact and source_calls <= summary["source_query_cap"]
        if not exact: raise AssertionError("Query accounting or development selection mismatch")
        accounting.append({"method": summary["method"], "meta_seed": summary["meta_seed"],
                           "source_calls": source_calls, "development_calls": dev_calls, "exact": True})
    replays = []
    with ProcessPoolExecutor(max_workers=args.workers, mp_context=mp.get_context("spawn")) as executor:
        futures = []
        for seed in META_SEEDS:
            for method in ACQUISITION_METHODS:
                futures.append(executor.submit(replay_job, method, seed, str(output / "search" / f"{method}_{seed}")))
        for future in as_completed(futures):
            result = future.result(); replays.append(result)
            print(f"Exact source/acquisition/counterfactual/development replay: {result['method']} seed{result['meta_seed']}", flush=True)
    replays.sort(key=lambda row: (row["meta_seed"], row["method"]))
    gradient_tasks = tasks_for("train") + [task for task in tasks_for("final") if task.seed % 1000 < 3]
    gradients = gradient_checks(gradient_tasks)
    if max(row["normalized_gradient_error"] for row in gradients) > 1e-5: raise AssertionError("Gradient audit failed")
    if max(row["known_minimum_value"] for row in gradients) > 1e-20: raise AssertionError("Known minimum value failed")
    if max(row["known_minimum_gradient_norm"] for row in gradients) > 1e-10: raise AssertionError("Known minimum gradient failed")
    frame = pd.read_csv(output / "final_results.csv")
    active = frame[frame.method == "learned_acquisition"].sort_values(["meta_seed", "task_seed", "query_budget"])
    passive = frame[frame.method == "same_label_passive"].sort_values(["meta_seed", "task_seed", "query_budget"])
    compared_fields = ["relative_objective", "log10_relative_objective", "restricted_queries_to_1e_minus_6", "actual_oracle_calls_within_prefix", "policy_sha256", "action_counts"]
    if not np.array_equal(active[compared_fields].to_numpy(), passive[compared_fields].to_numpy()):
        raise AssertionError("Same-label passive refit results differ")
    trajectory_checks = []
    for filename in ["final_trajectories.npz", "generation_final_trajectories.npz"]:
        with np.load(output / filename, allow_pickle=False) as data:
            finite = all(np.isfinite(data[name]).all() for name in data.files)
            monotone = all(np.all(np.diff(data[name]) <= 0) for name in data.files)
            if not (finite and monotone): raise AssertionError("Trajectory invariant failed")
            trajectory_checks.append({"file": filename, "arrays": len(data.files), "finite": finite, "best_value_nonincreasing": monotone})
    pilot_calls = 0; pilot_details = []
    root = Path(__file__).resolve().parent
    for folder in ["pilot_results", "pilot_centered_results"]:
        path = root / folder / "pilot_results.json"
        if path.exists():
            pilot = read(path)
            calls = sum(row["source_calls"] + row["development_calls"] for row in pilot["jobs"])
            calls += sum(row["oracle_equivalent_checks"] for row in pilot["gradient_checks"])
            pilot_calls += calls; pilot_details.append({"stage": folder, "calls": calls})
    dimension_path = root / "pilot_dimension_audit.json"
    if dimension_path.exists():
        calls = read(dimension_path)["total_gradient_value_calls"]
        pilot_calls += calls; pilot_details.append({"stage": "pilot_dimension_audit", "calls": calls})
    audit_calls = sum(row["source_collection_replay_calls"] + row["counterfactual_replay_calls"] + row["development_replay_calls"] for row in replays)
    gradient_calls = sum(row["oracle_equivalent_checks"] for row in gradients)
    summary = read(output / "summary.json")
    ledger = {**summary["query_ledger"], "independent_replay_calls": audit_calls,
              "independent_gradient_audit_calls": gradient_calls, "historical_pilot_calls": pilot_calls}
    ledger["total_including_pilots_and_audit"] = summary["query_ledger"]["total_before_independent_audit"] + audit_calls + gradient_calls + pilot_calls
    report = {"source_hashes": source_hashes(), "audit_source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        "freeze_file_sha256": hashlib.sha256(freeze_bytes).hexdigest(), "freeze_unchanged": freeze_bytes == freeze_path.read_bytes(),
        "audit_does_not_change_selected_programs": True, "all_checks_passed": True,
        "query_accounting": accounting, "replays": replays, "analytic_gradient_checks": gradients,
        "finite_difference_is_numerical_not_formal_proof": True,
        "same_label_passive_identical_fields": compared_fields, "same_label_paired_rows": len(active),
        "trajectory_checks": trajectory_checks, "pilot_costs": pilot_details, "query_ledger": ledger,
        "wall_seconds": time.perf_counter() - started}
    (output / "independent_audit.json").write_text(json.dumps(report, indent=2, allow_nan=False) + "\n")
    print(json.dumps({"all_checks_passed": True, "replayed_generations": sum(len(row['replay_records']) for row in replays),
                      "gradient_checks": len(gradients), "max_gradient_error": max(row['normalized_gradient_error'] for row in gradients),
                      "query_ledger": ledger, "wall_seconds": report['wall_seconds']}, indent=2), flush=True)


if __name__ == "__main__": main()