Download progresslm/scripts/render_figures.py from Vio1etV/Robustness_of_progress_model: direct link, hf CLI and curl.
- Browser
- Download file 14 kB
-
https://huggingface.co/datasets/Vio1etV/Robustness_of_progress_model/resolve/main/progresslm/scripts/render_figures.py
- Command line
-
hf download hf://datasets/Vio1etV/Robustness_of_progress_model/progresslm/scripts/render_figures.py
-
curl -L -o render_figures.py https://huggingface.co/datasets/Vio1etV/Robustness_of_progress_model/resolve/main/progresslm/scripts/render_figures.py
14 kB
| #!/usr/bin/env python3 | |
| """ | |
| Render summary figures + stats from episode_results/ (no GPU needed). | |
| ProgressLM demo-robustness (mirror of the Robometer prefix-robustness figures, | |
| adapted because ProgressLM produces ONE score per checkpoint β not a dense | |
| curve). Same metrics/threshold, terminology renamed Prefix -> Demo per v4. | |
| Reads: <results-root>/episode_results/<chunk>_<episode>/<mode>.json | |
| Writes: <results-root>/summary/ | |
| fig1_absolute_scores.png 4 checkpoints x episodes x 5 demo modes | |
| fig2_metrics.png Demo Range / Demo Std / Reference Error | |
| fig3_by_length.png range vs video length | |
| summary.md mean / median / p90, %>threshold, n/a rate | |
| top10/rankNN_<episode>.png 5-mode x 4-checkpoint overlays, worst episodes | |
| Run with any python that has numpy + matplotlib (e.g. conda qwenvl): | |
| 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 = ["demo5_uniform", "demo3_sparse", "demo9_dense", "demo5_jitterA", "demo5_jitterB"] | |
| BASELINE = "demo5_uniform" | |
| MODE_COLORS = { | |
| "demo5_uniform": "tab:blue", "demo3_sparse": "tab:orange", "demo9_dense": "tab:green", | |
| "demo5_jitterA": "tab:red", "demo5_jitterB": "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 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 is per-checkpoint, not per-pool-idx) ββ | |
| score = defaultdict(dict) # (ep, frac) -> {mode: score or None} | |
| rng_, std_ = {}, {} # (ep, frac) -> float (over present modes) | |
| ref_err = defaultdict(list) # mode -> [score - baseline score] | |
| na_count = defaultdict(int) # mode -> #n/a cells | |
| na_examples = defaultdict(list) # mode -> [(ep, frac, raw_response)] | |
| total_cells = 0 | |
| for ep in eps: | |
| for ci, frac in enumerate(FRACS): | |
| total_cells += 1 | |
| present = {} | |
| for m in MODES: | |
| sc = data[ep][m]["scores_100"][ci] | |
| score[(ep, frac)][m] = sc | |
| if sc is None: | |
| na_count[m] += 1 | |
| if len(na_examples[m]) < 3: | |
| na_examples[m].append( | |
| (ep, frac, data[ep][m].get("raw_responses", ["<none>"] * 4)[ci])) | |
| else: | |
| present[m] = sc | |
| vals = np.array(list(present.values()), dtype=float) | |
| if len(vals) >= 2: | |
| rng_[(ep, frac)] = float(vals.max() - vals.min()) | |
| std_[(ep, frac)] = float(vals.std(ddof=0)) | |
| base_sc = score[(ep, frac)][BASELINE] | |
| if base_sc is not None: | |
| for m in MODES: | |
| if m == BASELINE: | |
| continue | |
| if score[(ep, frac)][m] is not None: | |
| ref_err[m].append(score[(ep, frac)][m] - base_sc) | |
| # per-episode aggregates (over checkpoints that have a valid range) | |
| ep_rngs = {e: [rng_[(e, f)] for f in FRACS if (e, f) in rng_] for e in eps} | |
| eps_valid = [e for e in eps if ep_rngs[e]] | |
| ep_mean_rng = {e: float(np.mean(ep_rngs[e])) for e in eps_valid} | |
| ep_max_rng = {e: float(max(ep_rngs[e])) for e in eps_valid} | |
| order = sorted(eps_valid, 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) if all_rng else 0.0 | |
| # ββ 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 if score[(e, frac)][m] is not None] | |
| if vals: | |
| ax.plot([i, i], [min(vals), max(vals)], color="0.85", lw=1, zorder=1) | |
| for m in MODES: | |
| ys = [score[(e, frac)][m] for e in order] | |
| xs = [i for i, y in enumerate(ys) if y is not None] | |
| yy = [y for y in ys if y is not None] | |
| ax.scatter(xs, yy, 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 Demo Range, desc)") | |
| fig.suptitle("Summary of absolute progress scores β 5 demo modes per episode\n" | |
| "(gray bar = min-max spread at the same physical target 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 if (e, frac) in rng_), reverse=True) | |
| if not vals: | |
| continue | |
| 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("Demo Range (pts)") | |
| ax.set_title("(A) Demo 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("Demo Range (pts)") | |
| ax.set_ylabel("count (episode x checkpoint)") | |
| ax.set_title(f"(B) Demo 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("Demo Std (pts)") | |
| ax.set_ylabel("count (episode x checkpoint)") | |
| ax.set_title("(C) Demo Std distribution") | |
| ax.grid(alpha=0.2) | |
| ax = axes[1][1] | |
| ax.boxplot([ref_err[m] for m in MODES if m != BASELINE], | |
| labels=[m.replace("_", "\n") for m in MODES if m != BASELINE], | |
| showmeans=True) | |
| ax.axhline(0, color="black", lw=1) | |
| ax.set_ylabel(f"score - {BASELINE} score (pts)") | |
| ax.set_title("(D) Reference Error vs baseline (signed)") | |
| ax.grid(alpha=0.2) | |
| fig.suptitle("Demo-robustness metrics (ProgressLM-3B-RL, 4 checkpoints)", 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][BASELINE]["total_raw_frames"] | |
| / max(data[e][BASELINE]["native_fps"], 1e-6) for e in eps_valid]) | |
| mrng = np.array([ep_max_rng[e] for e in eps_valid]) | |
| if len(dur): | |
| 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={int(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 Demo Range over 4 checkpoints (pts)") | |
| ax.set_title("Demo 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) | |
| if len(a) == 0: | |
| return "n/a (no data)" | |
| 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]][BASELINE]["camera"] | |
| lines = ["# ProgressLM-3B-RL demo-robustness β full batch summary", ""] | |
| lines += [f"Episodes: **{len(eps)}** | camera: {cam} | " | |
| f"modes: {', '.join(MODES)} | baseline: {BASELINE} | " | |
| f"threshold: {THRESHOLD:.0f} pts", ""] | |
| lines += ["Each score = ProgressLM scoring one fixed target frame against a self-demo; " | |
| "the perturbation is the demo organisation. Metrics compare the 5 modes at the " | |
| "same physical target frame.", ""] | |
| lines += ["## Demo Range (max - min of the 5 mode scores, same target frame)", "", | |
| "| checkpoint | stats | % > threshold |", "|---|---|---|"] | |
| for frac in FRACS: | |
| vals = [rng_[(e, frac)] for e in eps if (e, frac) in rng_] | |
| pct = 100.0 * np.mean(np.array(vals) > THRESHOLD) if vals else 0.0 | |
| 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_valid]) | |
| if eps_valid else 0.0) | |
| lines += ["", f"Episodes with >= 1 checkpoint above threshold: **{ep_any:.1f}%**", ""] | |
| lines += ["## Demo Std", "", f"All cells: {stats(list(std_.values()))}", ""] | |
| lines += ["## Reference Error vs baseline (signed, pts)", "", | |
| "| mode | mean | median | std | n |", "|---|---|---|---|---|"] | |
| for m in MODES: | |
| if m == BASELINE: | |
| continue | |
| a = np.array(ref_err[m]) | |
| if len(a): | |
| lines.append(f"| {m} | {a.mean():+.2f} | {np.median(a):+.2f} | {a.std():.2f} | {len(a)} |") | |
| else: | |
| lines.append(f"| {m} | n/a | n/a | n/a | 0 |") | |
| lines.append("") | |
| # ββ n/a report ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| lines += ["## n/a rate (per mode; a cell = one episode x checkpoint)", "", | |
| f"Total cells per mode: **{total_cells}**", "", | |
| "| mode | n/a count | n/a rate |", "|---|---|---|"] | |
| high_na = [] | |
| for m in MODES: | |
| rate = 100.0 * na_count[m] / max(total_cells, 1) | |
| flag = " **>10%**" if rate > 10.0 else "" | |
| lines.append(f"| {m} | {na_count[m]} | {rate:.1f}%{flag} |") | |
| if rate > 10.0: | |
| high_na.append(m) | |
| lines.append("") | |
| if high_na: | |
| lines += ["### High-n/a modes β 3 example raw responses each", ""] | |
| for m in high_na: | |
| lines.append(f"**{m}**") | |
| for ep, frac, raw in na_examples[m]: | |
| snippet = (raw or "").replace("\n", " ")[:400] | |
| lines.append(f"- `{ep}` @ {frac}: {snippet}") | |
| lines.append("") | |
| # ββ top10: 5-mode x 4-checkpoint overlays βββββββββββββββββββββββββββββ | |
| worst = sorted(eps_valid, key=lambda e: -ep_max_rng[e])[:args.top_n] | |
| lines += [f"## Top {args.top_n} least-robust episodes (by max Demo Range)", "", | |
| "| rank | episode | max range | mean range | figure |", | |
| "|---|---|---|---|---|"] | |
| xt = np.arange(len(FRACS)) | |
| for rank, e in enumerate(worst, 1): | |
| 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=(11, 6)) | |
| for m in MODES: | |
| ys = [score[(e, f)][m] for f in FRACS] | |
| xs = [i for i, y in enumerate(ys) if y is not None] | |
| yy = [y for y in ys if y is not None] | |
| ax.plot(xs, yy, "-o", color=MODE_COLORS[m], lw=1.6, ms=6, label=m) | |
| ax.set_xticks(xt) | |
| ax.set_xticklabels(FRACS) | |
| ax.set_xlabel("checkpoint (target frame 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][BASELINE]["task"] | |
| ax.set_title(f"#{rank} {e} max Demo 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() | |