HRM-Text-checkpoints / code /slurm /plot_trajectories.py
fhyfhy's picture
Add code, tokenizer and README
23c39b5 verified
Raw History Blame Contribute Delete
6.48 kB
"""Training-trajectory figures: one PNG per benchmark + one for eval loss.
Series (fixed color order, validated palette):
HRM blue #2a78d6
loop_baseline orange #eb6834 (the UT run, per report naming)
transformer aqua #1baf7a
Reads per-epoch results from each run's benchmark_results.json /
eval_loss.json; runs with missing epochs just plot the epochs they have.
"""
import json
import os
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
BASE = "/lustre/fsw/portfolios/nemotron/users/hengyuf/HRM-Text/checkpoints/HRM-Text"
OUT = "/lustre/fsw/portfolios/nemotron/users/hengyuf/HRM-Text/plots"
SERIES = [ # (label, run_dir, color) — fixed assignment, never re-ordered
("HRM", "L-4n-repro", "#2a78d6"),
("loop_baseline", "ut-L-4n", "#eb6834"),
("transformer", "transformer-L-4n", "#1baf7a"),
("loop_cot_v2", "loop-cot-v2-L-4n", "#eda100"),
("hrm_fullbp", "hrm-fullbp-L-4n", "#8e44ad"),
("gated_loop", "gated-loop-L-4n", "#c0392b"),
]
# Superseded mis-wired-readout variants, kept out of the figures:
# ("loop_cot", "loop-cot-L-4n"), ("loop_cot_b1", "loop-cot-b1-L-4n"),
# ("loop_cot_a011", "loop-cot-a011-L-4n")
BENCHES = ["GSM8k", "MATH", "DROP", "MMLU", "ARC", "HellaSwag", "Winogrande", "BoolQ"]
METRIC_NAME = {"DROP": "F1"} # others: accuracy
INK, INK2, GRID = "#3a3a37", "#6f6e66", "#e5e4dd"
def style(ax, ylabel):
for s in ("top", "right"):
ax.spines[s].set_visible(False)
for s in ("left", "bottom"):
ax.spines[s].set_color(GRID)
ax.grid(axis="y", color=GRID, linewidth=0.8)
ax.set_axisbelow(True)
ax.tick_params(colors=INK2, labelsize=10)
ax.set_xlabel("epoch", color=INK2, fontsize=10)
ax.set_ylabel(ylabel, color=INK2, fontsize=10)
ax.set_xticks([1, 2, 3, 4])
ax.set_xlim(0.85, 4.55) # room for direct end labels
def load(run, fname):
p = os.path.join(BASE, run, fname)
return json.load(open(p)) if os.path.exists(p) else {}
def bench_value(d, epoch, bench):
v = d.get(str(epoch), {}).get(bench)
if not v:
return None
return (v["acc"] if v.get("acc") is not None else v["f1"]) * 100
def plot_one(title, ylabel, getter, outfile, series=None):
series = SERIES if series is None else series
fig, ax = plt.subplots(figsize=(7, 4.6), dpi=150)
for label, run, color in series:
pts = [(e, getter(run, e)) for e in (1, 2, 3, 4)]
pts = [(e, v) for e, v in pts if v is not None]
if not pts:
continue
xs, ys = zip(*pts)
ax.plot(xs, ys, color=color, linewidth=2, marker="o", markersize=6,
markeredgecolor="white", markeredgewidth=1.2, label=label, zorder=3)
ax.annotate(label, (xs[-1], ys[-1]), xytext=(8, 0), textcoords="offset points",
color=INK, fontsize=9.5, va="center")
style(ax, ylabel)
ax.set_title(title, color=INK, fontsize=13, loc="left", pad=12)
ax.legend(frameon=False, fontsize=9.5, labelcolor=INK, loc="best")
fig.tight_layout()
fig.savefig(outfile, facecolor="white", bbox_inches="tight")
plt.close(fig)
print("wrote", outfile)
def main():
os.makedirs(OUT, exist_ok=True)
bench_data = {run: load(run, "benchmark_results.json") for _, run, _ in SERIES}
loss_data = {run: load(run, "eval_loss.json") for _, run, _ in SERIES}
for b in BENCHES:
metric = METRIC_NAME.get(b, "accuracy")
plot_one(f"{b} ({metric}, %)", f"{metric} (%)",
lambda run, e, b=b: bench_value(bench_data[run], e, b),
os.path.join(OUT, f"traj_{b}.png"))
plot_one("Held-out eval loss (EMA weights)", "CE loss (nats/token)",
lambda run, e: (loss_data[run].get(str(e)) or {}).get("ema/loss"),
os.path.join(OUT, "traj_eval_loss.png"))
def plot_panel(outfile=os.path.join(OUT, "traj_all_benchmarks.png"), series=None, subtitle=""):
"""2x4 small-multiples panel of all benchmarks, one shared legend."""
series = SERIES if series is None else series
bench_data = {run: load(run, "benchmark_results.json") for _, run, _ in series}
fig, axes = plt.subplots(2, 4, figsize=(16, 7.6), dpi=150)
for ax, b in zip(axes.flat, BENCHES):
for label, run, color in series:
pts = [(e, bench_value(bench_data[run], e, b)) for e in (1, 2, 3, 4)]
pts = [(e, v) for e, v in pts if v is not None]
if not pts:
continue
xs, ys = zip(*pts)
ax.plot(xs, ys, color=color, linewidth=2, marker="o", markersize=5,
markeredgecolor="white", markeredgewidth=1.0, label=label, zorder=3)
style(ax, "")
ax.set_xlim(0.8, 4.2)
ax.set_xlabel("")
metric = METRIC_NAME.get(b, "acc")
ax.set_title(f"{b} ({metric} %)", color=INK, fontsize=11.5, loc="left", pad=8)
for ax in axes[1]:
ax.set_xlabel("epoch", color=INK2, fontsize=10)
handles, labels = axes[0][0].get_legend_handles_labels()
fig.legend(handles, labels, frameon=False, fontsize=11, labelcolor=INK,
loc="lower center", ncol=min(len(labels), 4), bbox_to_anchor=(0.5, -0.02))
fig.suptitle("Benchmark trajectories — same params (694.7M), same data, same hyperparameters" + subtitle,
color=INK, fontsize=14, x=0.01, ha="left")
# Reserve enough bottom margin for the (wrapped) legend so it never
# overlaps the bottom row's x-axis labels.
fig.tight_layout(rect=(0, 0.04 + 0.032 * ((len(labels) + 3) // 4), 1, 0.96))
fig.savefig(outfile, facecolor="white", bbox_inches="tight")
plt.close(fig)
print("wrote", outfile)
def plot_recurrent_only():
"""Same figures without `transformer`, so the y-axes zoom in on the
recurrent architectures that are actually competing with each other."""
series = [s for s in SERIES if s[1] != "transformer-L-4n"]
loss_data = {run: load(run, "eval_loss.json") for _, run, _ in series}
plot_panel(os.path.join(OUT, "traj_all_benchmarks_recurrent.png"), series=series,
subtitle=" (recurrent architectures only)")
plot_one("Held-out eval loss (EMA weights) — recurrent architectures only",
"CE loss (nats/token)",
lambda run, e: (loss_data[run].get(str(e)) or {}).get("ema/loss"),
os.path.join(OUT, "traj_eval_loss_recurrent.png"), series=series)
if __name__ == "__main__":
main()
plot_panel()
plot_recurrent_only()