File size: 8,359 Bytes
a2b0c04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c7f145
 
 
 
 
 
 
 
 
 
 
a2b0c04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c7f145
a2b0c04
 
 
 
 
 
 
 
 
 
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
"""Every number that appears in the post, the Space and the README, computed from the recorded data.

    python scripts/figures.py            # writes hf/numbers.json and prints it

Nothing in the write-up is typed by hand: it is read from this file. Episodes our own harness failed on
(model-server timeouts, API connection drops) are excluded everywhere, as they are in the verdicts.
"""

from __future__ import annotations

import importlib.util
import json
import sys
from collections import Counter, defaultdict
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from shortlist.checks import check_suite, harness_error  # noqa: E402

RUN = ROOT / "runs" / "day2"           # the clean run with the fixed harness (and later passes into it)
PILOT_DIPG = ROOT / "runs" / "day1c"   # the DIPG marker experiment
EXPERIMENTS = ("dipg_safety_env-plain", "dipg_safety_env-brackets")  # reported inside the DIPG finding, not as suites
PLAYERS = ["null", "random", "small", "beam-low", "beam-medium", "beam-high", "beam-max"]


def load(run: Path) -> dict[str, list[dict]]:
    out = {}
    for path in sorted(run.glob("*.jsonl")):
        out[path.stem] = [r for r in (json.loads(l) for l in path.read_text().splitlines() if l.strip()) if not harness_error(r)]
    return out


def census() -> dict:
    spec = importlib.util.spec_from_file_location("hub_sweep", ROOT / "scripts" / "hub_sweep.py")
    hs = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(hs)
    rows = hs.merged(ROOT / "runs" / "hub" / "sweep")
    label = {"passes floor checks": "runs and passes the floor checks",
             "suspicious floor": "scores above zero for doing nothing",
             "no standard API": "running, but no standard OpenEnv API",
             "broken": "broken (build or runtime error on the Hub)",
             "paused by owner": "paused by its owner",
             "asleep, didn't wake": "asleep, no answer within 10 minutes",
             "doesn't start": "not yet re-checked (first pass: no answer within 150 s)",
             "crashes": "crashes on reset or step",
             "refuses a session": "refuses a session"}
    counts = Counter(r["class"] for r in rows)
    n = len(rows)
    groups = [{"group": label.get(k, k), "count": v, "share": round(v / n, 3)} for k, v in counts.most_common()]
    floors = []
    for r in rows:
        if r["class"] == "suspicious floor":
            null = next((f["return"] for f in r.get("floor", []) if f["policy"] == "null"), None)
            floors.append({"space": r["id"], "do_nothing_score": null})
    floors.sort(key=lambda x: -(x["do_nothing_score"] or 0))
    rechecked = (ROOT / "runs" / "hub" / "sweep" / "census2.jsonl")
    return {"spaces": n, "groups": groups, "sum_of_shares": round(sum(g["share"] for g in groups), 3),
            "do_nothing_highest": floors[:5],
            "do_nothing_at_least_1": sum(1 for f in floors if (f["do_nothing_score"] or 0) >= 1),
            "second_pass_done": len(rechecked.read_text().splitlines()) if rechecked.exists() else 0}


def adversarial_floor() -> dict | None:
    """The can-it-be-gamed check (shortlist/gaming.py) over the small model's families."""
    path = ROOT / "hf" / "gaming.json"
    if not path.exists():
        return None
    g = json.loads(path.read_text())
    return {"families": len(g), "gameable": sum(x["gameable"] for x in g),
            "flagged": [{"suite": x["suite"], "strategy": x["best"]["strategy"], "label": x["best"]["label"], "answer": x["best"]["answer"],
                         "score": x["best"]["score"], "learner_mean": x["learner_mean"]} for x in g if x["gameable"]]}


def main() -> None:
    data = load(RUN)
    verdicts = {s: check_suite(s, rows) for s, rows in data.items() if rows}
    shown = {s: v for s, v in verdicts.items() if s not in EXPERIMENTS}
    rows_shown = [r for s, rows in data.items() if s not in EXPERIMENTS for r in rows]

    played = {p: sum(1 for s in shown if any(r["policy"] == p and not r.get("error") for r in data[s])) for p in PLAYERS}
    by_group: dict[str, Counter] = defaultdict(Counter)
    for v in shown.values():
        key = v.get("judged_for") or "floor players"
        by_group[v.get("group", "?")][key + (" (provisional)" if v.get("provisional") else "")] += 1

    def wins(suite):
        out = {}
        for p in ("null", "random", "beam-low"):
            rs = [r for r in data.get(suite, []) if r["policy"] == p and not r.get("error")]
            if rs:
                out[p] = {"won": sum(r["return"] >= 1 for r in rs), "games": len(rs)}
        return out

    def gate(rows):
        rs = [r for r in rows if r["policy"].startswith("beam") and not r.get("error")]
        return {"cleared_format_gate": sum(r["return"] > -10 for r in rs), "answers": len(rs),
                "fully_correct": sum(r["return"] >= 10 for r in rs),
                "mean_score": round(sum(r["return"] for r in rs) / max(1, len(rs)), 2)}

    pilot = load(PILOT_DIPG) if PILOT_DIPG.exists() else {}
    small_vs_beam = []
    for s, v in sorted(shown.items()):
        t = v["tiers"]
        if "small" in t and "beam-low" in t:
            small_vs_beam.append({"suite": s, "beam_low_solved": t["beam-low"].get("pass@1"),
                                  "small_solved": t["small"].get("pass@1"), "small_mean": round(t["small"]["mean"], 3),
                                  "small_grpo_signal": t["small"].get("grpo_signal"), "verdict": v["verdict"]})
    effort = []
    for s, v in sorted(shown.items()):
        t = v["tiers"]
        rungs = {p: {"solved": t[p].get("pass@1"), "mean": round(t[p]["mean"], 3), "episodes": t[p]["episodes"]}
                 for p in PLAYERS if p.startswith("beam") and p in t}
        if len(rungs) > 1:
            effort.append({"suite": s, "rungs": rungs})
    # Low effort against the highest effort tried, by share solved on the first try.
    pairs = [(e["rungs"]["beam-low"]["solved"], list(e["rungs"].values())[-1]["solved"]) for e in effort
             if "beam-low" in e["rungs"] and e["rungs"]["beam-low"]["solved"] is not None]
    effort_summary = {"suites": len(effort), "compared": len(pairs),
                      "higher_solved_more": sum(hi > lo + 1e-9 for lo, hi in pairs),
                      "same": sum(abs(hi - lo) <= 1e-9 for lo, hi in pairs),
                      "higher_solved_less": sum(hi < lo - 1e-9 for lo, hi in pairs)}

    training = {}
    tdir = ROOT / "training" / "kaggle" / "results"
    if (tdir / "results.json").exists():
        res = json.loads((tdir / "results.json").read_text())
        training = {"families": len(res), "held": sum(r["held"] for r in res),
                    "rows": [{k: r[k] for k in ("family", "prediction", "shortlist_verdict", "improved", "held")} |
                             {"before": r["before"]["mean_score"], "after": r["after"]["mean_score"], "p": r["gain"]["p"]} for r in res]}

    out = {
        "environments": len({v["env"] for v in shown.values()}),
        "task_suites": len(shown),
        "community_environments": sum(1 for s in shown if s.startswith("hub-")),
        "episodes": len(rows_shown),
        "beam_episodes": sum(1 for r in rows_shown if r["policy"].startswith("beam")),
        "small_episodes": sum(1 for r in rows_shown if r["policy"] == "small"),
        "beam_output_tokens": sum(r["tokens"]["completion"] for r in rows_shown if r["policy"].startswith("beam")),
        "suites_played_by": played,
        "verdict_groups": {g: dict(c) for g, c in sorted(by_group.items())},
        "connect4": {"as_shipped": wins("connect4_env"), "with_beams_fix": wins("connect4_env-patched")},
        "dipg": {"default_markers": gate(data.get("dipg_safety_env", [])),
                 "square_brackets": gate(data.get("dipg_safety_env-brackets", [])),
                 "pilot": {k: gate(v) for k, v in pilot.items() if k.startswith("dipg")}},
        "small_vs_beam": small_vs_beam,
        "effort_ladder": effort,
        "effort_summary": effort_summary,
        "adversarial_floor": adversarial_floor(),
        "census": census(),
        "training": training,
    }
    (ROOT / "hf").mkdir(exist_ok=True)
    (ROOT / "hf" / "numbers.json").write_text(json.dumps(out, indent=2))
    print(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()