Spaces:
Running
Running
Download analyze.py from UncleanCode/denseam-hp-transfer: direct link, hf CLI and curl.
- Browser
- Download file 6.18 kB
-
https://huggingface.co/spaces/UncleanCode/denseam-hp-transfer/resolve/main/analyze.py
- Command line
-
hf download hf://spaces/UncleanCode/denseam-hp-transfer/analyze.py
-
curl -L -o analyze.py https://huggingface.co/spaces/UncleanCode/denseam-hp-transfer/resolve/main/analyze.py
6.18 kB
| """Aggregate the grid, test the transfer claim, and draw Figure 4 style panels. | |
| Transfer metrics | |
| ---------------- | |
| argmin spread : (largest / smallest) per-scale optimal eta_0, over the six scales. | |
| single-LR regret : min over eta_0 of max over scales of L_j(eta_0) / min_eta L_j(eta_0). | |
| A value near 1 means one learning rate is essentially optimal at every scale, | |
| which is the operational content of "learning rate transfer". | |
| stability edge : largest eta_0 whose median loss is still finite. | |
| """ | |
| import json | |
| import math | |
| import os | |
| import sys | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| LABEL = {1: "j=1 N=784 K=1568", 2: "j=2 N=196 K=392", 3: "j=3 N=100 K=200", | |
| 4: "j=4 N=49 K=98", 5: "j=5 N=36 K=72", 6: "j=6 N=25 K=50"} | |
| COLOR = {1: "#1f77b4", 2: "#ff7f0e", 3: "#2ca02c", 4: "#d62728", 5: "#9467bd", 6: "#8c564b"} | |
| ORDER = [("relu", "sgd"), ("relu", "adam"), ("softmax", "sgd"), ("softmax", "adam")] | |
| def load(paths): | |
| rows = [] | |
| for p in paths: | |
| if not os.path.exists(p): | |
| continue | |
| with open(p) as fh: | |
| for line in fh: | |
| if line.strip(): | |
| rows.append(json.loads(line)) | |
| return rows | |
| def agg(rows, act, opt, metric): | |
| buckets = {} | |
| for r in rows: | |
| if r["act"] == act and r["opt"] == opt: | |
| buckets.setdefault((r["j"], r["eta0"]), []).append(r[metric]) | |
| series = {} | |
| for (j, lr), vals in buckets.items(): | |
| v = np.array([x for x in vals if not math.isnan(x)], float) | |
| series.setdefault(j, {"lr": [], "med": [], "lo": [], "hi": [], "n": []}) | |
| series[j]["lr"].append(lr) | |
| series[j]["med"].append(float(np.median(v)) if len(v) else float("nan")) | |
| series[j]["lo"].append(float(v.min()) if len(v) else float("nan")) | |
| series[j]["hi"].append(float(v.max()) if len(v) else float("nan")) | |
| series[j]["n"].append(len(v)) | |
| for j in series: | |
| o = np.argsort(series[j]["lr"]) | |
| for k in ("lr", "med", "lo", "hi", "n"): | |
| series[j][k] = list(np.array(series[j][k], dtype=float)[o]) | |
| return series | |
| def best_lr(series, j): | |
| lrs, med = np.array(series[j]["lr"]), np.array(series[j]["med"]) | |
| ok = np.isfinite(med) | |
| if not ok.any(): | |
| return None, None | |
| i = int(np.argmin(np.where(ok, med, np.inf))) | |
| return float(lrs[i]), float(med[i]) | |
| def stable_edge(series, j): | |
| lrs, med = np.array(series[j]["lr"]), np.array(series[j]["med"]) | |
| ok = np.isfinite(med) | |
| return float(lrs[ok].max()) if ok.any() else None | |
| def regret(series): | |
| """best single eta_0: minimise the worst per-scale ratio to that scale's optimum.""" | |
| cand = sorted({lr for j in series for lr in series[j]["lr"]}) | |
| per_scale_min = {j: min([m for m in series[j]["med"] if np.isfinite(m)] or [np.nan]) | |
| for j in series} | |
| best = (None, np.inf, None) | |
| for lr in cand: | |
| worst, worst_j = 0.0, None | |
| for j in series: | |
| idx = series[j]["lr"].index(lr) if lr in series[j]["lr"] else None | |
| if idx is None: | |
| worst = np.inf | |
| break | |
| m = series[j]["med"][idx] | |
| r = np.inf if not np.isfinite(m) else m / per_scale_min[j] | |
| if r > worst: | |
| worst, worst_j = r, j | |
| if worst < best[1]: | |
| best = (lr, worst, worst_j) | |
| return best | |
| def panel(ax, series, title, ylabel=False): | |
| for j in sorted(series): | |
| s = series[j] | |
| ax.plot(s["lr"], s["med"], marker="o", ms=2.8, lw=1.3, | |
| color=COLOR[j], label=LABEL[j]) | |
| b, v = best_lr(series, j) | |
| if b is not None: | |
| ax.plot([b], [v], marker="*", ms=10, color=COLOR[j], | |
| markeredgecolor="k", markeredgewidth=0.4, zorder=5) | |
| ax.set_xscale("log") | |
| ax.set_yscale("log") | |
| ax.set_title(title, fontsize=9) | |
| ax.grid(True, which="both", alpha=0.22, lw=0.5) | |
| if ylabel: | |
| ax.set_ylabel("final train MSE", fontsize=8) | |
| ax.set_xlabel(r"$\eta_0$", fontsize=9) | |
| ax.tick_params(labelsize=7) | |
| def main(): | |
| paths = sys.argv[1:] or ["results/grid_relu.jsonl", "results/grid_softmax.jsonl"] | |
| rows = load(paths) | |
| print(f"{len(rows)} runs loaded") | |
| summary = {} | |
| fig, axes = plt.subplots(2, 2, figsize=(8.2, 6.2)) | |
| for k, (act, opt) in enumerate(ORDER): | |
| ax = axes[k // 2][k % 2] | |
| ser = agg(rows, act, opt, "final_train_mse") | |
| if not ser: | |
| ax.set_axis_off() | |
| continue | |
| panel(ax, ser, f"{act.capitalize()} p=1 - {opt.upper()}", ylabel=(k % 2 == 0)) | |
| bests = {j: dict(zip(("best_eta0", "best_mse"), best_lr(ser, j)), | |
| stable_edge=stable_edge(ser, j)) for j in sorted(ser)} | |
| vals = [v["best_eta0"] for v in bests.values() if v["best_eta0"]] | |
| lr_star, worst, worst_j = regret(ser) | |
| summary[f"{act}_{opt}"] = dict( | |
| per_scale={str(j): v for j, v in bests.items()}, | |
| best_eta0_min=min(vals) if vals else None, | |
| best_eta0_max=max(vals) if vals else None, | |
| argmin_spread=max(vals) / min(vals) if vals else None, | |
| single_lr=lr_star, single_lr_worst_regret=worst, | |
| single_lr_worst_scale=worst_j) | |
| print(f"\n{act} {opt}") | |
| for j in sorted(bests): | |
| print(f" j={j} N={int(ser[j]['lr'][0]*0)+[784,196,100,49,36,25][j-1]:4d} " | |
| f"best eta0={bests[j]['best_eta0']:<8g} mse={bests[j]['best_mse']:.4g} " | |
| f"stable_edge={bests[j]['stable_edge']:g}") | |
| print(f" argmin spread {max(vals)/min(vals):.1f}x " | |
| f"single eta0={lr_star:g} with worst-case regret {worst:.2f}x (scale j={worst_j})") | |
| handles, labels = axes[0][0].get_legend_handles_labels() | |
| fig.legend(handles, labels, loc="lower center", ncol=6, fontsize=7, frameon=False) | |
| fig.tight_layout(rect=(0, 0.06, 1, 1)) | |
| fig.savefig("results/figure4_repro.png", dpi=200) | |
| with open("results/analysis.json", "w") as fh: | |
| json.dump(summary, fh, indent=2) | |
| print("\nwrote results/figure4_repro.png and results/analysis.json") | |
| if __name__ == "__main__": | |
| main() | |