File size: 11,889 Bytes
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
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
#!/usr/bin/env python3
"""Build the interactive static Space "RoboRACE-Playground".

Everything is precomputed from the cached Cosmos-Reason2 scores: for each robot, attack and set of lying
cameras, the page gets the corrupted reports and every fusion method's verdict per episode. The browser only
looks things up, so what the visitor sees is exactly what the benchmark code computes.

  python scripts/make_playground.py OUT_DIR   -> OUT_DIR/index.html, data.json, README.md
"""
import itertools
import json
import sys
from pathlib import Path

import numpy as np

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from robotics.bench import trackA  # noqa: E402
from robotics.swarm import attacks, fusion, racenet  # noqa: E402

DS = "Nabidnur/RoboRACE-Bench"
RES = f"https://huggingface.co/datasets/{DS}/resolve/main"
ATTACKS = ("invert", "collude", "noise", "stuck")
CAMS = ("front", "left", "right", "back", "top")


def methods():
    m = {"receiver alone": lambda P: fusion.single(P, P, 0),
         "majority vote": lambda P: fusion.majority(P, P),
         "Dawid–Skene": lambda P: fusion.dawid_skene(P, P),
         "RACE-S (ours)": lambda P: fusion.race_s(P, P, 0)[:2]}
    if racenet.available():
        m["RACE-Net (ours, learned)"] = lambda P: racenet.race_net(P, P, 0)
    return m


def compute():
    out = {"cams": CAMS, "attacks": ATTACKS, "robots": {}}
    M = methods()
    out["methods"] = list(M)
    for robot, label in (("so101", "SO-101"), ("panda", "Franka Panda")):
        sp, ep = ROOT / f"results/{robot}/vlm_scores.jsonl", ROOT / f"data/{robot}/episodes.jsonl"
        if not sp.exists() or not ep.exists():
            continue
        (_, _, _), (Pe, ye, _) = trackA.load_scores(sp)
        eps = sorted((e for e in map(json.loads, open(ep)) if e["split"] == "eval"), key=lambda e: e["seed"])
        cells = {}
        for atk in ATTACKS:
            for m in range(0, 5):
                for liars in itertools.combinations(range(1, 5), m):
                    P = attacks.apply(Pe, list(liars), atk, "eval", np.random.default_rng(0)) if liars else Pe
                    dec, acc = {}, {}
                    for name, fn in M.items():
                        s, thr = fn(P)
                        d = np.asarray(s) > thr
                        dec[name] = "".join("1" if x else "0" for x in d)
                        acc[name] = round(float(np.mean(d == ye)), 4)
                    cells[f"{atk}|{''.join(map(str, liars))}"] = {"p": np.round(P, 2).ravel().tolist(), "dec": dec, "acc": acc}
        out["robots"][robot] = {"label": label, "episodes": [{"seed": e["seed"], "task": e["task"], "mode": e["mode"], "gt": int(e["success"])}
                                                             for e in eps], "cells": cells}
    return out


PAGE = r"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>RoboRACE Playground</title>
<style>
:root{--bg:#fafaf9;--fg:#1f2937;--mut:#6b7280;--card:#fff;--line:#e5e7eb;--teal:#0f766e;--tealbg:#e6f4f1;--red:#dc2626;--redbg:#fee2e2;--amber:#b45309}
@media (prefers-color-scheme:dark){:root{--bg:#0f1115;--fg:#e5e7eb;--mut:#9ca3af;--card:#171a21;--line:#2a2f3a;--teal:#2dd4bf;--tealbg:#11312d;--red:#f87171;--redbg:#3b1717;--amber:#fbbf24}}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
main{max-width:1100px;margin:0 auto;padding:22px 14px 60px}h1{margin:0 0 4px;font-size:1.9rem;letter-spacing:-.02em}
.lead{color:var(--mut);margin:0 0 16px;max-width:60em}a{color:var(--teal)}
.panel{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:14px;margin:12px 0}
.row{display:flex;flex-wrap:wrap;gap:8px;align-items:center}.lab{color:var(--mut);font-size:.85rem;min-width:92px}
button,.chip{font:inherit;border:1px solid var(--line);background:var(--card);color:var(--fg);padding:6px 12px;border-radius:999px;cursor:pointer}
button.on{background:var(--teal);border-color:var(--teal);color:#fff}button.liar.on{background:var(--red);border-color:var(--red)}
.bars{display:grid;gap:7px;margin-top:6px}.bar{display:grid;grid-template-columns:190px 1fr 54px;gap:8px;align-items:center;font-size:.9rem}
.track{height:18px;background:var(--line);border-radius:9px;overflow:hidden;position:relative}.fill{display:block;height:100%;background:var(--mut);border-radius:9px;transition:width .25s}
.fill.ours{background:var(--teal)}.half{position:absolute;left:50%;top:0;bottom:0;width:1px;background:var(--fg);opacity:.35}
.cams{display:grid;grid-template-columns:repeat(5,1fr);gap:8px}@media (max-width:760px){.cams{grid-template-columns:repeat(2,1fr)}.bar{grid-template-columns:130px 1fr 48px}}
.cam{border:3px solid var(--line);border-radius:10px;overflow:hidden;background:var(--card)}.cam.recv{border-color:var(--teal)}.cam.liar{border-color:var(--red)}
.cam img{width:100%;display:block;aspect-ratio:1;background:#ddd}.cam .cap{padding:5px 7px;font-size:.8rem}.cam .p{height:8px;background:var(--line);border-radius:4px;overflow:hidden;margin-top:3px}
.cam .p i{display:block;height:100%;background:var(--teal)}.cam.liar .p i{background:var(--red)}
.verd{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}.v{padding:6px 10px;border-radius:10px;border:1px solid var(--line);font-size:.88rem}
.v.ok{background:var(--tealbg);border-color:var(--teal)}.v.bad{background:var(--redbg);border-color:var(--red)}.gt{font-weight:700}
small{color:var(--mut)}
</style></head><body><main>
<h1>RoboRACE Playground</h1>
<p class="lead">Five cameras watch a robot arm; a vision-language model (Cosmos-Reason2-2B, run on a CPU) scores each view for
“did the task succeed?”. <b>Choose which cameras lie</b> and see what each fusion rule concludes on 110 real cached episodes.
The front camera is the receiver: the robot's own camera, which it trusts. All numbers are precomputed by the benchmark code in the
<a href="https://huggingface.co/datasets/Nabidnur/RoboRACE-Bench">RoboRACE dataset</a>; nothing is simulated in your browser.</p>
<div class="panel">
 <div class="row"><span class="lab">Robot</span><span id="robots"></span></div>
 <div class="row" style="margin-top:8px"><span class="lab">Attack</span><span id="attacks"></span></div>
 <div class="row" style="margin-top:8px"><span class="lab">Lying cameras</span><span id="liars"></span><small id="frac"></small></div>
 <p id="atkdesc" style="margin:10px 0 0"><small></small></p>
</div>
<div class="panel"><b>Accuracy over all 110 evaluation episodes</b> <small>(thin line = 50%, coin flip)</small><div class="bars" id="bars"></div></div>
<div class="panel">
 <div class="row"><b id="eptitle"></b><span style="flex:1"></span>
  <button id="prev">◀ prev</button><button id="next">next ▶</button><button id="rand">random</button><button id="fooled">majority fooled ▶</button></div>
 <p id="task" style="margin:8px 0"></p>
 <div class="cams" id="cams"></div>
 <div class="verd" id="verd"></div>
</div>
<p><small>Attacks: <b>invert</b> – liars report 1 − p (a consistent liar still carries information); <b>collude</b> – all liars send one identical inverted report;
<b>noise</b> – random reports; <b>stuck</b> – always “success”. Methods are label-free: none sees the ground truth. Each camera's vote uses its own threshold (a quantile of its unlabelled history), so a low raw score can still count as a “yes” vote.
Full study, code and videos: <a href="https://huggingface.co/spaces/Nabidnur/RoboRACE">showcase</a> ·
<a href="https://huggingface.co/Nabidnur/RoboRACE-Net">RACE-Net model</a>.</small></p>
</main>
<script>
const RES="__RES__";const DESC={invert:"Inverted cameras report 1 − p. Majority vote is fooled once they are the majority; anchored methods flip them back.",
collude:"All liars send the same inverted report, like one voice copied several times.",noise:"Liars report random numbers: no information, pure dilution.",
stuck:"Liars always report “success”, like a stuck sensor or a lazy verifier."};
let D,S={robot:null,attack:"invert",liars:new Set([1,2,3]),ep:0};
const $=id=>document.getElementById(id);
function key(){return S.attack+"|"+[...S.liars].sort().join("")}
function btn(txt,on,cls,fn){const b=document.createElement("button");b.textContent=txt;b.className=(cls||"")+(on?" on":"");b.onclick=fn;return b}
function render(){
 const R=D.robots[S.robot],C=R.cells[key()],E=R.episodes;
 $("robots").replaceChildren(...Object.entries(D.robots).map(([k,v])=>btn(v.label,k===S.robot,"",()=>{S.robot=k;S.ep=0;render()})));
 $("attacks").replaceChildren(...D.attacks.map(a=>btn(a,a===S.attack,"",()=>{S.attack=a;render()})));
 $("liars").replaceChildren(...[1,2,3,4].map(j=>btn(D.cams[j],S.liars.has(j),"liar",()=>{S.liars.has(j)?S.liars.delete(j):S.liars.add(j);render()})));
 $("frac").textContent=" "+S.liars.size+" of 5 cameras lie"+(S.liars.size>=3?" — a liar majority":"");
 $("atkdesc").firstChild.textContent=DESC[S.attack];
 const order=[...D.methods].sort((a,b)=>C.acc[b]-C.acc[a]);
 $("bars").replaceChildren(...order.map(m=>{const d=document.createElement("div");d.className="bar";const ours=m.includes("ours");
  d.innerHTML=`<span>${m}</span><span class="track"><span class="fill ${ours?"ours":""}" style="width:${100*C.acc[m]}%"></span><span class="half"></span></span><b>${(100*C.acc[m]).toFixed(1)}%</b>`;return d}));
 const e=E[S.ep];$("eptitle").textContent=`Episode ${S.ep+1} / ${E.length}`;
 $("task").innerHTML=`Task: <b>“${e.task}”</b> · ground truth (physics): <span class="gt" style="color:${e.gt?"var(--teal)":"var(--red)"}">${e.gt?"SUCCESS":"FAILURE"}</span>`+(e.mode!=="success"?` <small>(${e.mode.replace("_"," ")})</small>`:"");
 $("cams").replaceChildren(...D.cams.map((c,j)=>{const p=C.p[S.ep*5+j],d=document.createElement("div");d.className="cam"+(j===0?" recv":"")+(S.liars.has(j)?" liar":"");
  d.innerHTML=`<img loading="lazy" alt="${c} camera" src="${RES}/data/${S.robot}/eval/${e.seed}/${c}.png"><div class="cap"><b>${c}</b>${j===0?" · receiver":S.liars.has(j)?" · LIAR":""}<br>reports P(success) = ${p.toFixed(2)}<div class="p"><i style="width:${100*p}%"></i></div></div>`;return d}));
 $("verd").replaceChildren(...D.methods.map(m=>{const v=C.dec[m][S.ep]==="1",ok=(v?1:0)===e.gt,d=document.createElement("div");d.className="v "+(ok?"ok":"bad");
  d.innerHTML=`${m}: <b>${v?"SUCCESS":"FAILURE"}</b> ${ok?"✓":"✗"}`;return d}));
}
function step(k){const n=D.robots[S.robot].episodes.length;S.ep=(S.ep+k+n)%n;render()}
$("prev").onclick=()=>step(-1);$("next").onclick=()=>step(1);
$("rand").onclick=()=>{S.ep=Math.floor(Math.random()*D.robots[S.robot].episodes.length);render()};
$("fooled").onclick=()=>{const R=D.robots[S.robot],C=R.cells[key()],n=R.episodes.length;for(let k=1;k<=n;k++){const i=(S.ep+k)%n;if((C.dec["majority vote"][i]==="1"?1:0)!==R.episodes[i].gt){S.ep=i;break}}render()};
fetch("data.json").then(r=>r.json()).then(d=>{D=d;S.robot=Object.keys(D.robots)[0];render()});
</script></body></html>
"""


def build(out):
    out = Path(out)
    out.mkdir(parents=True, exist_ok=True)
    data = compute()
    (out / "data.json").write_text(json.dumps(data, separators=(",", ":")))
    (out / "index.html").write_text(PAGE.replace("__RES__", RES))
    (out / "README.md").write_text("""---
title: RoboRACE Playground
emoji: 🕵️
colorFrom: red
colorTo: green
sdk: static
pinned: false
short_description: Pick which robot cameras lie; watch each fusion rule
---

Interactive companion to RoboRACE. Data and code: https://huggingface.co/datasets/""" + DS + "\n")
    print("playground cells:", {k: len(v["cells"]) for k, v in data["robots"].items()}, "bytes", (out / "data.json").stat().st_size)
    return out


if __name__ == "__main__":
    build(sys.argv[1] if len(sys.argv) > 1 else ROOT / ".hf_stage_play")