File size: 9,718 Bytes
a2b0c04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c7f145
 
 
 
 
 
 
 
 
a2b0c04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c7f145
 
 
 
 
 
 
ad54cd3
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
"""Build the Hugging Face dataset folder and the Space's data file from the recorded runs.

    python scripts/figures.py && python scripts/export.py

The clean run (runs/day2) is the result; the earlier runs (day1, day1b, day1c) are the pilot and are published
separately. Writes:
  hf/dataset/episodes.jsonl        every clean-run episode (reasoning trimmed to 2,000 characters per step)
  hf/dataset/pilot_episodes.jsonl  the pilot runs, before the harness fixes
  hf/dataset/verdicts.json         the learnability checks and verdict per task suite
  hf/dataset/census/               the Hub census (both passes) and Beam-written community setups
  hf/dataset/fixes/                Beam's diagnosis, reasoning and patch for each fixed environment
  hf/space/data.json               what the Space shows (numbers from hf/numbers.json)
"""

import base64
import json
import shutil
import sys
from collections import defaultdict
from pathlib import Path

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

HF = ROOT / "hf"


def load(runs: list[Path]) -> dict[str, list[dict]]:
    pooled: dict[str, list[dict]] = defaultdict(list)
    for run in runs:
        for path in sorted(run.glob("*.jsonl")):
            for line in path.read_text().splitlines():
                if line.strip():
                    r = json.loads(line)
                    r["run"] = run.name
                    pooled[path.stem].append(r)
    return pooled


def trim(r: dict) -> dict:
    r = dict(r)
    r.pop("traceback", None)
    steps = []
    for s in r.get("steps", []):
        s = dict(s)
        if "beam" in s:
            b = dict(s["beam"])
            if b.get("reasoning"):
                b["reasoning"] = b["reasoning"][:2000]
            s["beam"] = b
        steps.append(s)
    r["steps"] = steps
    return r


def connect4_story(numbers: dict) -> dict:
    reply = (ROOT / "runs/fixes/connect4_env.beam-reply.md").read_text()
    return {"env": "connect4_env", "as_shipped": numbers["connect4"]["as_shipped"],
            "with_beams_fix": numbers["connect4"]["with_beams_fix"], "diagnosis": reply.split("### FILE:")[0].strip()}


def dipg_story(pooled: dict[str, list[dict]]) -> dict | None:
    """How often Beam's answer clears DIPG's format gate under each marker style."""
    variants = [("dipg_safety_env", "Harmony markers (default)", "<|channel|>analysis<|message|> … <|end|>"),
                ("dipg_safety_env-plain", "Angle-bracket markers", "<analysis> … <end>"),
                ("dipg_safety_env-brackets", "Square-bracket markers", "[analysis] … [end]")]
    out = []
    for suite, label, example in variants:
        rows = [r for r in pooled.get(suite, []) if r["policy"].startswith("beam") and not r.get("error")]
        if rows:
            passed = sum(r["return"] > -10 for r in rows)  # -10 is the format-mismatch penalty
            out.append({"suite": suite, "label": label, "example": example, "passed": passed, "answers": len(rows)})
    return {"variants": out} if out else None


def rail(v: dict, rows: list[dict]) -> dict:
    """Place each rung's mean score on one axis: 0 = the worst episode seen, 1 = the best possible (or best episode seen)."""
    tiers = v["tiers"]
    scores = [score(r) for r in rows if not r.get("error")] or [0.0]
    cfg = suite_config(v["suite"])
    cfg_top = cfg.max_score if cfg and not v.get("declared_max_wrong") else None  # a beaten guess is no maximum
    hi = cfg_top if cfg_top is not None else max(scores)
    lo = min(scores)
    if hi - lo < 1e-9:  # every episode scored the same
        if cfg_top is not None and not cfg.setup_by:
            lo = hi - 1.0  # and that score is the known maximum: put the rungs at the top
        else:
            cfg_top = None  # a guessed maximum (community setups) that nobody moved off says nothing
    span = (hi - lo) or 1.0
    order = ["null", "random", "small", "beam-low", "beam-medium", "beam-high", "beam-xhigh", "beam-max"]
    return {"rungs": [{"policy": p, "x": round((tiers[p]["mean"] - lo) / span, 4), "mean": tiers[p]["mean"],
                       "solved": tiers[p].get("pass@1"), "grpo": tiers[p].get("grpo_signal"), "n": tiers[p]["episodes"]}
                      for p in order if p in tiers],
            "top_known": cfg_top is not None}


def pelicans(rows: list[dict]) -> list[dict]:
    out = []
    for r in rows:
        if not r["policy"].startswith("beam") or not r.get("steps"):
            continue
        raw = (r["steps"][0].get("action") or {}).get("response", "")
        start, end = raw.find("<svg"), raw.rfind("</svg>")
        if start < 0 or end < 0:
            continue
        svg = raw[start:end + len("</svg>")]  # drop any text or fences around the drawing
        head = svg[:svg.find(">") + 1]
        if "xmlns=" not in head:  # an <img> only renders SVG that declares its namespace
            svg = svg.replace("<svg", '<svg xmlns="http://www.w3.org/2000/svg"', 1)
        fo = r.get("final_observation", {})
        out.append({"svg_b64": base64.b64encode(svg.encode()).decode(), "reward": r["return"],
                    "structure": fo.get("structure_score"), "judged": fo.get("judged"), "policy": r["policy"]})
    return out


def main() -> None:
    clean = load([ROOT / "runs" / "day2"])
    clean = {k: [r for r in v if not harness_error(r)] for k, v in clean.items()}
    pilot = load([ROOT / "runs" / d for d in ("day1", "day1b", "day1c")])
    numbers = json.loads((HF / "numbers.json").read_text())
    verdicts = [check_suite(s, rows) for s, rows in sorted(clean.items()) if rows]
    gaming = {g["suite"]: g for g in json.loads((HF / "gaming.json").read_text())} if (HF / "gaming.json").exists() else {}
    for x in verdicts:  # RFC 008 #26, our procedure (shortlist/gaming.py); added after the training proof
        g = gaming.get(x["suite"])
        if g:
            b = g["best"]
            x["checks"]["statistical.adversarial_floor"] = {
                "pass": not g["gameable"], "strategy": b["strategy"], "label": b["label"], "answer": b["answer"], "score": b["score"],
                "learner_mean": g["learner_mean"], "added_after_training": True}
            x["gameable"] = g["gameable"]
    for d in ("fixes", "census", "census/setups"):
        (HF / "dataset" / d).mkdir(parents=True, exist_ok=True)
    (HF / "space").mkdir(parents=True, exist_ok=True)

    for name, pooled in (("episodes.jsonl", clean), ("pilot_episodes.jsonl", pilot)):
        with (HF / "dataset" / name).open("w") as f:
            for suite, rows in sorted(pooled.items()):
                for r in rows:
                    f.write(json.dumps(trim(r), default=str) + "\n")
    (HF / "dataset" / "verdicts.json").write_text(json.dumps(verdicts, indent=2))
    for p in (ROOT / "runs" / "fixes").glob("*.*"):
        if p.is_file():
            shutil.copy(p, HF / "dataset" / "fixes" / p.name)
    for p in ("census.jsonl", "census2.jsonl", "chosen.json"):
        if (ROOT / "runs" / "hub" / "sweep" / p).exists():
            shutil.copy(ROOT / "runs" / "hub" / "sweep" / p, HF / "dataset" / "census" / p)
    for p in (ROOT / "runs" / "hub" / "setups").glob("*.json"):
        shutil.copy(p, HF / "dataset" / "census" / "setups" / p.name)

    shown = [x for x in verdicts if not x["suite"].startswith("dipg_safety_env-")]  # marker experiments go in the DIPG story
    training = json.loads((ROOT / "training" / "kaggle" / "analysis.json").read_text())
    maze_dir = ROOT / "training" / "maze"
    forward = None
    if (maze_dir / "predictions.json").exists():
        pred = json.loads((maze_dir / "predictions.json").read_text())
        forward = {"family": "maze", "written_at": pred["written_at"], "claims": pred["predictions"][0]["claims"],
                   "evidence": pred["predictions"][0]["evidence_before_training"],
                   "sha256": (maze_dir / "predictions.sha256").read_text().split()[0],
                   "result": json.loads((maze_dir / "results" / "analysis.json").read_text()) if (maze_dir / "results" / "analysis.json").exists() else None}
    data = {
        "numbers": {k: numbers[k] for k in ("environments", "task_suites", "community_environments", "episodes",
                                             "beam_episodes", "small_episodes", "beam_output_tokens", "suites_played_by")},
        "verdicts": [{**{k: v for k, v in x.items() if k != "error_examples"}, "rail": rail(x, clean[x["suite"]])} for x in shown],
        "connect4": connect4_story(numbers), "dipg": numbers["dipg"], "effort": numbers["effort_ladder"], "effort_summary": numbers["effort_summary"],
        "census": numbers["census"], "training": training, "forward_test": forward,
        "pelicans": pelicans(clean.get("pelican_svg_env", [])),
        "links": {"dataset": "https://huggingface.co/datasets/JagritGumber/shortlist",
                  "code": "https://huggingface.co/datasets/JagritGumber/shortlist/tree/main/code",
                  "patch": "https://huggingface.co/datasets/JagritGumber/shortlist/blob/main/fixes/connect4_env.patch",
                  "training": "https://huggingface.co/datasets/JagritGumber/shortlist/blob/main/training/RESULTS.md",
                  "rfc": "https://github.com/openenv/OpenEnv/blob/main/rfcs/008-environment-auto-validation.md"},
    }
    (HF / "space" / "data.json").write_text(json.dumps(data, indent=1, default=str))
    print(json.dumps(data["numbers"]), f"\nverdicts: {len(shown)}  pelicans: {len(data['pelicans'])}  training rows: {len(training['rows'])}")


if __name__ == "__main__":
    main()