Vio1etV's picture
Prefix-robustness: runners + robometer results + v-docs
45e45cb verified
Raw
History Blame Contribute Delete
11 kB
#!/usr/bin/env python3
"""
Render summary figures + stats from episode_results/ (no GPU needed).
Reads: <results-root>/episode_results/<chunk>_<episode>/<mode>.json
Writes: <results-root>/summary/
fig1_absolute_scores.png 4 checkpoints x episodes x 5 modes
fig2_metrics.png Prefix Range / Prefix Std / Reference Error
fig3_by_length.png range vs video length
summary.md mean / median / p90, %>threshold
top10/rankNN_<episode>.png full 5-curve overlays, worst episodes
Run with any python that has numpy + matplotlib:
python render_figures.py [--results-root PATH] [--top-n 10]
"""
from __future__ import annotations
import argparse
import json
from collections import defaultdict
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
MODES = ["uniform", "front_biased", "back_biased", "random_seed0", "random_seed1"]
MODE_COLORS = {
"uniform": "tab:blue", "front_biased": "tab:orange", "back_biased": "tab:green",
"random_seed0": "tab:red", "random_seed1": "tab:purple",
}
FRACS = ["1/4", "2/4", "3/4", "end"]
THRESHOLD = 20.0
def parse_args():
p = argparse.ArgumentParser()
base = Path(__file__).resolve().parent.parent
p.add_argument("--results-root", default=str(base / "results_full"))
p.add_argument("--top-n", type=int, default=10)
return p.parse_args()
def load_episodes(results_root: Path):
"""-> {ep_key: {mode: payload}} for episodes with all 5 modes present."""
data = {}
for ep_dir in sorted((results_root / "episode_results").iterdir()):
if not ep_dir.is_dir():
continue
modes = {}
for m in MODES:
f = ep_dir / f"{m}.json"
if f.exists():
modes[m] = json.loads(f.read_text())
if len(modes) == len(MODES):
data[ep_dir.name] = modes
return data
def checkpoints_of(pool_n: int) -> list[int]:
return [int((pool_n - 1) * k / 4) for k in (1, 2, 3, 4)]
def main():
args = parse_args()
root = Path(args.results_root)
out = root / "summary"
(out / "top10").mkdir(parents=True, exist_ok=True)
data = load_episodes(root)
eps = sorted(data)
print(f"episodes with all {len(MODES)} modes: {len(eps)}")
if not eps:
return
# ── extract checkpoint scores + metrics ───────────────────────────────
# score[(ep, frac)][mode], rng_[(ep, frac)], std_[(ep, frac)]
score = defaultdict(dict)
rng_, std_ = {}, {}
ref_err = defaultdict(list) # mode -> [score - uniform score]
for ep in eps:
n = data[ep]["uniform"]["pool_n"]
cps = checkpoints_of(n)
for frac, t in zip(FRACS, cps):
for m in MODES:
score[(ep, frac)][m] = data[ep][m]["scores_100"][t]
arr = np.array([score[(ep, frac)][m] for m in MODES])
rng_[(ep, frac)] = float(arr.max() - arr.min())
std_[(ep, frac)] = float(arr.std(ddof=0))
for m in MODES[1:]:
ref_err[m].append(score[(ep, frac)][m] - score[(ep, frac)]["uniform"])
ep_mean_rng = {e: np.mean([rng_[(e, f)] for f in FRACS]) for e in eps}
ep_max_rng = {e: max(rng_[(e, f)] for f in FRACS) for e in eps}
order = sorted(eps, key=lambda e: -ep_mean_rng[e])
x = np.arange(len(order))
all_rng = list(rng_.values())
pct_all = 100.0 * np.mean(np.array(all_rng) > THRESHOLD)
# ── fig1: absolute scores ─────────────────────────────────────────────
fig, axes = plt.subplots(4, 1, figsize=(16, 14), sharex=True)
for ax, frac in zip(axes, FRACS):
for i, e in enumerate(order):
vals = [score[(e, frac)][m] for m in MODES]
ax.plot([i, i], [min(vals), max(vals)], color="0.85", lw=1, zorder=1)
for m in MODES:
ax.scatter(x, [score[(e, frac)][m] for e in order],
s=8, color=MODE_COLORS[m], label=m, zorder=2)
ax.set_ylabel("score (0-100)")
ax.set_title(f"checkpoint {frac}", loc="left", fontsize=11)
ax.set_ylim(0, 100)
ax.grid(alpha=0.2)
axes[0].legend(ncol=5, fontsize=9, loc="upper right")
axes[-1].set_xlabel("episode (sorted by mean Prefix Range, desc)")
fig.suptitle("Summary of absolute progress scores β€” 5 prefix modes per episode\n"
"(gray bar = min-max spread at the same physical frame)", y=0.995)
fig.tight_layout()
fig.savefig(out / "fig1_absolute_scores.png", dpi=150)
plt.close(fig)
# ── fig2: metrics ─────────────────────────────────────────────────────
fig, axes = plt.subplots(2, 2, figsize=(15, 11))
ax = axes[0][0]
for frac in FRACS:
vals = sorted((rng_[(e, frac)] for e in eps), reverse=True)
pct = 100.0 * np.mean(np.array(vals) > THRESHOLD)
ax.plot(vals, label=f"{frac} ({pct:.0f}% > {THRESHOLD:.0f} pts)")
ax.axhline(THRESHOLD, color="red", ls="--", lw=1)
ax.set_xlabel("episode rank (desc)")
ax.set_ylabel("Prefix Range (pts)")
ax.set_title("(A) Prefix Range per checkpoint, sorted")
ax.legend(fontsize=9)
ax.grid(alpha=0.2)
ax = axes[0][1]
ax.hist(all_rng, bins=30, color="tab:red", alpha=0.75)
ax.axvline(THRESHOLD, color="black", ls="--", lw=1.5,
label=f"{THRESHOLD:.0f}-pt threshold")
ax.set_xlabel("Prefix Range (pts)")
ax.set_ylabel("count (episode x checkpoint)")
ax.set_title(f"(B) Prefix Range distribution β€” {pct_all:.0f}% above threshold")
ax.legend(fontsize=9)
ax.grid(alpha=0.2)
ax = axes[1][0]
ax.hist(list(std_.values()), bins=30, color="tab:blue", alpha=0.75)
ax.set_xlabel("Prefix Std (pts)")
ax.set_ylabel("count (episode x checkpoint)")
ax.set_title("(C) Prefix Std distribution")
ax.grid(alpha=0.2)
ax = axes[1][1]
ax.boxplot([ref_err[m] for m in MODES[1:]],
labels=[m.replace("_", "\n") for m in MODES[1:]], showmeans=True)
ax.axhline(0, color="black", lw=1)
ax.set_ylabel("score - uniform score (pts)")
ax.set_title("(D) Reference Error vs uniform (signed)")
ax.grid(alpha=0.2)
fig.suptitle("Prefix-robustness metrics (Robometer, dense curves)", y=0.995)
fig.tight_layout()
fig.savefig(out / "fig2_metrics.png", dpi=150)
plt.close(fig)
# ── fig3: range vs video length ───────────────────────────────────────
fig, ax = plt.subplots(figsize=(10, 6))
dur = np.array([data[e]["uniform"]["total_raw_frames"]
/ max(data[e]["uniform"]["native_fps"], 1e-6) for e in eps])
mrng = np.array([ep_max_rng[e] for e in eps])
qs = np.quantile(dur, [0, 0.25, 0.5, 0.75, 1.0])
groups, labels = [], []
for lo, hi in zip(qs[:-1], qs[1:]):
m = (dur >= lo) & (dur <= hi)
groups.append(mrng[m])
labels.append(f"{lo:.0f}-{hi:.0f}s\n(n={m.sum()})")
ax.boxplot(groups, labels=labels, showmeans=True)
ax.axhline(THRESHOLD, color="red", ls="--", lw=1)
ax.set_xlabel("video length (quartile bins)")
ax.set_ylabel("max Prefix Range over 4 checkpoints (pts)")
ax.set_title("Prefix Range vs video length")
ax.grid(alpha=0.2)
fig.tight_layout()
fig.savefig(out / "fig3_by_length.png", dpi=150)
plt.close(fig)
# ── summary.md ────────────────────────────────────────────────────────
def stats(vals):
a = np.array(vals)
return (f"mean {a.mean():.2f} | median {np.median(a):.2f} | "
f"p90 {np.quantile(a, 0.9):.2f} | max {a.max():.2f}")
cam = data[eps[0]]["uniform"]["camera"]
lines = ["# Robometer prefix-robustness β€” full batch summary (dense curves)", ""]
lines += [f"Episodes: **{len(eps)}** | camera: {cam} | "
f"modes: {', '.join(MODES)} | threshold: {THRESHOLD:.0f} pts", ""]
lines += ["## Prefix Range (max - min of 5 mode scores, same frame)", "",
"| checkpoint | stats | % > threshold |", "|---|---|---|"]
for frac in FRACS:
vals = [rng_[(e, frac)] for e in eps]
pct = 100.0 * np.mean(np.array(vals) > THRESHOLD)
lines.append(f"| {frac} | {stats(vals)} | **{pct:.1f}%** |")
lines.append(f"| all | {stats(all_rng)} | **{pct_all:.1f}%** |")
ep_any = 100.0 * np.mean([ep_max_rng[e] > THRESHOLD for e in eps])
lines += ["", f"Episodes with >= 1 checkpoint above threshold: **{ep_any:.1f}%**", ""]
lines += ["## Prefix Std", "", f"All cells: {stats(list(std_.values()))}", ""]
lines += ["## Reference Error vs uniform (signed, pts)", "",
"| mode | mean | median | std |", "|---|---|---|---|"]
for m in MODES[1:]:
a = np.array(ref_err[m])
lines.append(f"| {m} | {a.mean():+.2f} | {np.median(a):+.2f} | {a.std():.2f} |")
lines.append("")
# ── top10: full-curve overlays ────────────────────────────────────────
worst = sorted(eps, key=lambda e: -ep_max_rng[e])[:args.top_n]
lines += [f"## Top {args.top_n} least-robust episodes (by max Prefix Range)", "",
"| rank | episode | max range | mean range | figure |",
"|---|---|---|---|---|"]
for rank, e in enumerate(worst, 1):
n = data[e]["uniform"]["pool_n"]
cps = checkpoints_of(n)
fname = f"rank{rank:02d}_{e}.png"
lines.append(f"| {rank} | {e} | {ep_max_rng[e]:.1f} | "
f"{ep_mean_rng[e]:.1f} | top10/{fname} |")
fig, ax = plt.subplots(figsize=(13, 6))
xs = np.arange(n) / max(n - 1, 1)
for m in MODES:
ax.plot(xs, data[e][m]["scores_100"], color=MODE_COLORS[m],
lw=1.5, label=m)
for frac, t in zip(FRACS, cps):
ax.axvline(t / max(n - 1, 1), color="0.6", ls=":", lw=1)
ax.text(t / max(n - 1, 1), 97, frac, ha="center", fontsize=8, color="0.4")
ax.set_xlabel("relative position in episode")
ax.set_ylabel("progress score (0-100)")
ax.set_ylim(0, 100)
ax.grid(alpha=0.2)
ax.legend(fontsize=9)
task = data[e]["uniform"]["task"]
ax.set_title(f"#{rank} {e} max range {ep_max_rng[e]:.1f}\n{task[:110]}",
fontsize=10)
fig.tight_layout()
fig.savefig(out / "top10" / fname, dpi=140)
plt.close(fig)
(out / "summary.md").write_text("\n".join(lines))
print("written:", out)
if __name__ == "__main__":
main()