File size: 19,940 Bytes
99e41a8
 
 
 
 
 
 
 
 
 
b2ead12
 
99e41a8
0b504c6
99e41a8
 
 
 
 
 
 
 
 
 
 
 
0b504c6
 
 
 
 
 
 
caa90b0
0b504c6
 
caa90b0
 
0b504c6
 
 
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b504c6
 
 
f4fdc38
 
 
0b504c6
99e41a8
 
f4fdc38
 
 
99e41a8
0b504c6
99e41a8
0b504c6
 
 
 
 
 
 
 
 
99e41a8
 
 
 
b2ead12
 
 
 
 
0b504c6
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b504c6
b2ead12
 
 
 
 
 
 
 
 
 
 
 
0b504c6
b2ead12
 
 
0b504c6
b2ead12
0b504c6
 
 
b2ead12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b504c6
 
 
 
 
 
 
4432cde
0b504c6
caa90b0
 
 
0b504c6
 
 
caa90b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99e41a8
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""RoboRACE-Bench: run all tracks from cached agent outputs and write the leaderboard.

  python scripts/run_benchmark.py            # -> results/LEADERBOARD.md, results/leaderboard.json
"""
import json
import sys
import time
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from robotics.bench import erqa_swarm, leaderboard, planbench_eval, trackA, trackB, trackC, trackD  # noqa: E402

OUT = Path("results")


def _save(rows, path):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps([{k: v for k, v in r.items() if k != "per_episode"} for r in rows]))


REUSE = "--reuse-tracks" in sys.argv   # load saved Track A/A0/B/C rows instead of recomputing them


def maze_llm_table(d):
    out = []
    for f in sorted(Path(d).glob("*.jsonl")):
        rs = [r for r in map(json.loads, open(f)) if not r.get("error_api") and r["attempts"]]
        rs = list({r["id"]: r for r in rs}.values())
        if len(rs) < 10:
            continue
        m = lambda xs: sum(xs) / len(xs) if xs else None  # noqa: E731
        out.append({"agent": f.stem, "n": len(rs), "oneshot": m([r["oneshot"] for r in rs]), "modulo": m([r["modulo"] for r in rs]),
                    "modulo_4": m([r["modulo"] for r in rs if r["cells"] == 4]),
                    "modulo_6": m([r["modulo"] for r in rs if r["cells"] == 6]), "calls": m([r["calls"] for r in rs]),
                    "n_4": sum(r["cells"] == 4 for r in rs), "n_6": sum(r["cells"] == 6 for r in rs)})
    return sorted(out, key=lambda r: -r["modulo"])


def _rows_or(path, compute):
    if REUSE and path.exists():
        return json.loads(path.read_text())
    return compute()


def main():
    t0 = time.time()
    md = ["# RoboRACE-Bench leaderboard", "",
          "Byzantine-robust multi-agent robotics on CPU. Accuracy in %. Ranks are medians over "
          "2,000 bootstrap resamples of benchmark cells (90% interval in brackets). `REF` rows "
          "use ground-truth labels on the history split and are not ranked. Generated by "
          "`scripts/run_benchmark.py`; do not edit by hand.", ""]
    summary = {}
    pct = lambda x: f"{100 * x:.1f}"  # noqa: E731
    # ------------------------------------------------------------------ famous benchmarks
    md += ["## Part I — public benchmarks", ""]
    if (OUT / "erqa/cosmos_r2_2b.jsonl").exists():
        rep = erqa_swarm.cosmos_reproduction()
        summary["ERQA_reproduction"] = rep
        md += ["### ERQA (Embodied Reasoning QA, 400 questions) — reproduction",
               "",
               f"Cosmos-Reason2-2B on a 4-core CPU (bf16, ≤448² px per image, answer = argmax of option-letter logits): "
               f"**{pct(rep['acc'])}%** (95% CI {pct(rep['lo'])}–{pct(rep['hi'])}, n = {rep['n']}, median "
               f"{rep['median_latency_s']:.1f} s/question). NVIDIA's model card reports **{pct(rep['published'])}%**: "
               f"{'inside' if rep['inside_ci'] else 'OUTSIDE'} our CI.", "",
               "| " + " | ".join(rep["by_type"]) + " |", "|" + "---:|" * len(rep["by_type"]),
               "| " + " | ".join(pct(v) for v in rep["by_type"].values()) + " |", ""]
        for side in (768,):
            pth = OUT / f"erqa/cosmos_r2_2b_{side}px.jsonl"
            if pth.exists() and sum(1 for _ in open(pth)) >= 400:
                r2 = erqa_swarm.cosmos_reproduction(pth)
                a448 = {r["id"]: r for r in map(json.loads, open(OUT / "erqa/cosmos_r2_2b.jsonl"))}
                b = [json.loads(line) for line in open(pth)]
                r2["frac_affected"] = sum(a448[r["id"]]["n_tokens"] != r["n_tokens"] for r in b) / len(b)
                r2["n_changed_answers"] = sum(a448[r["id"]]["pred"] != r["pred"] for r in b)
                from math import comb
                mv = [r for r in b if r["type"] == "Multi-view Reasoning"]
                gain = sum((r["pred"] == r["answer"]) and a448[r["id"]]["pred"] != a448[r["id"]]["answer"] for r in mv)
                loss = sum((r["pred"] != r["answer"]) and a448[r["id"]]["pred"] == a448[r["id"]]["answer"] for r in mv)
                n_d = gain + loss
                r2["mv_gain"], r2["mv_loss"], r2["mv_n"] = gain, loss, len(mv)
                r2["mv_mcnemar_p"] = min(1.0, 2 * sum(comb(n_d, i) for i in range(min(gain, loss) + 1)) / 2 ** n_d) if n_d else 1.0
                summary[f"ERQA_reproduction_{side}"] = r2
                md += [f"Resolution ablation (≤{side}² px): **{pct(r2['acc'])}%** (CI {pct(r2['lo'])}–{pct(r2['hi'])}); only "
                       f"{pct(r2['frac_affected'])}% of questions have an image larger than 448² (the rest are identical inputs) "
                       f"and {r2['n_changed_answers']} answers change; "
                       f"multi-view {pct(r2['by_type'].get('Multi-view Reasoning', float('nan')))}% vs "
                       f"{pct(rep['by_type'].get('Multi-view Reasoning', float('nan')))}% at 448².", ""]
        ev = erqa_swarm.evaluate()
        summary["ERQA_swarm"] = {k: v for k, v in ev.items() if k != "rows"}
        md += [f"### ERQA — multi-agent swarm ({len(ev['agents'])} agents, {ev['n_questions']} questions answered by all)", "",
               "Questions are processed in a seeded random order, so the shared set is a representative sample; "
               "`reweighted` re-weights categories to ERQA's full mix.", "",
               "| system | accuracy | 95% CI | reweighted |", "|---|---:|---|---:|"]
        md += [f"| {t['system']} | **{pct(t['acc'])}** | {pct(t['lo'])}–{pct(t['hi'])} | {pct(t['reweighted'])} |"
               for t in ev["table"]]
        if ev["sota_subset"]:
            ss = ev["sota_subset"]
            md += ["", f"Gemini Robotics-ER 2 (free-tier daily quota: {ss['n']} shared questions only): "
                   + ", ".join(f"{k} {pct(v)}" for k, v in ss.items() if k != "n") + "."]
        # CGA needs the receiver's probabilities, so it only exists for the local Cosmos receiver: rank it in its own
        # table instead of letting it silently restrict the all-receiver table to Cosmos cells.
        rows_all = [r for r in ev["rows"] if r["method"] != "race CGA (new)"]
        rows_cos = [r for r in ev["rows"] if r["receiver"] == "cosmos_r2_2b"]
        text, tab = leaderboard.markdown("ERQA swarm under attack — every agent as receiver",
                                         rows_all, "Attacks: coherent (next wrong letter), random, colluding bloc.")
        text2, tab2 = leaderboard.markdown("ERQA swarm under attack — receiver = Cosmos-Reason2-2B (the robot's own CPU model)",
                                           rows_cos, "Includes CGA, which needs the receiver's own probabilities.")
        md += ["", text, "", text2, ""]
        summary["ERQA_attack"] = tab
        summary["ERQA_attack_cosmos"] = tab2
        _save(ev["rows"], OUT / "erqa/rows.json")
    if (OUT / "planbench").exists():
        pb = planbench_eval.evaluate(min_cov=40)
        summary["PlanBench"] = pb
        md += [f"### PlanBench Blocksworld — plan generation ({pb['n_instances']} instances answered by all of "
               f"{', '.join(pb['agents'])})", "",
               "Validator = exact Blocksworld simulator; it accepts all 500 official ground-truth plans "
               "(`tests/test_blocksworld.py`).", "",
               "| system | success | 95% CI | LLM calls / task |", "|---|---:|---|---:|"]
        md += [f"| {t['system']} | **{pct(t['acc'])}** | {pct(t['lo'])}–{pct(t['hi'])} | {t['calls']:.2f} |"
               for t in pb["table"]]
        md += [""]
    # ------------------------------------------------------------------ RoboRACE tracks
    md += ["## Part II — RoboRACE-Bench tracks", ""]
    for key, name, title in (("A", "so101", "Track A — SO-101 physics rollouts, 5-camera success verification (Cosmos-Reason2-2B)"),
                             ("AP", "panda", "Track A-Panda — cross-embodiment replication on a Franka Panda (all methods and "
                                             "hyper-parameters frozen before this data existed)"),
                             ("A0", "trackA", "Track A0 — procedural tabletop scenes (first iteration; development set for RACE-Net)"),
                             ("AH_so101", "so101_holdout", "Track A-Holdout · SO-101 — fresh episodes, evaluated only after every model and rule was frozen"),
                             ("AH_panda", "panda_holdout", "Track A-Holdout · Franka Panda — fresh episodes, evaluated only after every model and rule was frozen")):
        path, rows_path = OUT / name / "vlm_scores.jsonl", OUT / name / "rows.json"
        if not path.exists():
            continue
        if name.endswith("_holdout") and not (OUT / "holdout/FREEZE.json").exists():
            print(f"[{name}] skipped: no freeze record (scripts/freeze_holdout.py)", flush=True)
            continue
        hist, ev = trackA.load_scores(path)
        if len(ev[1]) < 100:
            continue
        run = lambda only=None: trackA.run(hist, ev, max_subsets=3, receivers=range(len(trackA.CAMS)), only=only)  # noqa: E731
        if REUSE and rows_path.exists():
            rows = json.loads(rows_path.read_text())
            missing = set(trackA.methods()) - {r["method"] for r in rows}
            if missing:                                   # cells are deterministic: add only the new methods
                print(f"[{name}] adding methods: {sorted(missing)}", flush=True)
                rows += run(missing)
        else:
            rows = run()
        text, tab = leaderboard.markdown(title, rows, f"History {len(hist[1])} unlabelled episodes, evaluation "
                                                      f"{len(ev[1])} episodes, 5 camera agents; every camera takes a turn as the receiver.")
        md += [text, ""]
        summary[key] = tab
        pm, pj = leaderboard.paired_markdown(rows, [("race_pool (new)", "race_s_online (new)"), ("race_net (new, learned)", "race_s_online (new)"),
                                                    ("race_net (new, learned)", "race_online (new)"), ("race_s_online (new)", "DS (crowd-kit)"),
                                                    ("race_net (new, learned)", "majority")])
        md += pm
        summary[key + "_paired"] = pj
        _save(rows, rows_path)
    rows = _rows_or(OUT / "trackB/rows.json", lambda: trackB.run(n_missions=40, Fs=(1, 2, 3, 4, 5)))
    text, tab = leaderboard.markdown("Track B — Byzantine-resilient cooperative localization + rendezvous (12 robots)",
                                     rows, "Score = mission success rate (all honest robots within 0.5 m of target).")
    md += [text, ""]
    summary["B"] = tab
    _save(rows, OUT / "trackB/rows.json")
    c_path = OUT / "trackC/answers.jsonl"
    if c_path.exists():
        rows, info = trackC.run(c_path)   # fast; always recomputed
        text, tab = leaderboard.markdown("Track C — LLM planner swarm with real LLM deceivers", rows,
                                         f"Agents (engineered pipeline): {', '.join(info['agents'])}; every agent takes a turn as the receiver. "
                                         f"{info['n_hist']} unlabelled history cases, {info['n_eval']} evaluation cases.")
        sys_text, sys_rows = trackC.systems_table(c_path)
        md += [text, "", sys_text, ""]
        _save(rows, OUT / "trackC/rows.json")
        summary["C"] = tab
        summary["C_systems"] = sys_rows
    d_path = OUT / "trackD/rows.json"
    if REUSE and d_path.exists():
        rows = json.loads(d_path.read_text())
        missing = set(trackD.available_methods()) - {r["method"] for r in rows}
        if missing:                                       # cells are deterministic: add only the new methods
            print(f"[trackD] adding methods: {sorted(missing)}", flush=True)
            rows += trackD.run(n_mazes=20, procs=4, only=missing)
    else:
        rows = trackD.run(n_mazes=20, procs=4)
    _save(rows, d_path)
    ablation = set(trackD.ABLATION_D) | {"race_map" + trackD.MV}
    ranked = [r for r in rows if r["method"] not in ablation]
    text, tab = leaderboard.markdown("Track D — Byzantine cooperative maze exploration (6 mobile robots, 20 mazes)", ranked,
                                     "Score = SPL (success weighted by path length) of honest robots; a robot fails beyond "
                                     "2.5x its optimal path + 10 steps. Baselines: naive merging, majority, W-MSR-style trimming "
                                     "(LeBlanc et al. 2013; F known), EigenTrust (Kamvar et al. 2003), Dawid-Skene (1979), "
                                     "beta-reputation (Josang & Ismail 2002).")
    succ = {}
    for r in ranked:
        succ.setdefault(r["method"], []).append(r["success"])
    md += [text, "", "Goal-reaching rate of honest robots (all cells): "
           + ", ".join(f"{m} {100 * sum(v) / len(v):.1f}%" for m, v in sorted(succ.items(), key=lambda kv: -sum(kv[1]) / len(kv[1]))) + ".", ""]
    pm, pj = leaderboard.paired_markdown(ranked, [("race_net_m" + trackD.MV, "race_map"), ("race_net_m", "race_map"), ("race_net_m" + trackD.MV, "wmsr_trim"),
                                                  ("race_net_m" + trackD.MV, "reputation"), ("race_net_m" + trackD.MV, "REF oracle"),
                                                  ("race_net_m" + trackD.MV, "race_net_m")], cluster="subset")
    md += pm
    summary["D_paired"] = pj
    # ablation: the reachability repair on top of several fusion rules (same cells)
    mean = {}
    for r in rows:
        mean.setdefault(r["method"], {}).setdefault(r["attack"], []).append(r["acc"])
    abl = []
    for base in ("majority", "eigentrust", "reputation", "race_map", "race_net_m"):
        if base in mean and base + trackD.MV in mean:
            f = lambda m, a=None: 100 * float(np.mean(sum(mean[m].values(), []) if a is None else mean[m][a]))  # noqa: E731
            abl.append({"fusion": base, "standard": f(base), "repair": f(base + trackD.MV), "collude_standard": f(base, "collude"),
                        "collude_repair": f(base + trackD.MV, "collude"), "false_walls_standard": f(base, "false_walls"),
                        "false_walls_repair": f(base + trackD.MV, "false_walls")})
    if abl:
        md += ["Ablation — reachability repair on top of each fusion rule (mean SPL x100; same 500 cells):", "",
               "| fusion rule | standard fallback | + reach-repair | collude: standard → repair | false_walls: standard → repair |", "|---|---:|---:|---:|---:|"]
        md += [f"| {r['fusion']} | {r['standard']:.1f} | {r['repair']:.1f} | {r['collude_standard']:.1f} → {r['collude_repair']:.1f} | "
               f"{r['false_walls_standard']:.1f} → {r['false_walls_repair']:.1f} |" for r in abl] + [""]
        summary["D_repair_ablation"] = abl
    summary["D"] = tab
    summary["D_success"] = {m: sum(v) / len(v) for m, v in succ.items()}
    if (OUT / "maze_llm").exists():
        mz = maze_llm_table(OUT / "maze_llm")
        if mz:
            summary["maze_llm"] = mz
            md += ["### LLM agents on procedural text mazes (exact validator, LLM-Modulo ≤3 repairs)", "",
                   "Free-tier quotas cut some agents short, so `n` differs per agent; compare one-shot with LLM-Modulo within a row.", "",
                   "| agent | n | one-shot | LLM-Modulo | 4x4 mazes (Modulo) | 6x6 mazes (Modulo) | calls / maze |", "|---|---:|---:|---:|---:|---:|---:|"]
            sz = lambda r, k: f"{pct(r['modulo_' + k])} (n={r['n_' + k]})" if r["n_" + k] else "–"  # noqa: E731
            md += [f"| {r['agent']} | {r['n']} | {pct(r['oneshot'])} | **{pct(r['modulo'])}** | {sz(r, '4')} | "
                   f"{sz(r, '6')} | {r['calls']:.2f} |" for r in mz]
            md += [""]
    ref = OUT / "published/reference_numbers.json"
    if ref.exists():
        from robotics.eval.stats import wilson
        pub = json.loads(ref.read_text())
        summary["published"] = pub
        agents = []
        for f in sorted((OUT / "erqa").glob("*.jsonl")):
            if f.stem.startswith("cosmos_r2_2b"):
                continue
            rs = list({r["id"]: r for r in map(json.loads, open(f)) if r.get("pred") is not None}.values())
            if len(rs) >= 25:
                k = sum(r["pred"] == r["answer"] for r in rs)
                lo, hi = wilson(k, len(rs))
                agents.append({"agent": erqa_swarm.PRETTY.get(f.stem, f.stem), "n": len(rs), "acc": k / len(rs), "lo": lo, "hi": hi})
        summary["ERQA_agents"] = sorted(agents, key=lambda a: -a["acc"])
        pb_agents = []
        for f in sorted((OUT / "planbench").glob("*.jsonl")):
            rs = list({r["instance_id"]: r for r in map(json.loads, open(f)) if not r.get("error_api") and r["attempts"]}.values())
            if len(rs) >= 25:
                pb_agents.append({"agent": f.stem, "n": len(rs), "oneshot": sum(r["oneshot"] for r in rs) / len(rs),
                                  "modulo": sum(r["modulo"] for r in rs) / len(rs), "calls": sum(r["calls"] for r in rs) / len(rs)})
        summary["PlanBench_agents"] = sorted(pb_agents, key=lambda a: -a["modulo"])
        md += ["## Part III — context: published numbers next to ours", "",
               "Published numbers are copied from the cited tables. They are context, not same-condition comparisons: models, "
               "dates and (for PlanBench) instance subsets differ.", "",
               "### ERQA (400 multiple-choice questions; chance = 25%)", "", "| model | ERQA % | source |", "|---|---:|---|"]
        rows_e = [(k, v, "Gemini Robotics paper, arXiv:2503.20020 (Feb 2025), no CoT") for k, v in pub["ERQA"]["no_cot"].items()]
        rows_e += [(k + " + CoT", v, "same paper, with chain-of-thought") for k, v in pub["ERQA"]["with_cot"].items()]
        rows_e += [(k, v, "NVIDIA Cosmos-Reason2 model card") for k, v in pub["ERQA"]["model_card"].items()]
        if "ERQA_reproduction" in summary:
            r0 = summary["ERQA_reproduction"]
            rows_e.append((f"**Cosmos-Reason2-2B, our CPU run** (n={r0['n']}, CI {pct(r0['lo'])}–{pct(r0['hi'])})", 100 * r0["acc"], "this repo"))
        for a_ in summary["ERQA_agents"]:
            rows_e.append((f"**{a_['agent']}** (n={a_['n']}, CI {pct(a_['lo'])}–{pct(a_['hi'])})", 100 * a_["acc"], "this repo, hosted API, brief-reasoning prompt"))
        md += [f"| {k} | {v:.1f} | {src} |" for k, v, src in sorted(rows_e, key=lambda t: -t[1])]
        md += ["", "### PlanBench Blocksworld plan generation", "", "| model / system | success % | source |", "|---|---:|---|"]
        rows_p = [(k + " · one-shot", v, "arXiv:2409.13373, 600 instances") for k, v in pub["PlanBench_Blocksworld"]["one_shot"].items()]
        rows_p += [(k + " · zero-shot", v, "arXiv:2409.13373, 600 instances") for k, v in pub["PlanBench_Blocksworld"]["zero_shot"].items()]
        rows_p.append(("GPT-4 + VAL back-prompting ≤15 rounds (LLM-Modulo)", pub["PlanBench_Blocksworld"]["llm_modulo"]["value"],
                       "arXiv:2402.01817 citing arXiv:2305.15771 (subset of failed instances)"))
        for a_ in summary["PlanBench_agents"]:
            rows_p.append((f"**{a_['agent']} · one-shot** (n={a_['n']})", 100 * a_["oneshot"], "this repo, official prompt"))
            rows_p.append((f"**{a_['agent']} · LLM-Modulo ≤3 repairs** (n={a_['n']}, {a_['calls']:.2f} calls)", 100 * a_["modulo"], "this repo, exact validator"))
        md += [f"| {k} | {v:.1f} | {src} |" for k, v, src in sorted(rows_p, key=lambda t: -t[1])]
        md += [""]
    (OUT / "LEADERBOARD.md").write_text("\n".join(md))
    (OUT / "leaderboard.json").write_text(json.dumps(summary, indent=1, default=float))
    print("\n".join(md))
    print(f"\n[{time.time() - t0:.0f}s]")


if __name__ == "__main__":
    main()