File size: 14,897 Bytes
33f388b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reproducible, fully metered tests of reciprocal operator repair.

Run: python3 src/experiment.py --seeds 24 --budget 1500000 --rank 4
No third-party dependencies. Development seeds are disjoint from report seeds.
"""
from __future__ import annotations

import argparse
from collections import Counter
import csv
from dataclasses import asdict
import hashlib
import json
import math
from pathlib import Path
import platform
import random
import resource
import statistics
import sys
import time

from core import (BudgetExhausted, K, Mat, Meter, Problem, add,
                  boundary_candidate, differential, equal, kernel_work, mul,
                  nnz, normalize, positions, proposal, repaired_candidate,
                  semantic_certificate, valid, zero)
from domains import CoordinateMoves, from_scratch_contraction, generate


ARMS = ("recursive", "frozen", "boundary", "coordinate", "rebuild_coordinate",
        "uncoupled", "no_normalization", "no_update")


def digest(h: Mat) -> str:
    return hashlib.sha256(json.dumps(h).encode()).hexdigest()[:16]


def search(p: Problem, mode: str, budget: int, seed: int,
           external_generator: Mat | None = None, forbidden: Mat | None = None,
           initial: Mat | None = None,
           cpu_budget: float | None = None) -> tuple[Mat, dict]:
    """All arms optimize the same exact future K-work objective, nnz(h).

    Equality accepted only when it changes h: neutral moves allow drift.
    Strict improvements alone are counted as improvements. For transplant,
    a parent cannot be installed verbatim (forbidden matrix).
    A budget exception discards the incomplete proposal; the last validated
    checkpoint survives. No partial computation is installed.
    """
    rng = random.Random(seed)
    m = Meter(budget)
    h = p.h0 if initial is None else initial
    frozen = p.h0 if external_generator is None else external_generator
    stats = Counter()
    events = []
    start = time.perf_counter()
    cpu_start = time.process_time()
    best_score = sum(row.bit_count() for row in h)
    best = h
    current_score = best_score
    initial_score = best_score
    chart = None
    try:
        m.use(p.n, "setup")
        current_score = best_score = nnz(h, m)
        if not valid(p, h, m):
            raise AssertionError("Invalid supplied initial contraction")
        pos_a = positions(p, -1, m)
        pos_b = positions(p, -2, m)
        if mode in ("coordinate", "rebuild_coordinate"):
            if mode == "rebuild_coordinate":
                candidate = from_scratch_contraction(p, m)
                ok = valid(p, candidate, m)
                score = nnz(candidate, m)
                if ok and score <= best_score:
                    h = best = candidate
                    current_score = best_score = score
                    stats["rebuild_accepted"] += 1
                    events.append((m.used, score))
            chart = CoordinateMoves.build(p, h, m)
        if mode != "no_update":
            while True:
                if cpu_budget is not None and time.process_time() - cpu_start >= cpu_budget:
                    stats["cpu_interrupts"] += 1
                    break
                stats["attempts"] += 1
                m.use(12, "bookkeeping")
                if mode in ("coordinate", "rebuild_coordinate"):
                    candidate = chart.propose(h, rng, m)
                elif mode == "boundary":
                    B = proposal(p, pos_b, rng, m)
                    candidate = boundary_candidate(p, h, B, m)
                else:
                    a = proposal(p, pos_a, rng, m)
                    if mode == "uncoupled":
                        candidate = add(h, a, m)
                    elif mode == "no_normalization":
                        z = add(a, K(p, h, differential(p, a, m), m), m)
                        candidate = add(h, z, m)
                    else:
                        generator = h if mode == "recursive" else frozen
                        candidate = repaired_candidate(p, h, generator, a, m)
                ok = valid(p, candidate, m)
                stats["completed"] += 1
                if cpu_budget is not None and time.process_time() - cpu_start >= cpu_budget:
                    # Never install a candidate whose validation crosses the cap.
                    stats["cpu_interrupts"] += 1
                    break
                if not ok:
                    stats["invalid"] += 1
                    continue
                score = nnz(candidate, m)
                if forbidden is not None and equal(candidate, forbidden, m):
                    stats["parent_copy_rejected"] += 1
                    continue
                same = equal(candidate, h, m)
                if same:
                    stats["unchanged"] += 1
                    continue
                if score <= current_score:
                    h = candidate
                    if score < current_score:
                        stats["strict_accepts"] += 1
                    else:
                        stats["neutral_accepts"] += 1
                    current_score = score
                    if score < best_score:
                        best = h
                        best_score = score
                        events.append((m.used, score))
                else:
                    stats["worse_rejected"] += 1
    except BudgetExhausted:
        stats["budget_interrupts"] += 1
    result = dict(stats)
    result.update({"mode": mode, "budget": budget, "work": m.used,
                   "cpu_budget_s": cpu_budget,
                   "initial_nnz": initial_score, "final_nnz": best_score,
                   "nnz_gain": initial_score - best_score,
                   "wall_s": time.perf_counter() - start,
                   "cpu_s": time.process_time() - cpu_start,
                   "work_categories": dict(m.counts), "events": events,
                   "operator_digest": digest(best),
                   "operator_bytes": sys.getsizeof(best) +
                       sum(sys.getsizeof(row) for row in best),
                   "zero_progress": initial_score == best_score})
    return best, result


def fresh_tasks(p: Problem, seed: int, count: int = 32) -> list[Mat]:
    """Fresh exact End-repair tasks F=partial T; private T is never exposed.

    Random sparse degree-zero T; F has degree one, partial F=0, QFQ=0.
    This is a future-work/validity test, not a task-generalization benchmark:
    the chosen word-RAM cost has a known linear dependence on nnz(h).
    """
    rng = random.Random(seed)
    m = Meter()
    pos = positions(p, 0, m)
    return [differential(p, proposal(p, pos, rng, m, width=5), m)
            for _ in range(count)]


def audit(p: Problem, h: Mat, tasks: list[Mat]) -> dict:
    km = Meter()
    vm = Meter()
    failures = 0
    cross_failures = 0
    start = time.perf_counter()
    for f in tasks:
        repair = K(p, h, f, km)
        if not equal(differential(p, repair, vm), f, vm):
            failures += 1
        no_cross = K(p, h, f, vm, cross=False)
        if not equal(differential(p, no_cross, vm), f, vm):
            cross_failures += 1
    return {"tasks": len(tasks), "task_failures": failures,
            "cross_ablation_failures": cross_failures,
            "kernel_work": km.used,
            "audit_work": vm.used,
            "audit_wall_s": time.perf_counter() - start}


def interval(values: list[float]) -> dict:
    mean = statistics.mean(values)
    sd = statistics.stdev(values) if len(values) > 1 else 0.0
    # Descriptive normal interval; no claim that small-sample tails are Gaussian.
    return {"mean": mean, "sd": sd,
            "mean_ci95_normal": [mean - 1.96 * sd / math.sqrt(len(values)),
                                 mean + 1.96 * sd / math.sqrt(len(values))],
            "min": min(values), "max": max(values)}


def summarize(records: list[dict]) -> dict:
    out = {}
    for arm in sorted({r["arm"] for r in records}):
        rows = [r for r in records if r["arm"] == arm]
        out[arm] = {key: interval([float(r.get(key, 0)) for r in rows])
                    for key in ("nnz_gain", "final_nnz", "kernel_work", "work",
                                "cpu_s", "wall_s", "completed", "invalid",
                                "strict_accepts", "operator_bytes",
                                "task_failures", "cross_ablation_failures")}
        out[arm]["zero_progress_count"] = sum(r["zero_progress"] for r in rows)
        out[arm]["n"] = len(rows)
    return out


def run(args) -> dict:
    records = []
    descendants = []
    outdir = Path(args.output)
    outdir.mkdir(parents=True, exist_ok=True)
    run_start = time.perf_counter()
    for offset in range(args.seeds):
        seed = args.seed_start + offset
        p = generate(seed, rank=args.rank, homology=1,
                     grades_count=4, scramble=args.scramble)
        tasks = fresh_tasks(p, seed * 100000 + 31001)
        outputs = {}
        parent_record = None
        for arm in ARMS:
            h, row = search(p, arm, args.budget, seed * 100000 + 10001,
                            cpu_budget=args.cpu_budget)
            outputs[arm] = h
            row.update({"seed": seed, "arm": arm, "n": p.n})
            row.update(audit(p, h, tasks))
            records.append(row)
            if arm == "recursive":
                parent_record = row
        # Parent -> fresh discovery -> descendant-only fresh repair audit.
        # Every child starts at h0. The parent is available ONLY to the proposal
        # generator; its exact matrix cannot be installed as the child.
        parent = outputs["recursive"]
        child_tasks = fresh_tasks(p, seed * 100000 + 61001)
        for label, generator in (("learned_parent", parent),
                                 ("initial_parent", p.h0)):
            h, row = search(p, "frozen", args.child_budget,
                            seed * 100000 + 41001,
                            external_generator=generator, forbidden=parent,
                            cpu_budget=None if args.cpu_budget is None else args.cpu_budget / 2)
            row.update({"seed": seed, "arm": label, "n": p.n,
                        "parent_digest": digest(parent),
                        "parent_training_work": parent_record["work"] if label == "learned_parent" else 0,
                        "parent_training_cpu_s": parent_record["cpu_s"] if label == "learned_parent" else 0,
                        "total_work_including_parent": row["work"] +
                            (parent_record["work"] if label == "learned_parent" else 0),
                        "total_cpu_including_parent_s": row["cpu_s"] +
                            (parent_record["cpu_s"] if label == "learned_parent" else 0)})
            row.update(audit(p, h, child_tasks))
            descendants.append(row)
        # Resource-inclusive controls can spend the parent's cost on discovery.
        for label, mode in (("initial_parent_full_budget", "frozen"),
                            ("coordinate_full_budget", "coordinate"),
                            ("rebuild_full_budget", "rebuild_coordinate")):
            h, row = search(p, mode, args.budget + args.child_budget,
                            seed * 100000 + 41001, forbidden=parent,
                            cpu_budget=None if args.cpu_budget is None else 1.5 * args.cpu_budget)
            row.update({"seed": seed, "arm": label, "n": p.n,
                        "parent_training_work": 0,
                        "total_work_including_parent": row["work"]})
            row.update(audit(p, h, child_tasks))
            descendants.append(row)
        print(json.dumps({"seed": seed, "progress": offset + 1,
                          "initial_nnz": sum(x.bit_count() for x in p.h0),
                          "final_nnz": {a: sum(x.bit_count() for x in h)
                                        for a, h in outputs.items()}}), flush=True)
        # Checkpoint the reproducible observations; never use them to tune.
        (outdir / "raw_checkpoint.json").write_text(json.dumps(
            {"records": records, "descendants": descendants}, indent=2))

    paired = {}
    by_seed = {(r["seed"], r["arm"]): r for r in records}
    for other in ("frozen", "boundary", "coordinate", "rebuild_coordinate"):
        # Positive means recursive has lower held-out kernel cost.
        vals = [by_seed[(s, other)]["kernel_work"] -
                by_seed[(s, "recursive")]["kernel_work"]
                for s in range(args.seed_start, args.seed_start + args.seeds)]
        paired["recursive_vs_" + other] = interval(vals)
    child_by = {(r["seed"], r["arm"]): r for r in descendants}
    vals = [child_by[(s, "initial_parent")]["kernel_work"] -
            child_by[(s, "learned_parent")]["kernel_work"]
            for s in range(args.seed_start, args.seed_start + args.seeds)]
    paired["descendant_transplant"] = interval(vals)
    results = {"config": vars(args), "platform": platform.platform(),
               "python": sys.version, "total_wall_s": time.perf_counter() - run_start,
               "process_peak_rss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
               "meter_model": "n<=64 word RAM; matrix mul=2n+6*nnz(left); xor=2n; "
                              "fixed scan, RNG and control charges; see source",
               "summary": summarize(records), "descendant_summary": summarize(descendants),
               "paired_differences": paired,
               "records": records, "descendants": descendants}
    (outdir / "results.json").write_text(json.dumps(results, indent=2))
    for filename, rows in (("runs.csv", records), ("descendants.csv", descendants)):
        simple = [{k: v for k, v in row.items() if not isinstance(v, (dict, list))}
                  for row in rows]
        keys = sorted(set().union(*(set(row) for row in simple)))
        with (outdir / filename).open("w", newline="") as f:
            writer = csv.DictWriter(f, fieldnames=keys)
            writer.writeheader()
            writer.writerows(simple)
    print(json.dumps({"finished": True, "total_wall_s": results["total_wall_s"],
                      "results": str(outdir / 'results.json')}), flush=True)
    return results


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--seeds", type=int, default=24)
    parser.add_argument("--seed-start", type=int, default=1000)
    parser.add_argument("--budget", type=int, default=1500000)
    parser.add_argument("--child-budget", type=int, default=750000)
    parser.add_argument("--rank", type=int, default=4)
    parser.add_argument("--scramble", type=int, default=16)
    parser.add_argument("--output", default="results/main")
    parser.add_argument("--cpu-budget", type=float, default=None)
    run(parser.parse_args())