File size: 13,641 Bytes
7c188b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""MAUI-Bench execution harness.

Usage:
  python src/runner.py --config config/experiment.yaml [--dry-run]
      [--models m1,m2] [--families menu,layout] [--topologies single,critique]
      [--limit-instances N] [--run-id NAME]

Stages (idempotent, resumable):
  1. discover models, freeze manifest.json
  2. generate instances + compute oracles (cached to results/.cache)
  3. enumerate cells = instance x topology x model x condition x rep
  4. execute cells not yet present in results/<run_id>/records.jsonl
  5. score and append one JSON record per execution

Monitor progress from another terminal with:  python src/monitor.py --run-id NAME
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed

import numpy as np
import yaml

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from client import LLMClient
from tasks import FAMILIES, Instance
from topologies import TOPOLOGIES, DROPOUT_ROLE
import metrics as M

WRITE_LOCK = threading.Lock()


def load_config(path: str) -> dict:
    with open(path) as f:
        return yaml.safe_load(f)


def cell_key(**kw) -> str:
    return hashlib.sha1(json.dumps(kw, sort_keys=True).encode()).hexdigest()[:16]


def discover_models(client: LLMClient, cfg: dict) -> list[dict]:
    sel = cfg["models"]["selection"]
    listed = client.list_models()
    ids = [m["id"] for m in listed]
    if isinstance(sel, list):
        chosen = [i for i in sel if i in ids]
        missing = [i for i in sel if i not in ids]
        if missing:
            print(f"[warn] requested models not on server: {missing}")
    else:
        excl = cfg["models"].get("exclude_patterns", [])
        chosen = [i for i in ids if not any(p in i.lower() for p in excl)]
    meta = cfg["models"].get("metadata", {}) or {}
    return [{"id": i, **meta.get(i, {})} for i in chosen]


def build_instances(cfg: dict, grid: dict, cache_dir: str,
                    skip_oracles: bool = False) -> list[dict]:
    """Generate instances and exact oracles, cached by content hash."""
    os.makedirs(cache_dir, exist_ok=True)
    master = np.random.default_rng(cfg["design"]["master_seed"])
    out = []
    for family in grid["families"]:
        task_cls = FAMILIES[family]
        fam_rng = np.random.default_rng(master.integers(0, 2**31))
        for idx in range(grid["instances_per_family"]):
            inst = task_cls.generate(fam_rng, cfg["tasks"][family])
            h = hashlib.sha1(inst.to_json().encode()).hexdigest()[:16]
            cpath = os.path.join(cache_dir, f"oracle_{family}_{h}.json")
            if os.path.exists(cpath):
                with open(cpath) as f:
                    oc = json.load(f)
            elif skip_oracles:
                oc = None
            else:
                a_star, c_star, c_rand = task_cls.oracle(inst)
                oc = {"a_star": a_star, "c_star": c_star, "c_rand": c_rand}
                with open(cpath, "w") as f:
                    json.dump(oc, f)
            out.append({"family": family, "idx": idx, "inst": inst, "oracle": oc})
    return out


def condition_list(cfg: dict, grid: dict, topology: str) -> list[dict]:
    """The perturbation-condition matrix for one topology."""
    conds: list[dict] = []
    K, J = grid["replications"], grid["paraphrases"]
    for r in range(K):
        conds.append({"name": "replication", "rep": r, "paraphrase": None,
                      "perturb": {}})
    for j in range(J):
        conds.append({"name": "paraphrase", "rep": 0, "paraphrase": j,
                      "perturb": {}})
    p = cfg["perturbations"]
    if p.get("dropout") and topology in DROPOUT_ROLE:
        conds.append({"name": "dropout", "rep": 0, "paraphrase": None,
                      "perturb": {"dropout_role": DROPOUT_ROLE[topology]}})
    conds.append({"name": "corruption", "rep": 0, "paraphrase": None,
                  "perturb": {"char_noise": p["corruption_char_noise"],
                              "truncate": p["corruption_truncate"]}})
    if p.get("context_truncation"):
        conds.append({"name": "ctx_truncation", "rep": 0, "paraphrase": None,
                      "perturb": {"ctx_truncation": True}})
    if cfg["decoding"].get("greedy_reference"):
        conds.append({"name": "greedy", "rep": 0, "paraphrase": None,
                      "perturb": {}, "greedy": True})
    return conds


def truncate_context(inst: Instance) -> Instance:
    """Keep only the top-half probability mass of the usage table (F1 sensitivity)."""
    d = json.loads(json.dumps(inst.data))
    usage = d.get("usage")
    if usage:
        items = sorted(usage.items(), key=lambda kv: -kv[1])
        keep, mass = {}, 0.0
        for k, v in items:
            keep[k] = v
            mass += v
            if mass >= 0.5:
                break
        d["usage_note"] = "partial usage table; remaining items unobserved"
        d["usage"] = keep
    inst2 = Instance(inst.family, inst.seed, d, inst.paraphrases)
    return inst2


def execute_cell(client, cfg, rec, topology, model_id, cond, run_dir) -> dict:
    family = rec["family"]
    task_cls = FAMILIES[family]
    inst: Instance = rec["inst"]
    oracle = rec["oracle"]
    dec = dict(cfg["decoding"])
    dec["temperature"] = 0.0 if cond.get("greedy") else dec["temperature"]
    desc = (inst.paraphrases[cond["paraphrase"]]
            if cond["paraphrase"] is not None else inst.data["description"])
    run_inst = truncate_context(inst) if cond["perturb"].get("ctx_truncation") else inst
    rng = np.random.default_rng(
        (inst.seed * 1_000_003 + hash((topology, model_id, cond["name"],
                                       cond["rep"], cond["paraphrase"])) )
        % (2**31)
    )
    t0 = time.monotonic()
    trace = TOPOLOGIES[topology](client, model_id, run_inst, task_cls, dec,
                                 cond["perturb"], rng, desc)
    wall = time.monotonic() - t0

    parsed = task_cls.parse(inst, trace.final_text) if trace.final_text else None
    action, penalty = task_cls.penalized(inst, parsed)
    c_hat = task_cls.cost(inst, action) + penalty
    nr = M.normalized_regret(c_hat, oracle["c_star"], oracle["c_rand"])

    committee_regrets = []
    for txt in trace.committee_texts:
        p = task_cls.parse(inst, txt) if txt else None
        a, pen = task_cls.penalized(inst, p)
        committee_regrets.append(
            M.normalized_regret(task_cls.cost(inst, a) + pen,
                                oracle["c_star"], oracle["c_rand"]))

    record = {
        "key": cell_key(family=family, idx=rec["idx"], topology=topology,
                        model=model_id, cond=cond["name"], rep=cond["rep"],
                        para=cond["paraphrase"]),
        "ts": time.time(),
        "family": family, "instance_idx": rec["idx"], "instance_seed": inst.seed,
        "topology": topology, "model": model_id,
        "condition": cond["name"], "rep": cond["rep"],
        "paraphrase": cond["paraphrase"],
        "parsed_ok": parsed is not None,
        "penalty": penalty,
        "cost": c_hat, "c_star": oracle["c_star"], "c_rand": oracle["c_rand"],
        "normalized_regret": nr,
        "committee_regrets": committee_regrets,
        "committee_divergence": (M.committee_divergence(committee_regrets, nr)
                                 if committee_regrets else None),
        "wall_latency_s": wall,
        "sum_call_latency_s": trace.total_latency_s,
        "prompt_tokens": trace.total_prompt_tokens,
        "completion_tokens": trace.total_completion_tokens,
        "role_failures": trace.role_failures,
        "action": action,
    }
    # full trace to a sidecar file for annotation and debugging
    tdir = os.path.join(run_dir, "traces")
    os.makedirs(tdir, exist_ok=True)
    with open(os.path.join(tdir, record["key"] + ".json"), "w") as f:
        json.dump({"record_key": record["key"], "calls": trace.calls,
                   "final_text": trace.final_text}, f)
    return record


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--config", default="config/experiment.yaml")
    ap.add_argument("--run-id", default=None)
    ap.add_argument("--models", default=None, help="comma-separated override")
    ap.add_argument("--families", default=None)
    ap.add_argument("--topologies", default=None)
    ap.add_argument("--limit-instances", type=int, default=None)
    ap.add_argument("--dry-run", action="store_true",
                    help="enumerate and count cells without calling the server")
    args = ap.parse_args()

    cfg = load_config(args.config)
    grid = dict(cfg["design"]["grids"][cfg["design"]["active_grid"]])
    if args.families:
        grid["families"] = args.families.split(",")
    if args.topologies:
        grid["topologies"] = args.topologies.split(",")
    if args.limit_instances:
        grid["instances_per_family"] = args.limit_instances

    run_id = args.run_id or time.strftime("run_%Y%m%d_%H%M%S")
    run_dir = os.path.join(cfg["paths"]["results_dir"], run_id)
    os.makedirs(run_dir, exist_ok=True)

    client = LLMClient(
        base_url=cfg["server"]["base_url"], api_key=cfg["server"]["api_key"],
        timeout_s=cfg["server"]["timeout_s"],
        max_retries=cfg["server"]["max_retries"],
        retry_backoff_s=cfg["server"]["retry_backoff_s"],
        max_concurrency=cfg["server"]["max_concurrency"],
    )

    if args.dry_run:
        models = ([{"id": m} for m in args.models.split(",")] if args.models
                  else [{"id": "DRYRUN-MODEL"}])
    else:
        models = discover_models(client, cfg)
        if args.models:
            wanted = args.models.split(",")
            models = [m for m in models if m["id"] in wanted] or \
                     [{"id": w} for w in wanted]
    print(f"[info] {len(models)} models in pool")

    instances = build_instances(cfg, grid, cfg["paths"]["cache_dir"],
                                skip_oracles=args.dry_run)
    print(f"[info] {len(instances)} instances generated, oracles cached")

    cells = []
    for rec in instances:
        for topo in grid["topologies"]:
            for m in models:
                for cond in condition_list(cfg, grid, topo):
                    cells.append((rec, topo, m["id"], cond))
    print(f"[info] total cells: {len(cells)}")

    manifest = {
        "run_id": run_id, "config": cfg, "grid": grid,
        "models": models, "n_instances": len(instances),
        "n_cells": len(cells), "started": time.time(),
    }
    with open(os.path.join(run_dir, "manifest.json"), "w") as f:
        json.dump(manifest, f, indent=2, default=str)

    if args.dry_run:
        est_calls = 0
        per_topo = {"single": 1, "chain": 2, "critique": 3, "debate": 7,
                    "hierarchical": 3}
        for _, topo, _, _ in cells:
            est_calls += per_topo[topo]
        print(f"[dry-run] estimated model calls: {est_calls}")
        return

    records_path = os.path.join(run_dir, "records.jsonl")
    done: set[str] = set()
    if os.path.exists(records_path):
        with open(records_path) as f:
            for line in f:
                try:
                    done.add(json.loads(line)["key"])
                except Exception:
                    pass
        print(f"[info] resuming: {len(done)} cells already recorded")

    todo = [c for c in cells
            if cell_key(family=c[0]["family"], idx=c[0]["idx"], topology=c[1],
                        model=c[2], cond=c[3]["name"], rep=c[3]["rep"],
                        para=c[3]["paraphrase"]) not in done]
    print(f"[info] executing {len(todo)} remaining cells")

    progress_path = os.path.join(run_dir, "progress.json")
    n_done = len(done)
    t_start = time.monotonic()

    def work(c):
        rec, topo, mid, cond = c
        return execute_cell(client, cfg, rec, topo, mid, cond, run_dir)

    with ThreadPoolExecutor(max_workers=cfg["server"]["max_concurrency"]) as ex:
        futures = {ex.submit(work, c): c for c in todo}
        for fut in as_completed(futures):
            try:
                record = fut.result()
            except Exception as e:
                c = futures[fut]
                record = {"key": "ERR", "error": f"{type(e).__name__}: {e}",
                          "family": c[0]["family"], "topology": c[1],
                          "model": c[2], "condition": c[3]["name"],
                          "ts": time.time()}
            with WRITE_LOCK:
                with open(records_path, "a") as f:
                    f.write(json.dumps(record) + "\n")
                n_done += 1
                if n_done % 10 == 0 or n_done == len(cells):
                    elapsed = time.monotonic() - t_start
                    rate = (n_done - len(done)) / max(elapsed, 1e-9)
                    remaining = (len(cells) - n_done) / max(rate, 1e-9)
                    prog = {"run_id": run_id, "done": n_done,
                            "total": len(cells),
                            "pct": round(100 * n_done / len(cells), 2),
                            "cells_per_s": round(rate, 3),
                            "eta_s": round(remaining),
                            "updated": time.time()}
                    with open(progress_path, "w") as pf:
                        json.dump(prog, pf)
                    print(f"[{prog['pct']:6.2f}%] {n_done}/{len(cells)} "
                          f"eta {remaining/60:.1f} min", flush=True)

    print("[info] run complete:", records_path)


if __name__ == "__main__":
    main()