RoboRACE-Bench / scripts /select_racenet.py
Nabidnur's picture
sync scripts: RACE-Net-M, Track D baselines, RACE-Net-V v3
b2ead12 verified
Raw History Blame Contribute Delete
5.78 kB
#!/usr/bin/env python3
"""Choose the released RACE-Net-V checkpoint. Selection uses development data only.
python scripts/select_racenet.py name=dir [name=dir ...]
Development cells (rule fixed before the v3 candidates existed):
A0 evaluation window of the procedural track
SO-101 HISTORY split of the SO-101 track (110 episodes)
Panda HISTORY split of the Franka Panda track (110 episodes)
The history splits are the unlabelled calibration data of the benchmark; no label-free method ever used their
labels, so they can serve as development data for the arms. The evaluation splits stay untouched as test sets.
Rule: highest mean accuracy of `race_net` over the three development sets (each set weighted equally); ties within
0.1 point go to the higher held-out synthetic accuracy. The winner is copied to models/racenet. Test numbers of
every candidate are computed AFTER the choice and stored for transparency (models/racenet/selection.json).
"""
import json
import shutil
import sys
from pathlib import Path
import numpy as np
import torch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from robotics.bench import trackA # noqa: E402
from robotics.swarm import racenet # noqa: E402
NET, POOL = "race_net (new, learned)", "race_pool (new)"
REFS = ("race_s_online (new)", "race_online (new)", "majority", "receiver_only")
DEV = (("A0", "trackA", "eval"), ("SO-101 history", "so101", "hist"), ("Panda history", "panda", "hist"))
TEST = (("SO-101", "so101", "eval"), ("Panda", "panda", "eval"))
OUT = Path("models/racenet")
def synthetic(net, gen, n_batches=40, seed=20_000):
rng, acc = np.random.default_rng(seed), []
with torch.inference_mode():
for _ in range(n_batches):
z, adv, y = racenet.batch_tensors(rng, 16, gen, getattr(net, "advisor_names", ()))
acc.append(float(((net(z, adv) > 0) == (y > 0.5)).float().mean()))
return float(np.mean(acc))
def cells(name, split, methods):
hist, ev = trackA.load_scores(f"results/{name}/vlm_scores.jsonl")
win = ev if split == "eval" else hist # online methods judge the window they are fitted on
rows = trackA.run(win, win, max_subsets=3, receivers=range(len(trackA.CAMS)), only=set(methods))
out = {}
for m in methods:
a = np.array([r["acc"] for r in rows if r["method"] == m])
f = np.array([r["f"] for r in rows if r["method"] == m])
out[m] = {"mean": float(a.mean()), "clean": float(a[f == 0].mean()), "liar_majority": float(a[f >= 0.5].mean()), "worst": float(a.min())}
return out
def main():
cands = dict(a.split("=", 1) for a in sys.argv[1:] if "=" in a)
refs = {label: cells(name, split, REFS) for label, name, split in DEV}
print("reference methods on the development sets:")
for m in REFS:
print(f" {m:24s}", " | ".join(f"{label} {100 * refs[label][m]['mean']:.1f}" for label, _, _ in DEV),
f"| mean {100 * np.mean([refs[label][m]['mean'] for label, _, _ in DEV]):.2f}")
table = []
for name, d in cands.items():
racenet.DEFAULT_DIR = Path(d)
cfg = json.loads((Path(d) / "config.json").read_text())
net = racenet.load(d)
dev = {label: cells(nm, split, (NET, POOL)) for label, nm, split in DEV}
row = {"name": name, "generator": cfg["training"].get("generator", "v1"), "steps": cfg["training"]["steps"],
"params": cfg["n_params"], "advisors": cfg.get("advisors", []),
"synthetic_v1": synthetic(net, "v1"), "synthetic_v3": synthetic(net, "v3"),
"dev": {label: dev[label][NET] for label in dev}, "dev_pool": {label: dev[label][POOL] for label in dev}}
row["dev_mean"] = float(np.mean([v["mean"] for v in row["dev"].values()]))
row["dev_pool_mean"] = float(np.mean([v["mean"] for v in row["dev_pool"].values()]))
table.append(row)
print(f"{name:28s} net: " + " | ".join(f"{k} {100 * v['mean']:.1f}" for k, v in row["dev"].items())
+ f" | mean {100 * row['dev_mean']:.2f} pool mean {100 * row['dev_pool_mean']:.2f} syn v3 {100 * row['synthetic_v3']:.1f}", flush=True)
best = max(table, key=lambda r: (round(100 * r["dev_mean"], 1), r["synthetic_v3"]))
print("selected:", best["name"])
if "--dev-only" in sys.argv:
return
for r in table: # after the choice: test tracks, for transparency only
racenet.DEFAULT_DIR = Path(cands[r["name"]])
r["selected"] = r["name"] == best["name"]
t = {label: cells(nm, split, (NET, POOL)) for label, nm, split in TEST}
r["test"], r["test_pool"] = {k: v[NET] for k, v in t.items()}, {k: v[POOL] for k, v in t.items()}
src = Path(cands[best["name"]])
OUT.mkdir(parents=True, exist_ok=True)
if src.resolve() != OUT.resolve():
for f in ("model.safetensors", "config.json", "training_log.json"):
shutil.copy(src / f, OUT / f)
(OUT / "selection.json").write_text(json.dumps({
"rule": "highest mean accuracy of RACE-Net-V over three development sets (A0 evaluation window, SO-101 history split, "
"Panda history split; equal weight); ties within 0.1 point go to the higher synthetic accuracy",
"selected": best["name"], "references_dev": refs, "candidates": table}, indent=1))
racenet.DEFAULT_DIR = OUT
for r in table:
print(f"{r['name']:28s} dev {100 * r['dev_mean']:.2f} | test SO-101 {100 * r['test']['SO-101']['mean']:.1f} Panda {100 * r['test']['Panda']['mean']:.1f}"
f" | pool: SO-101 {100 * r['test_pool']['SO-101']['mean']:.1f} Panda {100 * r['test_pool']['Panda']['mean']:.1f}{' <- released' if r['selected'] else ''}")
if __name__ == "__main__":
main()