RoboRACE-Bench / scripts /make_figures.py
Nabidnur's picture
RoboRACE: code, cached agent outputs, results, media, SO-101 renders (part 9)
f4fdc38 verified
Raw History Blame Contribute Delete
41.9 kB
#!/usr/bin/env python3
"""All README figures, generated from results/ (run scripts/run_benchmark.py first)."""
import json
import sys
from collections import defaultdict
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from robotics.bench import trackA # noqa: E402
from robotics.swarm import attacks, fusion # noqa: E402
OUT = Path("media/figures")
OUT.mkdir(parents=True, exist_ok=True)
R = Path("results")
OURS = "#0f766e" # teal: methods introduced in this repo
RACE = "#2563eb" # blue: RACE (prior work by the same program)
BASE = "#9ca3af" # grey: baselines
REF = "#d97706" # amber: labelled reference
plt.rcParams.update({"font.size": 10, "axes.spines.top": False, "axes.spines.right": False,
"figure.dpi": 150, "savefig.bbox": "tight", "font.family": "DejaVu Sans"})
def color(m):
if "(new" in m or m.startswith(("race_c", "race_s", "race_map", "race_net")):
return OURS
if m.startswith("race"):
return RACE
if m.startswith("REF"):
return REF
return BASE
ROWS = {"A": "so101/rows.json", "AP": "panda/rows.json", "A0": "trackA/rows.json", "B": "trackB/rows.json",
"AH_so101": "so101_holdout/rows.json", "AH_panda": "panda_holdout/rows.json",
"C": "trackC/rows.json", "D": "trackD/rows.json", "ERQA": "erqa/rows.json"}
D_ABLATION = {m + " + reach-repair" for m in ("majority", "eigentrust", "reputation", "race_map")} # shown as a table only
def load(track):
rows = json.loads((R / ROWS[track]).read_text())
return [r for r in rows if r["method"] not in D_ABLATION] if track == "D" else rows
def mean_by(rows, key):
d = defaultdict(list)
for r in rows:
d[key(r)].append(r["acc"])
return {k: float(np.mean(v)) for k, v in d.items()}
def leaderboard_bars(track, title, fname, subtitle):
rows = load(track)
overall = mean_by(rows, lambda r: r["method"])
maj = mean_by([r for r in rows if r["attack"] != "none" and r["f"] >= 0.5], lambda r: r["method"])
clean = mean_by([r for r in rows if r["attack"] == "none"], lambda r: r["method"])
ms = sorted(overall, key=overall.get)
fig, ax = plt.subplots(figsize=(7.5, 0.42 * len(ms) + 1.2))
y = np.arange(len(ms))
ax.barh(y, [100 * overall[m] for m in ms], color=[color(m) for m in ms], height=0.62)
ax.scatter([100 * clean.get(m, np.nan) for m in ms], y, marker="|", s=160, color="black", zorder=3, label="no attack")
if maj:
ax.scatter([100 * maj.get(m, np.nan) for m in ms], y, marker="x", s=36, color="#b91c1c", zorder=3, label="liars ≥ 50%")
for yi, m in zip(y, ms):
v = 100 * overall[m]
if v >= 15: # value at the start of the bar: markers (clean |, liar-majority x) can never cover it
ax.text(1.2, yi, f"{v:.1f}", va="center", ha="left", fontsize=8.5, color="white", fontweight="bold")
else:
ax.text(v + 0.8, yi, f"{v:.1f}", va="center", fontsize=8.5)
ax.set_yticks(y, ms)
ax.set_xlim(0, 105)
ax.set_xlabel("accuracy / success (%) — bar = mean over all benchmark cells")
ax.set_title(f"{title}\n", loc="left", fontweight="bold")
ax.text(0, 1.01, subtitle, transform=ax.transAxes, fontsize=8.5, color="#4b5563")
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.09 - 0.25 / len(ms)), frameon=False, fontsize=8, ncol=2)
fig.savefig(OUT / fname)
plt.close(fig)
def curves_vs_liars(track, fname, title, methods, attacks_shown, xlabel="number of liars", ylabel="accuracy / success (%)"):
rows = load(track)
fig, axs = plt.subplots(1, len(attacks_shown), figsize=(3.2 * len(attacks_shown), 3.1), sharey=True)
clean = mean_by([r for r in rows if r["attack"] == "none"], lambda r: r["method"])
# baselines get distinct muted hues, markers and dashes so every line can be told apart
base_pal = dict(zip([m for m in methods if color(m) == BASE], ["#475569", "#c2410c", "#a16207", "#be185d", "#94a3b8"]))
base_ls = dict(zip(base_pal, ["--", (0, (1, 1.2)), (0, (5, 1.5, 1, 1.5)), (0, (3, 1)), ":"]))
for ax, atk in zip(axs, attacks_shown):
d = mean_by([r for r in rows if r["attack"] == atk], lambda r: (r["method"], r["liars"]))
for m in methods:
xs = sorted({k[1] for k in d if k[0] == m})
c = {"race_online (new)": "#5eb8ad", "race CGA (new)": "#0891b2", "race_net (new, learned)": "#7c3aed", "race_map": "#5eb8ad",
**base_pal}.get(m, color(m))
ls = (0, (4, 1.5)) if m in ("race_online (new)", "race CGA (new)", "race_map") else ("-" if color(m) != BASE else base_ls[m])
base_style = dict(lw=1.3, alpha=0.95) if color(m) == BASE else dict(lw=2.6, zorder=3)
mk = {"receiver_only": "s", "majority": "v", "dawid_skene": "^", "mean": "D", "DS (crowd-kit)": "^",
"wmsr": "s", "geomedian": "^", "median": "v", "reputation": "s", "solo": "D", "trust_all": "^"}.get(m, "o")
ax.plot([0] + xs, [100 * clean[m]] + [100 * d[(m, x)] for x in xs], marker=mk, ms=3.8,
color=c, ls=ls, label=m, **base_style)
ax.set_title(atk, fontsize=10)
ax.set_xlabel(xlabel)
ax.set_ylim(0, 102)
ax.grid(alpha=0.25)
axs[0].set_ylabel(ylabel)
axs[-1].legend(fontsize=8, frameon=False, loc="center left", bbox_to_anchor=(1.02, 0.5), handlelength=3.2)
fig.suptitle(title, x=0.01, y=1.04, ha="left", fontweight="bold")
fig.savefig(OUT / fname)
plt.close(fig)
def _need_so101_data(fig_name):
if not Path("data/so101/episodes.jsonl").exists():
print(f"skip {fig_name}: needs data/so101 (run scripts/so101_generate.py); keeping the committed figure")
return True
return False
def camera_quality():
if _need_so101_data("trackA_cameras.png"):
return
(Ph, yh, _), (Pe, ye, _) = trackA.load_scores(R / "so101/vlm_scores.jsonl")
au = [trackA.auroc(Pe[:, j], ye) for j in range(5)]
from PIL import Image
from robotics.sim.so101_env import CAMERAS
eps = [json.loads(line) for line in open("data/so101/episodes.jsonl")]
e = next(x for x in eps if x["split"] == "eval" and x["mode"] == "wrong_place")
class S: # minimal view of an episode for the panel title
task, success = e["task"], e["success"]
s = S()
fig = plt.figure(figsize=(13, 2.9))
for j, c in enumerate(CAMERAS):
ax = fig.add_subplot(1, 6, j + 1)
ax.imshow(Image.open(f"data/so101/eval/{e['seed']}/{c}.png"))
ax.set_title(f"{c}\nAUROC {au[j]:.2f}", fontsize=9)
ax.axis("off")
ax = fig.add_subplot(1, 6, 6)
ax.bar(range(5), au, color=[OURS if a == max(au) else BASE for a in au])
ax.set_xticks(range(5), CAMERAS, rotation=45, fontsize=8)
ax.set_ylim(0.5, 1)
ax.set_title("AUROC per camera\n(evaluation split)", fontsize=9)
fig.suptitle(f"Track A agents (SO-101): five cameras, one VLM\nnear-miss episode · task “{s.task}” · ground truth: "
f"{'success' if s.success else 'FAILURE'}", x=0.01, y=1.13, ha="left", fontweight="bold", fontsize=10)
fig.savefig(OUT / "trackA_cameras.png")
plt.close(fig)
def verifier_calibration():
rows = [json.loads(line) for line in open(R / "verifier_cosmos_reason2_2b.jsonl")]
test = [r for r in rows if r["split"] == "test"]
p = np.array([r["p"] for r in test])
y = np.array([r["gt"] for r in test])
thr = rows[0]["threshold"]
naive, calib = np.mean((p >= .5) == y), np.mean((p >= thr) == y)
fig, axs = plt.subplots(1, 2, figsize=(11, 3.8), gridspec_kw={"wspace": 0.28})
bins = np.linspace(0, 1, 26)
axs[0].hist(p[y], bins, alpha=0.75, color=OURS, label="true success")
axs[0].hist(p[~y], bins, alpha=0.75, color="#b91c1c", label="true failure")
axs[0].axvline(0.5, color="black", ls="--", lw=1, label=f"naive threshold 0.5 → {100 * naive:.0f}% acc.")
axs[0].axvline(thr, color=OURS, lw=2, label=f"calibrated threshold {thr:.2f} → {100 * calib:.0f}% acc.")
axs[0].set_xlabel("Cosmos-Reason2 P(success)")
axs[0].set_ylabel("held-out scenes")
axs[0].legend(frameon=True, framealpha=0.95, edgecolor="white", fontsize=8, loc="upper left")
axs[0].set_title("held-out score distribution", fontsize=10)
ts = np.linspace(0, 1, 201)
axs[1].plot([np.mean(p[~y] >= t) for t in ts], [np.mean(p[y] >= t) for t in ts], color=OURS, lw=2)
axs[1].plot([0, 1], [0, 1], color=BASE, ls="--")
axs[1].set_xlabel("false-positive rate")
axs[1].set_ylabel("true-positive rate")
axs[1].set_title(f"ROC — AUROC {trackA.auroc(p, y):.3f}", fontsize=10)
fig.suptitle("Cosmos-Reason2-2B as a success verifier on CPU (1.4 s / image)", x=0.01, y=1.03, ha="left",
fontweight="bold")
fig.savefig(OUT / "verifier_calibration.png")
plt.close(fig)
def race_weights():
"""RACE-S signed agent weights: liars get NEGATIVE weight (inverted, still informative)."""
(Ph, yh, _), (Pe, ye, _) = trackA.load_scores(R / "so101/vlm_scores.jsonl")
conds = [("none", []), ("invert", [1, 2]), ("invert", [1, 2, 3, 4]), ("collude", [2, 3, 4]),
("noise", [1, 4]), ("stuck", [3])]
W = []
for atk, liars in conds:
Pa = attacks.apply(Pe, liars, atk, "eval", np.random.default_rng(0)) if liars else Pe
W.append(fusion.race_s(Pa, Pa, 0)[2]["weight"])
W = np.array(W)
fig, ax = plt.subplots(figsize=(6.4, 3.4))
lim = np.abs(W).max()
im = ax.imshow(W, cmap="RdBu", vmin=-lim, vmax=lim, aspect="auto")
for i in range(W.shape[0]):
for j in range(W.shape[1]):
liar = j in conds[i][1]
ax.text(j, i, f"{W[i, j]:+.1f}" + ("\nliar" if liar else ""), ha="center", va="center", fontsize=7.5,
color="white" if abs(W[i, j]) > lim * 0.55 else "black", fontweight="bold" if liar else None)
ax.set_xticks(range(5), trackA.CAMS)
ax.set_yticks(range(len(conds)), [f"{a} {l}" if l else "no attack" for a, l in conds], fontsize=8)
plt.colorbar(im, ax=ax, label="signed evidence weight")
ax.set_title("RACE-S learns, without labels, to INVERT lying cameras (negative weight)\n"
"and to ignore noise / stuck ones (≈0). Receiver = front.", fontsize=9.5, loc="left")
fig.savefig(OUT / "race_s_weights.jpg", pil_kwargs={"quality": 92}) # .jpg name chosen by the repo owner
plt.close(fig)
def trackC_systems():
lb = json.loads((R / "leaderboard.json").read_text())["C_systems"]
by = {r["system"]: r for r in lb}
models = [n[:-len(" zero-shot")] for n in by if n.endswith("zero-shot") and not n.startswith("swarm")]
models.sort(key=lambda m: by[m + " zero-shot"]["acc"])
swarms = [n for n in by if n.startswith(("swarm", "small"))]
fig, ax = plt.subplots(figsize=(8.2, 0.48 * (len(models) + len(swarms)) + 1.4))
y = 0
labels = []
for m in models:
z, e = by[m + " zero-shot"], by[m + " engineered"]
ax.plot([100 * z["acc"], 100 * e["acc"]], [y, y], color=OURS, lw=2.5, alpha=0.5)
ax.scatter(100 * z["acc"], y, color=BASE, s=60, zorder=3)
ax.scatter(100 * e["acc"], y, color=OURS, s=60, zorder=3)
ax.text(101.5, y, f"{100 * z['acc']:.0f} → {100 * e['acc']:.0f} (+{100 * (e['acc'] - z['acc']):.0f})",
va="center", fontsize=8.5, color=OURS if e["acc"] > z["acc"] else "black")
labels.append(m)
y += 1
y += 0.4
for n in swarms:
r = by[n]
c = OURS if "engineered" in n else BASE
ax.scatter(100 * r["acc"], y, marker="s", color=c, s=55, zorder=3)
ax.text(101.5, y, f"{100 * r['acc']:.0f} · {r['llm_calls_per_task']:.1f} calls/task", va="center", fontsize=8.5)
labels.append(n)
y += 1
ax.set_yticks(np.r_[np.arange(len(models)), np.arange(len(swarms)) + len(models) + 0.4], labels, fontsize=8.5)
ax.set_xlim(60, 100.5)
ax.set_xlabel("exact-plan accuracy on 42 procedural tasks (%)")
ax.grid(axis="x", alpha=0.25)
ax.scatter([], [], color=BASE, label="zero-shot")
ax.scatter([], [], color=OURS, label="engineered: spec + few-shot + grounded validator + repair")
ax.legend(loc="upper left", frameon=False, fontsize=8)
ax.set_title("Track C — same models, better plumbing", loc="left", fontweight="bold")
fig.savefig(OUT / "trackC_systems.png")
plt.close(fig)
def heatmap(track, fname, title):
rows = load(track)
d = mean_by(rows, lambda r: (r["method"], r["attack"]))
ms = sorted({k[0] for k in d}, key=lambda m: -np.mean([v for k, v in d.items() if k[0] == m]))
ats = sorted({k[1] for k in d}, key=lambda a: (a != "none", a))
M = np.array([[100 * d.get((m, a), np.nan) for a in ats] for m in ms])
fig, ax = plt.subplots(figsize=(0.9 * len(ats) + 2.6, 0.38 * len(ms) + 1.2))
ax.imshow(M, cmap="viridis", vmin=0, vmax=100, aspect="auto")
for i in range(len(ms)):
for j in range(len(ats)):
ax.text(j, i, f"{M[i, j]:.0f}", ha="center", va="center", fontsize=8,
color="white" if M[i, j] < 60 else "black")
ax.set_xticks(range(len(ats)), ats, rotation=30)
ax.set_yticks(range(len(ms)), ms)
for t in ax.get_yticklabels():
t.set_color(color(t.get_text()) if color(t.get_text()) != BASE else "black")
t.set_fontweight("bold" if color(t.get_text()) == OURS else None)
ax.set_title(title, loc="left", fontweight="bold", fontsize=10)
fig.savefig(OUT / fname)
plt.close(fig)
def overview():
lb = json.loads((R / "leaderboard.json").read_text())
fig, axs = plt.subplots(1, 3, figsize=(12, 3.2))
spec = [("A", "Track A · camera swarm verifier", "accuracy"), ("B", "Track B · multi-robot rendezvous", "success"),
("C", "Track C · LLM planner swarm", "accuracy")]
for ax, (t, title, unit) in zip(axs, spec):
if t == "C":
sysr = {r["system"]: r for r in lb["C_systems"]}
zs = [r["acc"] for n, r in sysr.items() if n.endswith("zero-shot") and not n.startswith("swarm")]
es = [r["acc"] for n, r in sysr.items() if n.endswith("engineered") and not n.startswith(("swarm", "small"))]
small = next(r["acc"] for n, r in sysr.items() if n.startswith("small"))
items = [("zero-shot\n(mean of 4 LLMs)", np.mean(zs), BASE), ("engineered\n(mean of 4 LLMs)", np.mean(es), OURS),
("engineered small-\nmodel swarm", small, OURS)]
for i, (lab, v, c) in enumerate(items):
ax.bar(i, 100 * v, color=c, width=0.6)
ax.text(i, 100 * v + 1.5, f"{100 * v:.1f}", ha="center", fontweight="bold")
ax.set_xticks(range(3), [x[0] for x in items], fontsize=7.5)
ax.set_ylim(0, 108)
ax.set_title(title + " (no attack)", fontsize=10, fontweight="bold")
ax.set_ylabel("exact-plan accuracy (%)")
continue
tab = [r for r in lb[t] if not r["method"].startswith("REF") and "ablation" not in r["method"]]
ours = max((r for r in tab if color(r["method"]) == OURS), key=lambda r: r["mean_acc"], default=None)
racer = max((r for r in tab if color(r["method"]) == RACE), key=lambda r: r["mean_acc"], default=None)
base = max((r for r in tab if color(r["method"]) == BASE), key=lambda r: r["mean_acc"])
items = [x for x in (("best baseline\n" + base["method"], base, BASE),
("RACE\n" + racer["method"] if racer else None, racer, RACE),
("ours\n" + ours["method"] if ours else None, ours, OURS)) if x[1]]
for i, (lab, r, c) in enumerate(items):
ax.bar(i, 100 * r["mean_acc"], color=c, width=0.6)
ax.bar(i, 100 * r["majority_liars"] if r["majority_liars"] == r["majority_liars"] else 0,
color="black", alpha=0.18, width=0.6)
ax.text(i, 100 * r["mean_acc"] + 1.5, f"{100 * r['mean_acc']:.1f}", ha="center", fontweight="bold")
import textwrap
ax.set_xticks(range(len(items)), ["\n".join(textwrap.wrap(x[0].replace("\n", " · "), 18)) for x in items], fontsize=7.5)
ax.set_ylim(0, 108)
ax.set_title(title, fontsize=10, fontweight="bold")
ax.set_ylabel(f"mean {unit} (%)")
fig.suptitle("RoboRACE-Bench — best method per family (dark inner bar = liar-majority cells)",
x=0.01, y=1.04, ha="left", fontweight="bold")
fig.savefig(OUT / "overview.png")
plt.close(fig)
def so101_gallery():
if _need_so101_data("so101_gallery.png"):
return
from PIL import Image
from robotics.sim.so101_env import CAMERAS
eps = [json.loads(line) for line in open("data/so101/episodes.jsonl") if json.loads(line)["split"] == "eval"]
pick = []
for mode in ("success", "wrong_place", "wrong_object", "drop_transit", "miss_grasp"):
pick.append(next(e for e in eps if e["mode"] == mode))
fig, axs = plt.subplots(len(pick), 5, figsize=(11, 2.35 * len(pick)))
for i, e in enumerate(pick):
for j, c in enumerate(CAMERAS):
ax = axs[i, j]
ax.imshow(Image.open(f"data/so101/eval/{e['seed']}/{c}.png"))
ax.set_xticks([])
ax.set_yticks([])
for sp in ax.spines.values():
sp.set_visible(True)
sp.set_edgecolor(OURS if e["success"] else "#b91c1c")
sp.set_linewidth(2.5)
if i == 0:
ax.set_title(c, fontsize=10)
axs[i, 0].set_ylabel(f"{e['mode'].replace('_', ' ')}\n{'SUCCESS' if e['success'] else 'FAILURE'}", fontsize=9,
color=OURS if e["success"] else "#b91c1c", fontweight="bold")
axs[i, 4].text(1.04, 0.5, f"“{e['task']}”", transform=axs[i, 4].transAxes, rotation=270, va="center", fontsize=7.5)
fig.suptitle("SO-101 rollouts: 5 camera agents per episode; label = final physics state (green success, red failure)",
x=0.01, ha="left", fontweight="bold", y=1.0)
fig.tight_layout()
fig.savefig(OUT / "so101_gallery.png")
plt.close(fig)
def erqa_figures():
lb = json.loads((R / "leaderboard.json").read_text())
rep = lb.get("ERQA_reproduction")
if not rep:
return
hi = lb.get("ERQA_reproduction_768")
types = list(rep["by_type"])
sw = lb["ERQA_swarm"]
fig, axs = plt.subplots(1, 2, figsize=(13, 4.2), gridspec_kw={"width_ratios": [1.25, 1]})
ax = axs[0]
x = np.arange(len(types))
ax.bar(x - 0.2 if hi else x, [100 * rep["by_type"][t] for t in types], width=0.4 if hi else 0.6, color=OURS,
label=f"Cosmos-Reason2-2B ≤448² px ({100 * rep['acc']:.1f}%)")
if hi:
ax.bar(x + 0.2, [100 * hi["by_type"][t] for t in types], width=0.4, color="#5eb8ad",
label=f"≤768² px ({100 * hi['acc']:.1f}%)")
ax.axhline(100 * rep["published"], color=REF, ls="--", lw=1.5, label=f"NVIDIA reported overall ({100 * rep['published']:.2f}%)")
ax.axhline(100 * rep["acc"], color=OURS, ls=":", lw=1.2)
ax.axhline(25, color=BASE, lw=1, ls="-.", label="chance (4 options)")
ax.set_xticks(x, [t.replace(" Reasoning", "") for t in types], fontsize=8.5, rotation=30, ha="right")
ax.set_ylabel("accuracy (%)")
ax.set_ylim(0, 80)
ax.legend(fontsize=8, frameon=False, loc="upper right")
ax.set_title(f"ERQA reproduction on CPU — overall {100 * rep['acc']:.1f}% "
f"(95% CI {100 * rep['lo']:.1f}–{100 * rep['hi']:.1f}) vs reported {100 * rep['published']:.2f}%",
loc="left", fontsize=10, fontweight="bold")
ax = axs[1]
tab = sorted(sw["table"], key=lambda t: t["acc"])
y = np.arange(len(tab))
cols = [OURS if ("CGA" in t["system"] or "ours" in t["system"].lower() and "swarm" in t["system"]) else
(RACE if "RACE" in t["system"] else (BASE if "swarm" in t["system"] else "#6b7280")) for t in tab]
ax.barh(y, [100 * t["acc"] for t in tab], color=cols, height=0.65,
xerr=[[100 * (t["acc"] - t["lo"]) for t in tab], [100 * (t["hi"] - t["acc"]) for t in tab]],
error_kw=dict(lw=0.8, capsize=2, ecolor="#374151"))
ax.set_yticks(y, [t["system"].replace("swarm: ", "⊕ ") for t in tab], fontsize=7.3)
ax.set_xlabel("accuracy (%) with 95% CI")
ax.set_title(f"ERQA multi-agent swarm, no attack ({sw['n_questions']} shared questions)", loc="left", fontsize=10,
fontweight="bold")
fig.tight_layout()
fig.savefig(OUT / "erqa_results.png")
plt.close(fig)
# Pareto: clean accuracy vs worst attacked cell, receiver = the robot's local model (Cosmos)
rows = [r for r in load("ERQA") if r["receiver"] == "cosmos_r2_2b"]
by = defaultdict(list)
for r in rows:
by[r["method"]].append(r)
fig, ax = plt.subplots(figsize=(6.8, 4.6))
seen = defaultdict(int)
pts = {}
for m, rs in by.items():
clean = np.mean([r["acc"] for r in rs if r["attack"] == "none"])
worst = min(r["acc"] for r in rs)
pts[m] = (clean, worst)
c = OURS if "CGA" in m else (RACE if m.startswith("race") else BASE)
ax.scatter(100 * worst, 100 * clean, s=110, color=c, zorder=3, edgecolor="black" if "CGA" in m else None)
k = (round(100 * worst), round(100 * clean))
right_side = worst < 0.3 # points near the left edge get labels on their right
ax.annotate(m, (100 * worst, 100 * clean), textcoords="offset points",
xytext=(9 if right_side else -9, 6 - 13 * seen[k]), fontsize=8.5, ha="left" if right_side else "right")
seen[k] += 1
ax.set_xlabel("worst attacked cell accuracy (%) → robust")
ax.set_ylabel("clean accuracy (%) → useful")
ax.grid(alpha=0.25)
ws = [100 * v[1] for v in pts.values()]
ax.set_xlim(min(ws) - 3, max(ws) + 3)
rec, cg = pts.get("receiver_only"), pts.get("race CGA (new)")
ax.set_title("ERQA, receiver = Cosmos-Reason2-2B (the robot's own CPU model)\n"
f"CGA: clean {100 * cg[0]:.1f} vs receiver {100 * rec[0]:.1f}; worst cell {100 * cg[1]:.1f} vs "
f"{100 * rec[1]:.1f} — a compromise, not a free lunch", loc="left", fontsize=9.5, fontweight="bold")
fig.savefig(OUT / "erqa_pareto_cga.png")
plt.close(fig)
def planbench_figure():
lb = json.loads((R / "leaderboard.json").read_text())
pb = lb.get("PlanBench")
if not pb:
return
by = {t["system"]: t for t in pb["table"]}
agents = pb["agents"]
fig, ax = plt.subplots(figsize=(8.6, 0.55 * (len(agents) + 3) + 1.4))
y = 0
labels = []
for a in sorted(agents, key=lambda a: by[f"{a} · one-shot"]["acc"]):
o, m = by[f"{a} · one-shot"], by[f"{a} · LLM-Modulo (≤3 repairs)"]
ax.plot([100 * o["acc"], 100 * m["acc"]], [y, y], color=OURS, lw=2.5, alpha=0.55)
ax.scatter(100 * o["acc"], y, color=BASE, s=65, zorder=3)
ax.scatter(100 * m["acc"], y, color=OURS, s=65, zorder=3)
ax.text(101.5, y, f"{100 * o['acc']:.0f} → {100 * m['acc']:.0f} ({m['calls']:.2f} calls)", va="center", fontsize=8.5)
labels.append(a)
y += 1
y += 0.4
for name, t in by.items():
if name.startswith("swarm"):
ax.scatter(100 * t["acc"], y, marker="s", s=60, color=OURS if "Modulo" in name or "verify" in name else BASE)
ax.text(101.5, y, f"{100 * t['acc']:.0f} ({t['calls']:.2f} calls)", va="center", fontsize=8.5)
labels.append(name)
y += 1
ax.set_yticks(np.r_[np.arange(len(agents)), np.arange(len(labels) - len(agents)) + len(agents) + 0.4], labels, fontsize=8.5)
ax.set_xlim(min(40, 100 * min(t["acc"] for t in pb["table"])) - 5, 100.5)
ax.set_xlabel(f"plan success on {pb['n_instances']} PlanBench Blocksworld instances (%)")
ax.scatter([], [], color=BASE, label="one-shot (official PlanBench prompt)")
ax.scatter([], [], color=OURS, label="LLM-Modulo: exact validator feedback, ≤3 repairs")
ax.legend(fontsize=8, frameon=False, loc="upper left")
ax.grid(axis="x", alpha=0.25)
ax.set_title("PlanBench — the validator turns weak planners into strong ones", loc="left", fontweight="bold")
fig.savefig(OUT / "planbench.png")
plt.close(fig)
def cross_embodiment():
"""Replication plot: every method's mean accuracy on SO-101 (x) vs the Panda arm (y), frozen settings."""
if not (R / ROWS["AP"]).exists():
return
a, b = mean_by(load("A"), lambda r: r["method"]), mean_by(load("AP"), lambda r: r["method"])
ms = sorted(set(a) & set(b))
x, y = np.array([100 * a[m] for m in ms]), np.array([100 * b[m] for m in ms])
rx, ry = x.argsort().argsort(), y.argsort().argsort()
rho = float(np.corrcoef(rx, ry)[0, 1])
fig, ax = plt.subplots(figsize=(9.2, 5.6))
lo, hi = min(x.min(), y.min()) - 3, max(x.max(), y.max()) + 3
ax.plot([lo, hi], [lo, hi], color=BASE, ls="--", lw=1)
named = [k for k in np.argsort(-y) if color(ms[k]) != BASE or ms[k] in ("receiver_only", "majority", "max")]
for k in range(len(ms)):
ax.scatter(x[k], y[k], s=150 if k in named else 60, color=color(ms[k]), zorder=3, edgecolor="white", lw=0.8)
for n, k in enumerate(named, 1): # numbered markers + key: labels never overlap
ax.text(x[k], y[k], str(n), ha="center", va="center", fontsize=6.5, color="white", fontweight="bold", zorder=4)
ax.text(1.03, 0.97 - 0.062 * (n - 1), f"{n}", transform=ax.transAxes, fontsize=8, fontweight="bold", color=color(ms[k]), va="top")
ax.text(1.075, 0.97 - 0.062 * (n - 1), f"{ms[k].replace(' (new)', '').replace(' (new, learned)', ' (learned)')} {x[k]:.1f} → {y[k]:.1f}",
transform=ax.transAxes, fontsize=8, va="top")
ax.set_xlim(lo, hi)
ax.set_ylim(lo, hi)
ax.set_xlabel("mean accuracy on SO-101 (%)")
ax.set_ylabel("mean accuracy on Franka Panda (%)")
ax.grid(alpha=0.25)
ax.set_title(f"Cross-embodiment replication: {len(ms)} methods, frozen settings\nSpearman rank correlation ρ = {rho:.2f}",
loc="left", fontsize=10, fontweight="bold")
ax.set_aspect("equal")
fig.savefig(OUT / "cross_embodiment.png", bbox_inches="tight")
plt.close(fig)
def panda_gallery():
if not Path("data/panda/episodes.jsonl").exists():
print("skip panda_gallery.png: needs data/panda; keeping the committed figure")
return
from PIL import Image
eps = [json.loads(line) for line in open("data/panda/episodes.jsonl") if json.loads(line)["split"] == "eval"]
pick = [next(e for e in eps if e["mode"] == mode) for mode in ("success", "wrong_place", "drop_transit")]
cams = ("front", "left", "right", "back", "top")
fig, axs = plt.subplots(len(pick), 5, figsize=(11, 2.3 * len(pick)))
for i, e in enumerate(pick):
for j, c in enumerate(cams):
ax = axs[i, j]
ax.imshow(Image.open(f"data/panda/eval/{e['seed']}/{c}.png"))
ax.set_xticks([])
ax.set_yticks([])
for sp in ax.spines.values():
sp.set_visible(True)
sp.set_edgecolor(OURS if e["success"] else "#b91c1c")
sp.set_linewidth(2.5)
if i == 0:
ax.set_title(c, fontsize=10)
axs[i, 0].set_ylabel(f"{e['mode'].replace('_', ' ')}\n{'SUCCESS' if e['success'] else 'FAILURE'}", fontsize=9,
color=OURS if e["success"] else "#b91c1c", fontweight="bold")
fig.suptitle("Franka Panda rollouts (cross-embodiment replication): same tasks, cameras and physics labels", x=0.01, ha="left",
fontweight="bold", y=1.0)
fig.tight_layout()
fig.savefig(OUT / "panda_gallery.png")
plt.close(fig)
def racenet_figure():
logp = Path("models/racenet/training_log.json")
if not logp.exists():
return
log = json.loads(logp.read_text())
fig, axs = plt.subplots(1, 2, figsize=(14, 4.0), gridspec_kw={"width_ratios": [0.7, 2.2]})
ax = axs[0]
ax.plot([e["step"] for e in log], [100 * e["val_acc_synthetic"] for e in log], color=OURS, lw=2, marker="o", ms=3)
ax.set_xlabel("training step (synthetic swarms only)")
ax.set_ylabel("held-out synthetic accuracy (%)")
ax.grid(alpha=0.25)
ax.set_title("RACE-Net-V training (CPU)", loc="left", fontsize=10, fontweight="bold")
ax = axs[1]
sets = [(k, lab) for k, lab in (("A0", "A0 procedural\n(development)"), ("A", "SO-101\n(test)"), ("AP", "Franka Panda\n(test)"),
("AH_so101", "SO-101 hold-out\n(after freeze)"), ("AH_panda", "Panda hold-out\n(after freeze)"))
if (R / ROWS[k]).exists()]
meths = ["majority", "DS (crowd-kit)", "receiver_only", "race_online (new)", "race_s_online (new)", "race_net (new, learned)",
"race_pool (new)", "REF stack_lr (labelled)"]
cols = {"majority": BASE, "DS (crowd-kit)": "#6b7280", "receiver_only": "#d1d5db", "race_online (new)": "#5eb8ad",
"race_s_online (new)": OURS, "race_net (new, learned)": "#7c3aed", "race_pool (new)": "#c026d3", "REF stack_lr (labelled)": REF}
wbar = 0.8 / len(meths)
for k, m in enumerate(meths):
vals = []
for key, _ in sets:
mb = mean_by(load(key), lambda r: r["method"])
vals.append(100 * mb.get(m, np.nan))
xs = np.arange(len(sets)) + (k - len(meths) / 2 + 0.5) * wbar
ax.bar(xs, vals, wbar * 0.92, color=cols[m], label={"race_net (new, learned)": "RACE-Net-V (ours, learned)", "race_pool (new)": "RACE-Pool (ours)"}.get(
m, m.replace(" (new)", "")))
for xi, v in zip(xs, vals):
if v == v:
ax.text(xi, v + 0.6, f"{v:.0f}", ha="center", fontsize=6.5)
ax.set_xticks(np.arange(len(sets)), [lab for _, lab in sets])
ax.set_ylim(40, 100)
ax.set_ylabel("mean accuracy over all attack cells (%)")
ax.legend(fontsize=7, frameon=False, ncol=4, loc="upper center", bbox_to_anchor=(0.5, -0.2))
ax.set_title("Zero-shot transfer of RACE-Net-V to real VLM camera swarms", loc="left", fontsize=10, fontweight="bold")
fig.savefig(OUT / "racenet.png")
plt.close(fig)
def racenet_scaling():
p = R / "racenet/analysis.json"
if not p.exists():
return
d = json.loads(p.read_text())
style = {"majority": (BASE, "-", "majority"), "dawid_skene": ("#6b7280", "-", "Dawid–Skene"), "receiver_only": ("#9ca3af", ":", "receiver alone"),
"race_online": ("#5eb8ad", "-", "RACE online (EM)"), "race_s_online": (OURS, "-", "RACE-S online (EM)"),
"race_net_v1": ("#a78bfa", (0, (1, 1.5)), "RACE-Net-V, first release"), "race_net": ("#7c3aed", "-", "RACE-Net-V (released)"),
"race_pool": ("#c026d3", (0, (4, 1.5)), "RACE-Pool")}
panels = [("liar_fraction_J5", "liar fraction · 5 agents", "fraction of agents that lie", False),
("liar_fraction_J16", "liar fraction · 16 agents", "fraction of agents that lie", False),
("window", "window length · 3 of 5 lie", "unlabelled episodes in the window", True),
("swarm_size", "swarm size · 60% lie", "agents in the swarm", False),
("receiver_skill_clean", "weak receiver · no liars", "receiver's own accuracy", False),
("receiver_skill_2liars", "weak receiver · 2 of 5 lie", "receiver's own accuracy", False)]
fig, axs = plt.subplots(2, 3, figsize=(13.5, 7.2), sharey=True)
for ax, (key, title, xl, logx) in zip(axs.ravel(), panels):
rows = d[key]
xs = [r["x"] for r in rows]
for m, (c, ls, lab) in style.items():
if m not in rows[0]["acc"]:
continue
ys = np.array([100 * r["acc"][m] for r in rows])
se = np.array([100 * r["se"][m] for r in rows])
ax.plot(xs, ys, color=c, ls=ls, lw=2.4 if m in ("race_net", "race_pool") else 1.6, marker="o", ms=3.5, label=lab,
zorder=3 if m in ("race_net", "race_pool") else 2)
ax.fill_between(xs, ys - se, ys + se, color=c, alpha=0.12, lw=0)
if logx:
ax.set_xscale("log", base=2)
ax.set_xticks(xs, [str(x) for x in xs])
if key == "swarm_size":
ax.axvspan(11.5, max(xs) + 0.5, color="#f3f4f6", zorder=0)
ax.text(max(xs) + 0.2, 22, "larger than any\ntraining swarm", ha="right", fontsize=7.5, color="#6b7280")
ax.set_title(title, loc="left", fontsize=10, fontweight="bold")
ax.set_xlabel(xl, fontsize=9)
ax.grid(alpha=0.25)
for ax in axs[:, 0]:
ax.set_ylabel("accuracy (%)")
axs[0, 0].set_ylim(15, 100)
h, l = axs[0, 0].get_legend_handles_labels()
fig.legend(h, l, loc="lower center", ncol=4, frameon=False, fontsize=9, bbox_to_anchor=(0.5, -0.07), handlelength=2.8)
fig.suptitle(f"RACE-Net-V scaling study on an independent synthetic generator ({d['seeds']} seeds; attacks: {', '.join(d['attacks'])}; band = ±1 s.e.)",
x=0.01, ha="left", fontsize=11, fontweight="bold")
fig.tight_layout(rect=(0, 0.02, 1, 0.97))
fig.savefig(OUT / "racenet_scaling.png")
plt.close(fig)
def racenet_m_scaling():
p = R / "racenet_m/scaling.json"
if not p.exists():
return
d = json.loads(p.read_text())
meths = [("solo", "no communication", "#d1d5db"), ("majority", "majority", BASE), ("wmsr_trim", "W-MSR trimming", "#6b7280"),
("reputation", "beta-reputation", "#475569"), ("race_map", "race_map (hand-written)", "#5eb8ad"),
("race_net_m + reach-repair", "RACE-Net-M + repair (learned)", OURS), ("REF oracle", "oracle (knows the liars)", REF)]
cfgs = d["configs"]
fig, ax = plt.subplots(figsize=(12, 3.9))
w = 0.8 / len(meths)
for k, (m, lab, c) in enumerate(meths):
xs = np.arange(len(cfgs)) + (k - len(meths) / 2 + 0.5) * w
vals = [100 * c_["spl"][m] for c_ in cfgs]
ax.bar(xs, vals, w * 0.92, color=c, label=lab, yerr=[100 * c_["se"][m] for c_ in cfgs], error_kw={"lw": 0.8, "ecolor": "#374151"})
for xi, v, c_ in zip(xs, vals, cfgs):
ax.text(xi, v + 100 * c_["se"][m] + 1.2, f"{v:.0f}", ha="center", fontsize=6.8)
ax.set_xticks(np.arange(len(cfgs)), [f"{c_['label']}\n{c_['liars']} liars" for c_ in cfgs], fontsize=9)
ax.set_ylim(0, 100)
ax.set_ylabel("SPL of honest robots (×100)")
ax.legend(fontsize=8, frameon=False, ncol=7, loc="upper center", bbox_to_anchor=(0.5, -0.2))
ax.grid(axis="y", alpha=0.25)
ax.set_title(f"RACE-Net-M on swarm and map sizes it was never trained on (half of the robots lie; {d['mazes']} mazes × {len(d['attacks'])} attacks; bars = ±1 s.e.)",
loc="left", fontsize=10, fontweight="bold")
fig.savefig(OUT / "racenet_m_scaling.png")
plt.close(fig)
def published_context():
lb = json.loads((R / "leaderboard.json").read_text())
pub = lb.get("published")
if not pub:
return
fig, axs = plt.subplots(1, 2, figsize=(13.5, 5.4))
# ---- ERQA
ax = axs[0]
items = [(f"{k} †", v, BASE) for k, v in pub["ERQA"]["no_cot"].items()]
items += [(f"{k} ‡", v, "#d1d5db") for k, v in pub["ERQA"]["model_card"].items()]
rep, rep768 = lb.get("ERQA_reproduction"), lb.get("ERQA_reproduction_768")
if rep:
items.append((f"Cosmos-Reason2-2B · ours, CPU ≤448² (n={rep['n']})", 100 * rep["acc"], OURS))
if rep768:
items.append((f"Cosmos-Reason2-2B · ours, CPU ≤768² (n={rep768['n']})", 100 * rep768["acc"], OURS))
for a_ in lb.get("ERQA_agents", []):
items.append((f"{a_['agent']} · measured here (n={a_['n']})", 100 * a_["acc"], "#5eb8ad"))
items.sort(key=lambda t: t[1])
y = np.arange(len(items))
ax.barh(y, [t[1] for t in items], color=[t[2] for t in items], height=0.7)
for yi, t in zip(y, items):
ax.text(t[1] + 0.5, yi, f"{t[1]:.1f}", va="center", fontsize=7.5)
ax.set_yticks(y, [t[0] for t in items], fontsize=7.5)
ax.axvline(25, color="#9ca3af", ls=":", lw=1)
ax.set_xlabel("ERQA accuracy (%)\n† Gemini Robotics paper (Feb 2025) · ‡ NVIDIA model card · dotted line = chance", fontsize=8.5)
ax.set_title("ERQA in context", loc="left", fontweight="bold")
# ---- PlanBench
ax = axs[1]
items = [(f"{k} · one-shot †", v, BASE) for k, v in pub["PlanBench_Blocksworld"]["one_shot"].items()]
items += [(f"{k} · zero-shot †", pub["PlanBench_Blocksworld"]["zero_shot"][k], "#d1d5db") for k in ("o1-preview", "o1-mini", "LLaMA 3.1 405B")]
items.append(("GPT-4 + VAL back-prompting, ≤15 rounds (LLM-Modulo) §", pub["PlanBench_Blocksworld"]["llm_modulo"]["value"], "#d1d5db"))
for a_ in lb.get("PlanBench_agents", []):
items.append((f"{a_['agent']} · one-shot, here (n={a_['n']})", 100 * a_["oneshot"], "#5eb8ad"))
items.append((f"{a_['agent']} · LLM-Modulo ≤3, here (n={a_['n']})", 100 * a_["modulo"], OURS))
items.sort(key=lambda t: t[1])
y = np.arange(len(items))
ax.barh(y, [t[1] for t in items], color=[t[2] for t in items], height=0.7)
for yi, t in zip(y, items):
ax.text(t[1] + 0.5, yi, f"{t[1]:.1f}", va="center", fontsize=7.5)
ax.set_yticks(y, [t[0] for t in items], fontsize=7.5)
ax.set_xlim(0, 108)
ax.set_xlabel("Blocksworld plan-generation success (%)\n† arXiv:2409.13373 (600 instances) · § arXiv:2402.01817", fontsize=8.5)
ax.set_title("PlanBench Blocksworld in context", loc="left", fontweight="bold")
fig.suptitle("Published numbers (grey) next to our measurements (teal). Context only: models, dates and instance subsets differ.",
x=0.01, ha="left", fontsize=10)
fig.tight_layout()
fig.savefig(OUT / "published_context.png")
plt.close(fig)
def maze_llm_figure():
lb = json.loads((R / "leaderboard.json").read_text())
mz = lb.get("maze_llm")
if not mz:
return
mz = sorted(mz, key=lambda r: r["oneshot"])
fig, ax = plt.subplots(figsize=(8, 0.6 * len(mz) + 1.6))
for y, r in enumerate(mz):
ax.plot([100 * r["oneshot"], 100 * r["modulo"]], [y, y], color=OURS, lw=2.5, alpha=0.55)
ax.scatter(100 * r["oneshot"], y, color=BASE, s=65, zorder=3)
ax.scatter(100 * r["modulo"], y, color=OURS, s=65, zorder=3)
ax.text(102, y, f"{100 * r['oneshot']:.0f} → {100 * r['modulo']:.0f} ({r['calls']:.2f} calls, n={r['n']})", va="center", fontsize=8.5)
ax.set_yticks(range(len(mz)), [r["agent"] for r in mz], fontsize=9)
ax.set_xlim(0, 101)
ax.set_xlabel("text mazes solved (%)")
ax.scatter([], [], color=BASE, label="one-shot")
ax.scatter([], [], color=OURS, label="LLM-Modulo: exact validator feedback, ≤3 repairs")
ax.legend(fontsize=8, frameon=False, loc="upper left", bbox_to_anchor=(0, -0.25), ncol=2)
ax.grid(axis="x", alpha=0.25)
ax.set_title("LLM agents on procedural text mazes (4×4 and 6×6 cells)", loc="left", fontweight="bold")
fig.savefig(OUT / "maze_llm.png")
plt.close(fig)
if __name__ == "__main__":
overview()
leaderboard_bars("A", "Track A — SO-101 multi-camera success verification", "trackA_leaderboard.png",
"5 Cosmos-Reason2 camera agents · physics ground truth · 7 attacks · every camera as receiver")
leaderboard_bars("B", "Track B — Byzantine-resilient rendezvous (12 robots)", "trackB_leaderboard.png",
"mission success · 6 attacks × F = 1…5 Byzantine robots · 40 missions per cell")
leaderboard_bars("C", "Track C — LLM planner swarm with real LLM deceivers", "trackC_leaderboard.png",
"4 engineered LLM agents · real saboteur answers · every agent as receiver")
curves_vs_liars("A", "trackA_vs_liars.png", "Track A (SO-101): accuracy as liars take over the camera swarm",
["race_s_online (new)", "race_net (new, learned)", "race CGA (new)", "race", "receiver_only", "majority", "DS (crowd-kit)", "mean"],
["invert", "collude", "sleeper", "noise"], ylabel="accuracy (%)")
curves_vs_liars("B", "trackB_vs_liars.png", "Track B: mission success vs number of Byzantine robots (of 12)",
["race_c+wmsr", "wmsr", "geomedian", "median", "mean"], ["collude", "two_faced", "sleeper", "bias"],
xlabel="Byzantine robots")
heatmap("A", "trackA_heatmap.png", "Track A — mean accuracy (%) by attack")
heatmap("B", "trackB_heatmap.png", "Track B — mission success (%) by attack")
camera_quality()
verifier_calibration()
race_weights()
trackC_systems()
so101_gallery()
erqa_figures()
planbench_figure()
if (R / ROWS["D"]).exists():
leaderboard_bars("D", "Track D — Byzantine cooperative maze exploration", "trackD_leaderboard.png",
"SPL of honest robots · 6 mobile robots · 6 attacks × F = 1…4 liars · 20 mazes")
curves_vs_liars("D", "trackD_vs_liars.png", "Track D: SPL as liars take over the maze swarm (6 robots)",
["race_net_m + reach-repair", "race_map", "wmsr_trim", "reputation", "eigentrust", "solo", "majority"],
["invert", "false_walls", "sleeper", "collude"], xlabel="lying robots", ylabel="SPL of honest robots (×100)")
heatmap("D", "trackD_heatmap.png", "Track D — mean SPL (×100) by attack")
if (R / ROWS["AP"]).exists():
leaderboard_bars("AP", "Track A-Panda — cross-embodiment replication", "trackAP_leaderboard.png",
"Franka Panda · same cameras, tasks and frozen methods as SO-101")
cross_embodiment()
panda_gallery()
racenet_figure()
racenet_scaling()
racenet_m_scaling()
published_context()
maze_llm_figure()
print(sorted(p.name for p in OUT.iterdir()))