| |
| """Extract per-step training curves for the jupiter-tasktrove-dapo arms (D0-D4) and plot them. |
| |
| Adapted from ``experiments/complete/tasktrove-hparam-optimization/artifacts/plot_reward_curves.py``. |
| Differences: Jupiter only (these arms never ran on Iris), no HF gap filler, and the DAPO-specific |
| metrics (dynamic-sampling discard rate, Section 3.4 overlong incidence/penalty, shaped reward) get |
| their own panels. |
| |
| Source |
| ------ |
| Slurm ``.out`` logs under ``/e/data1/datasets/playground/ot-baf/jtd-d<N>*/logs/``, reached over ssh. |
| Every log carries ``WANDB_MIRROR kind=train step=N metrics={...}`` lines (Python repr, single |
| quotes). One extractor runs on Jupiter and returns JSON; it ships only files whose mtime/size |
| moved since the cached copy under ``curves/cache/``. |
| |
| Lineages |
| -------- |
| An arm's chains resume from a shared checkpoint bank (``jtd-<arm>/jtd-<arm>/checkpoints``), so steps |
| from several experiment roots (``jtd-d0_8``, ``jtd-d0_9``, ...) form ONE series. Chains that were |
| restarted from scratch (retired submissions in TRACKER.md) overlap those step numbers and must not |
| be merged in. ``LINEAGE`` names the roots of each arm's current series; every other root with train |
| lines is plotted as a faint dashed "retired" line on the per-arm panel and excluded from the |
| combined comparisons. Within a lineage, the most recently written log wins a step (a resume |
| re-does the in-flight step). |
| |
| Reading the plots |
| ----------------- |
| * ``reward/avg_pass_at_8`` on D1, D2 and D4 is measured AFTER dynamic-sampling's filter, so it is |
| high by construction (uninformative all-pass / all-fail groups are discarded). Compare D0/D3 to |
| D1/D2/D4 on ``reward/avg_raw_reward`` and on the never-filtered diagnostics, not on pass@8. |
| * D4 trains on the Harbor ``threshold`` shaped reward; its raw reward is the continuous verifier |
| pass-ratio, not the binary verdict the other arms use. |
| * Compare at matched STEPS. D0 and D3 pay no resampling cost and out-run D1/D2/D4 in wall-clock. |
| |
| Usage |
| ----- |
| python plot_dapo_curves.py # extract (cached) + plot into ./curves |
| python plot_dapo_curves.py --from-csv curves/dapo_curves.csv |
| python plot_dapo_curves.py --refresh # re-ship every log |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import ast |
| import csv |
| import json |
| import os |
| import re |
| import shlex |
| import subprocess |
| import sys |
| from collections import defaultdict |
|
|
| BASE = "/e/data1/datasets/playground/ot-baf" |
| SSH_HOST = "Jupiter" |
| ARMS = ["d0", "d1", "d2", "d3", "d4", "d5"] |
|
|
| LABELS = { |
| "d0": "D0 control: GRPO, eps 0.2/0.2, no dynamic sampling", |
| "d1": "D1 DAPO core: clip-higher 0.4 + dynamic sampling", |
| "d2": "D2 full DAPO: D1 + Section 3.4 overlong (l_max 12288 / l_cache 3072)", |
| "d3": "D3 Section 3.4 only: D0 + overlong (l_max 12288 / l_cache 3072)", |
| "d4": "D4 DAPO core + threshold partial credit (1.0 / 0.3), informative_on=shaped", |
| "d5": "D5 GSPO: D0 with policy_loss_type=gspo, eps 3e-4/4e-4, loss_reduction=sequence_mean", |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| LINEAGE = { |
| "d0": ["jtd-d0_7", "jtd-d0_8", "jtd-d0_9"], |
| "d1": ["jtd-d1_9", "jtd-d1_10", "jtd-d1_11", "jtd-d1_12"], |
| "d2": ["jtd-d2"], |
| "d3": ["jtd-d3_3", "jtd-d3_4"], |
| "d4": ["jtd-d4", "jtd-d4_2", "jtd-d4_3", "jtd-d4_4"], |
| "d5": ["jtd-d5"], |
| } |
|
|
| METRICS = [ |
| ("reward", "reward/avg_raw_reward"), |
| ("pass_at_8", "reward/avg_pass_at_8"), |
| ("entropy", "policy/policy_entropy"), |
| ("grad_norm", "policy/raw_grad_norm"), |
| ("adv_abs", "loss/avg_raw_advantages_abs"), |
| ("tokens", "generate/avg_num_tokens"), |
| ("discard_rate", "async/dynamic_sampling/discarded_rate"), |
| ("overlong_incidence", "generate/reward_shaping/overlong_incidence"), |
| ("overlong_penalty", "generate/reward_shaping/overlong_penalty_mean"), |
| ("shaped_reward", "generate/reward_shaping/shaped_reward_mean"), |
| ("response_tokens", "generate/reward_shaping/response_tokens_mean"), |
| ("clip_high", "policy/ppo_clip_ratio_high"), |
| ("clip_low", "policy/ppo_clip_ratio_low"), |
| ] |
| COLS = [c for c, _ in METRICS] |
| CSV_COLS = ["arm", "root", "job", "mtime", "step", *COLS] |
|
|
| ROOT_RE = re.compile(r"^jtd-(d\d)(?:_\d+)?$") |
| TRAIN_LINE_RE = re.compile(r"step=(\d+) metrics=(\{.*\})") |
| ANSI_RE = re.compile(r"\x1b\[[0-9;]*m") |
|
|
| |
| |
| EXTRACTOR = r''' |
| import glob, json, os, sys |
| base, known = sys.argv[1], json.loads(sys.argv[2]) |
| out = {} |
| for path in sorted(glob.glob(os.path.join(base, "jtd-d[0-9]*", "logs", "*.out"))): |
| if "__dryrun" in path: |
| continue |
| st = os.stat(path) |
| if known.get(path) == [int(st.st_mtime), st.st_size]: |
| continue |
| lines = [] |
| with open(path, "rb") as fh: |
| for raw in fh: |
| if b"WANDB_MIRROR kind=train" in raw: |
| lines.append(raw.decode("utf-8", errors="replace").rstrip("\n")) |
| if lines: |
| out[path] = {"mtime": int(st.st_mtime), "size": st.st_size, "lines": lines} |
| json.dump(out, sys.stdout) |
| ''' |
|
|
|
|
| def parse_line(line: str) -> tuple[int, dict] | None: |
| m = TRAIN_LINE_RE.search(ANSI_RE.sub("", line)) |
| if not m: |
| return None |
| try: |
| d = json.loads(m.group(2)) |
| except ValueError: |
| try: |
| d = ast.literal_eval(m.group(2)) |
| except (ValueError, SyntaxError): |
| return None |
| return int(m.group(1)), d |
|
|
|
|
| def extract(cache_path: str, refresh: bool) -> dict: |
| """Return {path: {mtime, size, rows: {step: {col: val}}}} for every Jupiter log with train lines.""" |
| cache = {} |
| if os.path.exists(cache_path) and not refresh: |
| with open(cache_path) as f: |
| cache = json.load(f) |
| known = {p: [v["mtime"], v["size"]] for p, v in cache.items()} |
| cmd = f"python3 - {shlex.quote(BASE)} {shlex.quote(json.dumps(known))}" |
| proc = subprocess.run(["ssh", SSH_HOST, cmd], input=EXTRACTOR, capture_output=True, text=True, |
| check=True) |
| fresh = json.loads(proc.stdout) |
| for path, rec in fresh.items(): |
| rows: dict[str, dict] = {} |
| for line in rec["lines"]: |
| parsed = parse_line(line) |
| if parsed is None: |
| continue |
| step, d = parsed |
| rows[str(step)] = {col: d.get(key) for col, key in METRICS} |
| cache[path] = {"mtime": rec["mtime"], "size": rec["size"], "rows": rows} |
| os.makedirs(os.path.dirname(cache_path), exist_ok=True) |
| with open(cache_path, "w") as f: |
| json.dump(cache, f) |
| print(f" {len(fresh)} log(s) re-shipped, {len(cache)} in cache") |
| return cache |
|
|
|
|
| def rows_from_cache(cache: dict) -> list[dict]: |
| out = [] |
| for path, rec in cache.items(): |
| root = os.path.basename(os.path.dirname(os.path.dirname(path))) |
| m = ROOT_RE.match(root) |
| if not m: |
| continue |
| job = os.path.basename(path).rsplit("_", 1)[-1].removesuffix(".out") |
| for step, vals in rec["rows"].items(): |
| out.append({"arm": m.group(1), "root": root, "job": job, "mtime": rec["mtime"], |
| "step": int(step), **vals}) |
| return out |
|
|
|
|
| def write_csv(path: str, rows: list[dict]) -> None: |
| with open(path, "w", newline="") as f: |
| w = csv.DictWriter(f, fieldnames=CSV_COLS) |
| w.writeheader() |
| for r in sorted(rows, key=lambda r: (r["arm"], r["root"], r["step"], r["mtime"])): |
| w.writerow(r) |
|
|
|
|
| def read_csv(path: str) -> list[dict]: |
| with open(path) as f: |
| rows = [] |
| for r in csv.DictReader(f): |
| r["mtime"] = int(r["mtime"]) |
| r["step"] = int(r["step"]) |
| for c in COLS: |
| r[c] = float(r[c]) if r[c] not in ("", "None") else None |
| rows.append(r) |
| return rows |
|
|
|
|
| def series(rows: list[dict]) -> tuple[dict, dict]: |
| """Split rows into (current, retired): arm -> {step: row}. Latest mtime wins within a lineage; |
| retired roots are keyed as "<arm>/<root>" so each retired chain keeps its own line.""" |
| current: dict[str, dict[int, dict]] = defaultdict(dict) |
| retired: dict[str, dict[int, dict]] = defaultdict(dict) |
| for r in sorted(rows, key=lambda r: r["mtime"]): |
| if r["root"] in LINEAGE.get(r["arm"], []): |
| current[r["arm"]][r["step"]] = r |
| else: |
| retired[f"{r['arm']}/{r['root']}"][r["step"]] = r |
| return current, retired |
|
|
|
|
| GAP_BREAK = 5 |
|
|
|
|
| def segments(pts: list[tuple], max_gap: int = GAP_BREAK) -> list[list[tuple]]: |
| runs: list[list[tuple]] = [] |
| for pt in pts: |
| if runs and pt[0] - runs[-1][-1][0] <= max_gap: |
| runs[-1].append(pt) |
| else: |
| runs.append([pt]) |
| return runs |
|
|
|
|
| def ema(vals: list[float], window: int = 5) -> list[float]: |
| out = [] |
| for i in range(len(vals)): |
| lo = max(0, i - window + 1) |
| out.append(sum(vals[lo:i + 1]) / len(vals[lo:i + 1])) |
| return out |
|
|
|
|
| def points(s: dict[int, dict], col: str) -> list[tuple[int, float]]: |
| return [(step, r[col]) for step, r in sorted(s.items()) if r.get(col) is not None] |
|
|
|
|
| ARM_COLORS = {"d0": "black", "d1": "red", "d2": "blue", "d3": "green", "d4": "fuchsia", "d5": "darkorange"} |
|
|
| COMBINED = [ |
| ("reward", "reward / avg_raw_reward", "raw reward (D4: continuous pass-ratio, others: binary)"), |
| ("pass_at_8", "reward / avg_pass_at_8", "pass@8 (POST-FILTER on D1/D2/D4 -- high by construction)"), |
| ("entropy", "policy / policy_entropy", "policy entropy"), |
| ("grad_norm", "policy / raw_grad_norm", "raw grad norm"), |
| ("tokens", "generate / avg_num_tokens", "mean generated tokens per trajectory"), |
| ("discard_rate", "dynamic_sampling / discarded_rate", "dynamic-sampling discard rate (D1/D2/D4 only)"), |
| ("overlong_incidence", "reward_shaping / overlong_incidence", "Section 3.4 overlong incidence (D2/D3)"), |
| ] |
|
|
|
|
| def _line(ax, pts, *, color, label, smooth, ls="-", alpha=1.0, lw=2.0, marker=None): |
| first = True |
| for run in segments(pts): |
| xs = [x for x, _ in run] |
| ys = [y for _, y in run] |
| ax.plot(xs, ema(ys) if smooth else ys, color=color, ls=ls, lw=lw, alpha=alpha, |
| marker=marker, ms=3, label=label if first else None) |
| first = False |
|
|
|
|
| def plot_combined(plt, current: dict, out_dir: str) -> None: |
| for col, ylabel, title in COMBINED: |
| fig, ax = plt.subplots(figsize=(12, 5.6)) |
| any_pts = False |
| for arm in ARMS: |
| pts = points(current.get(arm, {}), col) |
| if len(pts) < 2: |
| continue |
| any_pts = True |
| _line(ax, pts, color=ARM_COLORS[arm], label=f"{arm.upper()} (n={len(pts)})", smooth=False, |
| alpha=0.35, lw=1.0, marker="o") |
| _line(ax, pts, color=ARM_COLORS[arm], label=None, smooth=True, lw=2.2) |
| if not any_pts: |
| plt.close(fig) |
| continue |
| ax.set_xlabel("training step") |
| ax.set_ylabel(ylabel) |
| ax.set_title(f"jupiter-tasktrove-dapo -- {title}; faint = raw, bold = trailing-5 EMA") |
| ax.grid(True, alpha=0.3) |
| ax.legend(fontsize=9) |
| fig.tight_layout() |
| fig.savefig(os.path.join(out_dir, f"combined_{col}.png"), dpi=130) |
| plt.close(fig) |
|
|
|
|
| PANEL = [ |
| ("reward", "raw reward"), |
| ("pass_at_8", "pass@8"), |
| ("entropy", "entropy"), |
| ("grad_norm", "grad norm"), |
| ("tokens", "gen tokens"), |
| ("discard_rate", "discard rate"), |
| ("overlong_incidence", "overlong incidence"), |
| ("overlong_penalty", "overlong penalty"), |
| ("shaped_reward", "shaped reward"), |
| ] |
|
|
|
|
| def plot_arm(plt, arm: str, cur: dict[int, dict], retired: dict[str, dict[int, dict]], out_dir: str) -> None: |
| panels = [(col, name) for col, name in PANEL if len(points(cur, col)) >= 1 |
| or any(points(s, col) for s in retired.values())] |
| if not panels: |
| return |
| ncol = 3 |
| nrow = (len(panels) + ncol - 1) // ncol |
| fig, axes = plt.subplots(nrow, ncol, figsize=(15, 3.6 * nrow), squeeze=False) |
| for ax, (col, name) in zip(axes.flat, panels): |
| for key, s in sorted(retired.items()): |
| pts = points(s, col) |
| if pts: |
| _line(ax, pts, color="0.6", ls="--", lw=1.2, alpha=0.8, smooth=False, |
| label=f"retired {key.split('/', 1)[1]}") |
| pts = points(cur, col) |
| if pts: |
| _line(ax, pts, color=ARM_COLORS[arm], alpha=0.35, lw=1.0, marker="o", smooth=False, label="raw") |
| _line(ax, pts, color=ARM_COLORS[arm], lw=2.2, smooth=True, label="EMA-5") |
| ax.set_title(name, fontsize=10) |
| ax.grid(True, alpha=0.3) |
| ax.legend(fontsize=7) |
| for ax in list(axes.flat)[len(panels):]: |
| ax.axis("off") |
| steps = sorted(cur) |
| span = f"steps {steps[0]}..{steps[-1]} (n={len(steps)})" if steps else "no current-series steps" |
| fig.suptitle(f"{LABELS[arm]}\n{span}; roots {', '.join(LINEAGE[arm])}", fontsize=11) |
| fig.tight_layout() |
| fig.savefig(os.path.join(out_dir, f"arm_{arm}.png"), dpi=130) |
| plt.close(fig) |
| print(f" {arm}: {span}; retired chains: {len(retired)}") |
|
|
|
|
| def plot(rows: list[dict], out_dir: str) -> None: |
| import matplotlib |
|
|
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
|
|
| os.makedirs(out_dir, exist_ok=True) |
| current, retired = series(rows) |
| plot_combined(plt, current, out_dir) |
| for arm in ARMS: |
| ret = {k: v for k, v in retired.items() if k.startswith(f"{arm}/")} |
| plot_arm(plt, arm, current.get(arm, {}), ret, out_dir) |
| print(f"wrote plots to {out_dir}") |
|
|
|
|
| def main() -> None: |
| here = os.path.dirname(os.path.abspath(__file__)) |
| p = argparse.ArgumentParser(description=__doc__.split("\n")[0]) |
| p.add_argument("--out-dir", default=os.path.join(here, "curves")) |
| p.add_argument("--from-csv", help="re-plot from a CSV written earlier; no ssh") |
| p.add_argument("--refresh", action="store_true", help="ignore the mtime/size cache and re-ship every log") |
| args = p.parse_args() |
|
|
| os.makedirs(args.out_dir, exist_ok=True) |
| csv_path = os.path.join(args.out_dir, "dapo_curves.csv") |
| if args.from_csv: |
| rows = read_csv(args.from_csv) |
| else: |
| print(f"extracting from {SSH_HOST}:{BASE} ...") |
| cache = extract(os.path.join(args.out_dir, "cache", "jupiter.json"), args.refresh) |
| rows = rows_from_cache(cache) |
| write_csv(csv_path, rows) |
| print(f" wrote {csv_path} ({len(rows)} rows)") |
| plot(rows, args.out_dir) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|