Download dopamine/scripts/render_figures.py from Vio1etV/Robustness_of_progress_model: direct link, hf CLI and curl.
- Browser
- Download file 13.4 kB
-
https://huggingface.co/datasets/Vio1etV/Robustness_of_progress_model/resolve/main/dopamine/scripts/render_figures.py
- Command line
-
hf download hf://datasets/Vio1etV/Robustness_of_progress_model/dopamine/scripts/render_figures.py
-
curl -L -o render_figures.py https://huggingface.co/datasets/Vio1etV/Robustness_of_progress_model/resolve/main/dopamine/scripts/render_figures.py
13.4 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 Anchor Range / Anchor 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 | |
| The 5 modes are the 3 GRM BEFORE-anchoring modes (incremental / forward / | |
| backward) plus 2 sampling-density variants (interval_half / interval_double). | |
| Because the density variants sample a different number of frames, checkpoints | |
| are aligned by physical AFTER-frame index: the incremental (baseline) sequence | |
| defines the 4 target frames (1/4, 2/4, 3/4, end); every mode contributes the | |
| score of its AFTER frame closest to each target. | |
| Metric (same as Robometer): | |
| Anchor Range = max - min of the 5 mode scores at the same physical frame | |
| Anchor Std = std of the 5 mode scores | |
| Reference Error= mode score - incremental score (signed) | |
| threshold = 20 pts | |
| 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 = ["incremental", "forward", "backward", "interval_half", "interval_double"] | |
| BASELINE = "incremental" | |
| MODE_COLORS = { | |
| "incremental": "tab:blue", "forward": "tab:orange", "backward": "tab:green", | |
| "interval_half": "tab:red", "interval_double": "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 = {} | |
| ep_root = results_root / "episode_results" | |
| if not ep_root.exists(): | |
| return data | |
| for ep_dir in sorted(ep_root.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 target_frames(baseline_after: list[int]) -> list[int]: | |
| """4 physical AFTER-frame indices at 1/4, 2/4, 3/4, end of the baseline seq.""" | |
| L = len(baseline_after) | |
| ps = [int(round((L - 1) * k / 4)) for k in (1, 2, 3, 4)] | |
| return [baseline_after[p] for p in ps] | |
| def score_at(payload: dict, target_af: int) -> float: | |
| """Score of the AFTER frame closest to target_af (physical alignment).""" | |
| afs = payload["after_frames"] | |
| j = min(range(len(afs)), key=lambda i: abs(afs[i] - target_af)) | |
| return payload["scores_100"][j] | |
| def video_length_s(payload: dict) -> float: | |
| return payload["total_raw_frames"] / max(payload.get("native_fps", 0.0), 1e-6) | |
| 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 = defaultdict(dict) | |
| rng_, std_ = {}, {} | |
| ref_err = defaultdict(list) # mode -> [score - incremental score] | |
| fb_diff = [] # forward - backward per (ep, frac) | |
| for ep in eps: | |
| base_after = data[ep][BASELINE]["after_frames"] | |
| tgts = target_frames(base_after) | |
| for frac, taf in zip(FRACS, tgts): | |
| for m in MODES: | |
| score[(ep, frac)][m] = score_at(data[ep][m], taf) | |
| 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: | |
| if m == BASELINE: | |
| continue | |
| ref_err[m].append(score[(ep, frac)][m] - score[(ep, frac)][BASELINE]) | |
| fb_diff.append(score[(ep, frac)]["forward"] - score[(ep, frac)]["backward"]) | |
| 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) | |
| non_base = [m for m in MODES if m != BASELINE] | |
| # ββ 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 Anchor Range, desc)") | |
| fig.suptitle("Summary of absolute progress scores - 5 anchoring 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("Anchor Range (pts)") | |
| ax.set_title("(A) Anchor 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("Anchor Range (pts)") | |
| ax.set_ylabel("count (episode x checkpoint)") | |
| ax.set_title(f"(B) Anchor 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("Anchor Std (pts)") | |
| ax.set_ylabel("count (episode x checkpoint)") | |
| ax.set_title("(C) Anchor Std distribution") | |
| ax.grid(alpha=0.2) | |
| ax = axes[1][1] | |
| ax.boxplot([ref_err[m] for m in non_base], | |
| labels=[m.replace("_", "\n") for m in non_base], showmeans=True) | |
| ax.axhline(0, color="black", lw=1) | |
| ax.set_ylabel("score - incremental score (pts)") | |
| ax.set_title("(D) Reference Error vs incremental (signed)") | |
| ax.grid(alpha=0.2) | |
| fig.suptitle("Prefix-robustness metrics (Robo-Dopamine, 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([video_length_s(data[e][BASELINE]) 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={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 Anchor Range over 4 checkpoints (pts)") | |
| ax.set_title("Anchor 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]][BASELINE]["camera"] | |
| lines = ["# Robo-Dopamine prefix-robustness - full batch summary (dense curves)", ""] | |
| lines += [f"Episodes: **{len(eps)}** | camera: {cam} | " | |
| f"modes: {', '.join(MODES)} | threshold: {THRESHOLD:.0f} pts", ""] | |
| lines += ["Score axis = the GRM pipeline `progress` field (0-100), i.e. the " | |
| "per-mode task-completion estimate. The 3 anchor modes share " | |
| f"frame_interval={data[eps[0]]['incremental']['frame_interval']}; " | |
| "interval_half / interval_double halve / double it and are aligned " | |
| "to each checkpoint by the closest physical AFTER frame.", ""] | |
| lines += ["## Anchor 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 += ["## Anchor Std", "", f"All cells: {stats(list(std_.values()))}", ""] | |
| lines += ["## Reference Error vs incremental (signed, pts)", "", | |
| "| mode | mean | median | std |", "|---|---|---|---|"] | |
| for m in non_base: | |
| a = np.array(ref_err[m]) | |
| lines.append(f"| {m} | {a.mean():+.2f} | {np.median(a):+.2f} | {a.std():.2f} |") | |
| lines.append("") | |
| fb = np.array(fb_diff) | |
| lines += ["## Anchor bias: forward vs backward (systematic)", "", | |
| f"forward - backward (same frame): mean **{fb.mean():+.2f}** | " | |
| f"median {np.median(fb):+.2f} | std {fb.std():.2f} pts", "", | |
| "A large non-zero mean is direct evidence the model's completion " | |
| "estimate depends on whether it is anchored to the start or the goal.", ""] | |
| # ββ 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 Anchor Range)", "", | |
| "| rank | episode | max range | mean range | figure |", | |
| "|---|---|---|---|---|"] | |
| for rank, e in enumerate(worst, 1): | |
| base_after = data[e][BASELINE]["after_frames"] | |
| tgts = target_frames(base_after) | |
| 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)) | |
| for m in MODES: | |
| pay = data[e][m] | |
| xs = np.array(pay["after_frames"], dtype=float) | |
| ax.plot(xs, pay["scores_100"], color=MODE_COLORS[m], lw=1.5, | |
| marker=".", ms=3, label=m) | |
| for frac, taf in zip(FRACS, tgts): | |
| ax.axvline(taf, color="0.6", ls=":", lw=1) | |
| ax.text(taf, 97, frac, ha="center", fontsize=8, color="0.4") | |
| ax.set_xlabel("physical AFTER-frame index (original video frames)") | |
| 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 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() | |