File size: 6,482 Bytes
23c39b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
"""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()