File size: 5,779 Bytes
caa90b0
b2ead12
caa90b0
 
b2ead12
 
 
 
 
 
 
 
 
caa90b0
 
 
 
 
 
 
 
 
 
 
 
 
b2ead12
 
 
 
caa90b0
 
 
 
 
 
 
b2ead12
 
caa90b0
 
 
b2ead12
caa90b0
b2ead12
 
 
 
 
 
 
 
caa90b0
 
 
b2ead12
 
 
 
 
 
caa90b0
 
b2ead12
caa90b0
 
b2ead12
 
 
 
 
 
 
 
 
 
 
caa90b0
b2ead12
 
caa90b0
b2ead12
caa90b0
b2ead12
 
caa90b0
 
 
 
 
b2ead12
 
 
 
caa90b0
 
b2ead12
 
caa90b0
 
 
 
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
#!/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()