File size: 3,699 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
"""Empirical per-token distribution of the CoT gate alpha, per cycle & epoch.

Reads the `<prefix>alpha_hist` blocks that eval_loss.py writes into a run's
eval_loss.json (50 bins over [0,1], summed over every eval token and rank) and
renders them as densities.
"""
import json
import os
import sys

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

BASE = "/lustre/fsw/portfolios/nemotron/users/hengyuf/HRM-Text"
OUT = f"{BASE}/plots"
RUN = sys.argv[1] if len(sys.argv) > 1 else "loop-cot-v2-L-4n"
WEIGHTS = sys.argv[2] if len(sys.argv) > 2 else "raw"   # raw | ema

CYCLE_COLORS = {1: "#2a78d6", 2: "#eb6834", 3: "#1baf7a", 0: "#6f6e66"}
INK, INK2, GRID = "#3a3a37", "#6f6e66", "#e5e4dd"


def main():
    d = json.load(open(f"{BASE}/checkpoints/HRM-Text/{RUN}/eval_loss.json"))
    epochs = [e for e in sorted(d) if f"{WEIGHTS}/alpha_hist" in d[e]]
    if not epochs:
        raise SystemExit(f"no {WEIGHTS}/alpha_hist in {RUN}/eval_loss.json — rerun eval_loss")

    fig, axes = plt.subplots(1, len(epochs), figsize=(5.6 * len(epochs), 4.4), dpi=150, squeeze=False)
    for ax, e in zip(axes[0], epochs):
        hists = d[e][f"{WEIGHTS}/alpha_hist"]
        stats = d[e].get(f"{WEIGHTS}/cot_stats", {})
        for c in sorted(hists, key=int):
            counts = np.asarray(hists[c], dtype=float)
            if counts.sum() == 0:
                continue
            nb = len(counts)
            edges = np.linspace(0, 1, nb + 1)
            centers = 0.5 * (edges[:-1] + edges[1:])
            density = counts / counts.sum() / (1.0 / nb)   # integrates to 1
            mean = stats.get(c, {}).get("alpha_mean")
            label = f"cycle {c}" + (f"  (mean {mean:.3f})" if mean is not None else "")
            ax.plot(centers, density, color=CYCLE_COLORS.get(int(c), INK2), linewidth=2, label=label, zorder=3)
            if mean is not None:
                ax.axvline(mean, color=CYCLE_COLORS.get(int(c), INK2), linewidth=1, linestyle=":", alpha=0.7)
        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("alpha (per token)", color=INK2, fontsize=10)
        ax.set_ylabel("density", color=INK2, fontsize=10)
        ax.set_xlim(0, 1)
        ax.set_title(f"epoch {e}", color=INK, fontsize=12, loc="left", pad=10)
        ax.legend(frameon=False, fontsize=9.5, labelcolor=INK, loc="upper right")

    fig.suptitle(f"{RUN} — per-token CoT gate distribution ({WEIGHTS} weights)",
                 color=INK, fontsize=13, x=0.01, ha="left")
    fig.tight_layout(rect=(0, 0, 1, 0.94))
    out = os.path.join(OUT, f"alpha_hist_{RUN}_{WEIGHTS}.png")
    fig.savefig(out, facecolor="white", bbox_inches="tight")
    print("wrote", out)

    # Text summary: mass in the tails and the median bin.
    for e in epochs:
        for c, counts in sorted(d[e][f"{WEIGHTS}/alpha_hist"].items(), key=lambda kv: int(kv[0])):
            counts = np.asarray(counts, dtype=float)
            if counts.sum() == 0:
                continue
            p = counts / counts.sum()
            centers = 0.5 * (np.linspace(0, 1, len(p) + 1)[:-1] + np.linspace(0, 1, len(p) + 1)[1:])
            cdf = np.cumsum(p)
            q = lambda t: centers[int(np.searchsorted(cdf, t))]
            print(f"ep{e} c{c}: p5={q(.05):.2f} median={q(.5):.2f} p95={q(.95):.2f} "
                  f"| mass<0.1={p[centers < 0.1].sum():.3f}  mass>0.9={p[centers > 0.9].sum():.3f}")


if __name__ == "__main__":
    main()