#!/usr/bin/env python3
"""README videos, 1280x720 @ 30 fps H.264 (+ GIF previews). All content comes from cached results.
robot_rollouts SO-101 arm (MuJoCo Menagerie) pick-and-place, 5 cameras, then the camera swarm's
verdict: clean, and with 3 of 5 cameras inverted (liar majority)
swarm_rendezvous 12 robots, 4 colluding Byzantine robots: mean vs W-MSR vs RACE-C+W-MSR + live error plot
planbench_modulo a real cached LLM plan for a PlanBench instance: validator catches the failing step,
the repaired plan (LLM-Modulo) reaches the goal
"""
import json
import os
import subprocess
import sys
from pathlib import Path
os.environ.setdefault("MUJOCO_GL", "egl")
import matplotlib # noqa: E402
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
from PIL import Image, ImageDraw, ImageFont # noqa: E402
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from robotics.bench import trackA, trackB # noqa: E402
from robotics.benchmarks import blocksworld as bw # noqa: E402
from robotics.swarm import attacks, fusion # noqa: E402
OUT = Path("media/videos")
OUT.mkdir(parents=True, exist_ok=True)
W, H, FPS = 1280, 720, 30
TEAL, RED, INK, GREY, AMBER, BG = (15, 118, 110), (220, 38, 38), (31, 41, 55), (156, 163, 175), (217, 119, 6), (250, 250, 249)
FONT_DIR = Path(matplotlib.get_data_path()) / "fonts/ttf"
def font(size, bold=False):
return ImageFont.truetype(str(FONT_DIR / ("DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf")), size)
class Writer:
def __init__(self, path):
self.path = path
self.p = subprocess.Popen(["ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
"-s", f"{W}x{H}", "-r", str(FPS), "-i", "-", "-c:v", "libx264", "-preset", "slow",
"-crf", "20", "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(path)],
stdin=subprocess.PIPE)
def add(self, img, n=1):
b = np.asarray(img.convert("RGB").resize((W, H)) if img.size != (W, H) else img.convert("RGB")).tobytes()
for _ in range(n):
self.p.stdin.write(b)
def close(self):
self.p.stdin.close()
self.p.wait()
def to_gif(mp4, width=640, fps=12):
gif = mp4.with_suffix(".gif")
pal = mp4.with_suffix(".pal.png")
vf = f"fps={fps},scale={width}:-1:flags=lanczos"
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(mp4), "-vf", vf + ",palettegen=max_colors=128",
str(pal)], check=True)
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(mp4), "-i", str(pal), "-lavfi",
vf + "[x];[x][1:v]paletteuse=dither=sierra2_4a", str(gif)], check=True)
pal.unlink()
return gif
def card(title, lines, accent=TEAL):
im = Image.new("RGB", (W, H), BG)
d = ImageDraw.Draw(im)
d.rectangle([0, 0, 14, H], fill=accent)
d.text((80, 230), title, font=font(46, True), fill=INK)
for k, ln in enumerate(lines):
d.text((82, 320 + 44 * k), ln, font=font(26), fill=(75, 85, 99))
return im
# ============================================================================ robot rollouts
def robot_rollouts(n_show=3, liars=(1, 2, 3), robot="so101"):
if robot == "panda":
from robotics.sim.panda_env import rollout
else:
from robotics.sim.so101_env import rollout
eps = {e["seed"]: e for e in map(json.loads, open(f"data/{robot}/episodes.jsonl"))}
(Ph, yh, _), (Pe, ye, kinds) = trackA.load_scores(f"results/{robot}/vlm_scores.jsonl")
eval_seeds = sorted(s for s, e in eps.items() if e["split"] == "eval")
Pa = attacks.apply(Pe, list(liars), "invert", "eval", np.random.default_rng(0))
maj_c = fusion.majority(Pe, Pe)
rs_c = fusion.race_s(Pe, Pe, 0)[:2]
maj_a = fusion.majority(Pa, Pa)
rs_a = fusion.race_s(Pa, Pa, 0)[:2]
dec = lambda st: st[0] > st[1] # noqa: E731
mc, rc, ma, ra = dec(maj_c), dec(rs_c), dec(maj_a), dec(rs_a)
want = ["success", "wrong_place", "wrong_object", "drop_transit", "miss_grasp"]
picks = []
for mode in want:
for k, s in enumerate(eval_seeds):
if eps[s]["mode"] == mode and rc[k] == ye[k] and ra[k] == ye[k] and ma[k] != ye[k] and k not in picks:
picks.append(k)
break
if len(picks) == n_show:
break
out_path = OUT / ("panda_rollouts.mp4" if robot == "panda" else "robot_rollouts.mp4")
arm = "Franka Panda" if robot == "panda" else "SO-101"
wr = Writer(out_path)
wr.add(card(f"RoboRACE · {arm} camera swarm", [
f"A MuJoCo {arm} arm (Menagerie model) runs scripted pick-and-place with injected failures.",
"Ground truth comes from the final physics state, never from the script.",
"Five camera agents judge success with Cosmos-Reason2-2B on a CPU; then 3 of 5 cameras lie.",
"Majority vote vs RACE-S (label-free, receiver-anchored) — real cached scores."]), FPS * 4)
for n, k in enumerate(picks):
seed = eval_seeds[k]
e = eps[seed]
ep = rollout(seed, want_success=(e["mode"] == "success"), record_video=True, render_size=320)
assert ep.success == e["success"], "replay must reproduce the cached episode"
frames = ep.frames + [ep.frames[-1]] * 1
for f_i, fr in enumerate(frames):
wr.add(_robot_frame(fr, e, n, len(picks), phase="rollout", progress=f_i / len(frames)))
for phase, P, fused_maj, fused_rs in (("clean", Pe, mc, rc), ("attack", Pa, ma, ra)):
for t in range(int(FPS * 3.2)):
wr.add(_robot_frame(frames[-1], e, n, len(picks), phase=phase, scores=P[k], reveal=min(1, t / 25),
maj=fused_maj[k], rs=fused_rs[k], gt=ye[k], liars=liars if phase == "attack" else ()))
wr.add(card("Takeaway", ["With an honest swarm, every fusion rule agrees with the ground truth.",
"With a liar majority, majority vote flips; RACE-S learns negative weights for",
"the lying cameras without labels, inverts them, and stays correct."]), FPS * 4)
wr.close()
return out_path
def panda_rollouts():
return robot_rollouts(robot="panda")
def _robot_frame(views, e, n, n_tot, phase, progress=0.0, scores=None, reveal=0.0, maj=None, rs=None, gt=None, liars=()):
from robotics.sim.so101_env import CAMERAS
im = Image.new("RGB", (W, H), BG)
d = ImageDraw.Draw(im)
d.rectangle([0, 0, W, 58], fill=(255, 255, 255))
d.text((20, 12), f"Task: “{e['task']}”", font=font(24, True), fill=INK)
d.text((W - 300, 18), f"episode {n + 1}/{n_tot} · seed {e['seed']}", font=font(17), fill=(107, 114, 128))
pos = [(10, 68), (330, 68), (650, 68), (10, 396), (330, 396)]
for j, c in enumerate(CAMERAS):
x, y = pos[j]
tile = Image.fromarray(views[c]).resize((310, 310))
im.paste(tile, (x, y))
liar = j in liars
col = RED if liar else (TEAL if j == 0 else GREY)
d.rectangle([x - 2, y - 2, x + 311, y + 311], outline=col, width=5 if (liar or j == 0) else 2)
lab = f"{c}{' · receiver' if j == 0 else ''}{' · LIAR' if liar else ''}"
d.rectangle([x, y, x + 8 + 10 * len(lab), y + 26], fill=col)
d.text((x + 5, y + 3), lab, font=font(15, True), fill=(255, 255, 255))
if scores is not None:
p = float(scores[j])
bw_ = int(296 * p * reveal)
d.rectangle([x + 7, y + 284, x + 303, y + 302], fill=(243, 244, 246))
d.rectangle([x + 7, y + 284, x + 7 + bw_, y + 302], fill=RED if liar else TEAL)
d.text((x + 10, y + 262), f"P(success) = {p:.2f}", font=font(15, True), fill=(255, 255, 255),
stroke_width=2, stroke_fill=(0, 0, 0))
# sixth cell: how to read the frame
lx, ly = 650, 396
d.rectangle([lx, ly, lx + 310, ly + 310], fill=(255, 255, 255), outline=(229, 231, 235), width=2)
d.text((lx + 16, ly + 14), "How to read", font=font(18, True), fill=INK)
legend = [(TEAL, "receiver (own camera)"), (RED, "lying camera"), (GREY, "honest camera")]
for k, (col, txt) in enumerate(legend):
y0 = ly + 52 + 34 * k
d.rectangle([lx + 16, y0, lx + 34, y0 + 18], outline=col, width=4)
d.text((lx + 44, y0), txt, font=font(14), fill=INK)
d.text((lx + 16, ly + 162), "bar = the camera's reported\nP(success) from Cosmos-Reason2-2B\n(real cached scores, CPU)",
font=font(14), fill=(75, 85, 99), spacing=4)
d.text((lx + 16, ly + 238), "ground truth = final physics\nstate, never the script", font=font(14), fill=(75, 85, 99),
spacing=4)
# right panel
px = 970
d.rectangle([px, 68, W - 10, H - 10], fill=(255, 255, 255), outline=(229, 231, 235), width=2)
if phase == "rollout":
d.text((px + 18, 88), "Executing", font=font(22, True), fill=INK)
d.text((px + 18, 122), "IK + position control,\nkinematic grasp,\nfree-body physics", font=font(16),
fill=(75, 85, 99), spacing=6)
d.rectangle([px + 18, 220, W - 30, 236], fill=(243, 244, 246))
d.rectangle([px + 18, 220, px + 18 + int((W - 48 - px) * progress), 236], fill=TEAL)
return im
title = "Honest swarm" if phase == "clean" else "3 of 5 cameras lie"
d.text((px + 18, 88), title, font=font(22, True), fill=TEAL if phase == "clean" else RED)
d.text((px + 18, 122), "reports inverted: 1 − p" if phase == "attack" else "all cameras report truthfully",
font=font(15), fill=(75, 85, 99))
if reveal >= 1:
rows = [("Majority vote", maj), ("RACE-S (ours)", rs)]
for k, (nm, v) in enumerate(rows):
ok = v == gt
y0 = 180 + 92 * k
d.text((px + 18, y0), nm, font=font(18, True), fill=INK)
d.text((px + 18, y0 + 28), f"{'SUCCESS' if v else 'FAILURE'} {'✓' if ok else '✗'}", font=font(24, True),
fill=TEAL if ok else RED)
d.line([px + 18, 372, W - 30, 372], fill=(229, 231, 235), width=2)
d.text((px + 18, 386), "Ground truth (physics)", font=font(16, True), fill=INK)
d.text((px + 18, 412), f"{'SUCCESS' if gt else 'FAILURE'}", font=font(24, True), fill=INK)
if e["mode"] != "success":
d.text((px + 18, 446), "failure mode: " + e["mode"].replace("_", " "), font=font(16), fill=(107, 114, 128))
return im
# ============================================================================ swarm rendezvous
def swarm_rendezvous(F=4, attack="collude", seed=11):
from matplotlib.backends.backend_agg import FigureCanvasAgg
methods = [("mean", "DeGroot average", GREY), ("wmsr", "W-MSR (LeBlanc 2013)", (37, 99, 235)),
("race_c+wmsr", "RACE-C + W-MSR (ours)", TEAL)]
base = trackB.World(F=F, attack=attack, seed=seed)
target = np.array([6.5, 4.0])
m = base.measure(target)
traces = {}
for meth, _, _ in methods:
w = trackB.World(F=F, attack=attack, seed=seed)
w.sigma, w.byz, w.A, w.pos = base.sigma, base.byz, base.A, base.pos
chan = trackB.channel_estimates(w, trackB.history(w)) if meth.startswith("race_c") else None
tr = []
if meth.startswith("race_c"):
trackB.mission(w, meth, chan, target=target, m=m.copy(), trace=tr)
else:
x = m.copy()
honest = ~w.byz
tr = [(x.copy(), np.zeros((w.n, w.n), bool))]
for rnd in range(15):
new = x.copy()
for i in np.flatnonzero(honest):
nb = np.flatnonzero(w.A[i])
vals = np.array([w.lie(j, i, x[j], target, "eval", rnd) if w.byz[j] else x[j] for j in nb])
new[i] = np.vstack([x[i], vals]).mean(0) if meth == "mean" else trackB._wmsr(x[i], vals, w.F)
x = new
tr.append((x.copy(), np.zeros((w.n, w.n), bool)))
traces[meth] = tr
honest = ~base.byz
n_rounds = max(len(t) for t in traces.values())
per, hold = 9, 60
pos = {k: base.pos.astype(float).copy() for k in traces}
trail = {k: [base.pos.astype(float).copy()] for k in traces}
err_hist = {k: [] for k in traces}
allp = np.vstack([base.pos, target, target + base.bloc])
lo, hi = allp.min(0) - 0.8, allp.max(0) + 0.8
wr = Writer(OUT / "swarm_rendezvous.mp4")
wr.add(card("RoboRACE · Byzantine rendezvous", [
"12 robots measure a target with noisy sensors, agree on it by radio, and drive there.",
f"{F} robots are Byzantine and collude: they all broadcast the same false target.",
"Same robots, same lies, three consensus rules."], accent=(37, 99, 235)), FPS * 3)
fig = plt.figure(figsize=(12.8, 7.2), dpi=100)
canvas = FigureCanvasAgg(fig)
for t in range(n_rounds * per + hold):
r = min(t // per, n_rounds - 1)
fig.clf()
gs = fig.add_gridspec(2, 3, height_ratios=[3.2, 1], left=0.02, right=0.98, top=0.9, bottom=0.08, hspace=0.25,
wspace=0.05)
for col, (meth, title, c) in enumerate(methods):
ax = fig.add_subplot(gs[0, col])
est, banned = traces[meth][min(r, len(traces[meth]) - 1)]
pos[meth][honest] += 0.1 * (est[honest] - pos[meth][honest])
trail[meth].append(pos[meth].copy())
P = pos[meth]
Tr = np.array(trail[meth])
for i in range(base.n):
for j in np.flatnonzero(base.A[i]):
if j > i:
iso = (banned[i, j] and honest[i]) or (banned[j, i] and honest[j])
ax.plot(*zip(P[i], P[j]), color="#dc2626" if iso else "#e5e7eb", lw=1.6 if iso else 0.6,
ls="--" if iso else "-", zorder=1)
for i in np.flatnonzero(honest):
ax.plot(Tr[:, i, 0], Tr[:, i, 1], color=np.array(c) / 255, alpha=0.35, lw=1, zorder=2)
ax.add_patch(plt.Circle(target, 0.5, fill=False, ls=":", color="#b45309", lw=1.4, zorder=3))
ax.scatter(*target, marker="*", s=260, color="#f59e0b", edgecolor="black", zorder=3)
ax.scatter(*(target + base.bloc), marker="P", s=110, color="#fecaca", edgecolor="#dc2626", zorder=3)
ax.scatter(P[honest, 0], P[honest, 1], s=42, color=np.array(c) / 255, edgecolor="white", zorder=5)
ax.scatter(P[~honest, 0], P[~honest, 1], s=80, marker="X", color="#dc2626", zorder=5)
err = np.linalg.norm(P[honest] - target, axis=1).max()
if col == 0 or len(err_hist[meth]) < t + 1:
err_hist[meth].append(err)
ax.set_xlim(lo[0], hi[0])
ax.set_ylim(lo[1], hi[1])
ax.set_aspect("equal")
ax.set_xticks([])
ax.set_yticks([])
ax.set_title(title, fontsize=13, fontweight="bold", color=np.array(c) / 255 if col else "#374151")
ok = err < 0.5
ax.text(0.02, 0.03, f"worst honest error {err:.2f} m" + (" ✓" if ok else ""), transform=ax.transAxes,
fontsize=11, fontweight="bold", color="#0f766e" if ok else "#b91c1c")
axe = fig.add_subplot(gs[1, :])
for meth, title, c in methods:
axe.plot(np.arange(len(err_hist[meth])) / FPS, err_hist[meth], color=np.array(c) / 255, lw=2, label=title)
axe.axhline(0.5, color="#b45309", ls=":", lw=1.2)
axe.text(0.01, 0.55, "mission tolerance 0.5 m", fontsize=9, color="#b45309", transform=axe.get_yaxis_transform())
axe.set_xlim(0, (n_rounds * per + hold) / FPS)
axe.set_ylim(0, max(8, max(max(v) for v in err_hist.values())))
axe.set_ylabel("worst honest\nerror (m)", fontsize=9)
axe.set_xlabel("time (s)", fontsize=9)
axe.legend(fontsize=9, ncol=3, loc="upper right", frameon=False)
axe.spines[["top", "right"]].set_visible(False)
fig.suptitle("★ true target ✚ liars' false target ✖ Byzantine robot red dashed = link isolated by RACE-C",
fontsize=11, x=0.02, ha="left", y=0.975, color="#374151")
canvas.draw()
wr.add(Image.frombuffer("RGBA", canvas.get_width_height(), canvas.buffer_rgba()).convert("RGB"))
plt.close(fig)
wr.close()
return OUT / "swarm_rendezvous.mp4"
# ============================================================================ PlanBench LLM-Modulo
COLMAP = {"red": (220, 38, 38), "blue": (37, 99, 235), "orange": (249, 115, 22), "yellow": (234, 179, 8),
"green": (22, 163, 74), "purple": (147, 51, 234), "white": (229, 231, 235), "black": (31, 41, 55)}
def _stacks(state):
towers = []
for b, under in state.on.items():
if under == "table":
tower = [b]
while True:
above = [x for x, u in state.on.items() if u == tower[-1]]
if not above:
break
tower.append(above[0])
towers.append(tower)
return sorted(towers)
def _bw_frame(state, title, sub, goal, status=None, status_col=INK, plan=None, cur=-1, failed=None):
im = Image.new("RGB", (W, H), BG)
d = ImageDraw.Draw(im)
d.text((40, 24), title, font=font(26, True), fill=INK)
d.text((40, 62), sub, font=font(17), fill=(75, 85, 99))
d.rectangle([40, 600, 760, 610], fill=(120, 113, 108))
bs = 74
for k, tower in enumerate(_stacks(state)):
x = 70 + k * 120
for h, b in enumerate(tower):
y = 600 - (h + 1) * bs
d.rounded_rectangle([x, y, x + bs - 4, y + bs - 4], radius=8, fill=COLMAP.get(b, GREY), outline=INK, width=2)
d.text((x + 8, y + 26), b, font=font(15, True), fill=(255, 255, 255), stroke_width=2, stroke_fill=(0, 0, 0))
if state.holding:
b = state.holding
d.rounded_rectangle([380, 130, 380 + bs - 4, 130 + bs - 4], radius=8, fill=COLMAP.get(b, GREY), outline=INK, width=2)
d.text((388, 156), b, font=font(15, True), fill=(255, 255, 255), stroke_width=2, stroke_fill=(0, 0, 0))
d.line([418, 100, 418, 130], fill=INK, width=4)
d.text((470, 150), "hand", font=font(15), fill=(107, 114, 128))
d.rectangle([800, 110, W - 30, H - 30], fill=(255, 255, 255), outline=(229, 231, 235), width=2)
d.text((820, 124), "goal: " + ", ".join(f"{a} on {b}" for a, b in goal), font=font(15, True), fill=INK)
if plan:
for i, stp in enumerate(plan[:14]):
col = RED if failed == i else (TEAL if i < cur or (i == cur and failed is None) else (107, 114, 128))
mark = "▶ " if i == cur else " "
d.text((820, 165 + 28 * i), f"{mark}{i + 1}. {stp}", font=font(16, i == cur), fill=col)
if status:
d.rectangle([40, 650, 760, 700], fill=(255, 255, 255), outline=status_col, width=3)
d.text((56, 663), status, font=font(17, True), fill=status_col)
return im
def planbench_modulo():
ins = {i["instance_id"]: i for i in bw.load()}
best = None
for f in sorted(Path("results/planbench").glob("*.jsonl")):
for r in map(json.loads, open(f)):
if (not r["oneshot"]) and r["modulo"] and r["attempts"][0]["error"] and len(r["attempts"]) == 2:
if best is None or len(r["attempts"][0]["plan"]) > len(best[1]["attempts"][0]["plan"]):
best = (f.stem, r)
agent, r = best
q = ins[r["instance_id"]]["query"]
s0, goal = bw.parse_statement(q)
wr = Writer(OUT / "planbench_modulo.mp4")
wr.add(card("PlanBench Blocksworld · LLM-Modulo", [
f"Instance {r['instance_id']} of the official PlanBench plan-generation task (Valmeekam et al.).",
f"Agent: {agent}. Every frame below replays its real cached answers.",
"An exact simulator checks each action; its error message is the repair feedback."], accent=AMBER), FPS * 3)
for a_i, att in enumerate(r["attempts"]):
s = s0.copy()
steps = bw.parse_plan("\n".join(f"({x})" for x in att["plan"])) # cached as "act a b" -> PDDL
label = "one-shot plan (official prompt)" if a_i == 0 else "repaired plan after validator feedback"
wr.add(_bw_frame(s, f"Attempt {a_i + 1}: {label}", f"{len(steps)} actions", goal, plan=att["plan"], cur=-1), FPS)
failed = None
for i, (act, args) in enumerate(steps):
err = bw.step(s, act, args)
if err:
failed = i
wr.add(_bw_frame(s, f"Attempt {a_i + 1}: {label}", f"executing step {i + 1}", goal,
status=f"✗ validator: step {i + 1}: {err}"[:78], status_col=RED, plan=att["plan"],
cur=i, failed=i), FPS * 4)
break
wr.add(_bw_frame(s, f"Attempt {a_i + 1}: {label}", f"executing step {i + 1}", goal, plan=att["plan"], cur=i),
int(FPS * 0.7))
if failed is None:
reached = all(s.on.get(a) == b for a, b in goal)
wr.add(_bw_frame(s, f"Attempt {a_i + 1}: {label}", "done", goal,
status="✓ goal reached — plan valid" if reached else "✗ executable but goal not reached",
status_col=TEAL if reached else RED, plan=att["plan"], cur=len(steps)), FPS * 3)
wr.close()
return OUT / "planbench_modulo.mp4"
# ============================================================================ Track D maze swarm
def _maze_xml(G, goal, n, byz, cell=0.2):
H, W = G.shape
walls = "".join(f'