stgfn-repro-code / analyze_scaled.py
barnabee's picture
Upload folder using huggingface_hub
a76f68a verified
Raw
History Blame Contribute Delete
4.08 kB
"""Aggregate the scaled Hugging Face GPU Job results (downloaded from the bucket)."""
from __future__ import annotations
import argparse
import glob
import json
import os
from collections import defaultdict
import numpy as np
LABEL = {"stgfn": "ST-GFN (Ours)", "tb": "TB", "fm": "FM", "subtb": "SubTB", "db": "DB",
"eflownet": "EFlowNet", "stochastic_gfn": "Stochastic-GFN", "tb_rnd": "TB+RND",
"tb_novelty": "TB+Novelty", "tb_icm": "TB+ICM", "tb_cv": "TB+ControlVar"}
ORDER = ["stgfn", "tb", "fm", "subtb", "db", "eflownet", "stochastic_gfn",
"tb_rnd", "tb_novelty", "tb_icm", "tb_cv"]
METRICS = {
"hypergrid": [("modes_found", "Modes (of 256)", True),
("coverage_pct", "Cov.%", True),
("l1_to_target", "L1 to P*", False)],
"singlecell_proxy": [("target_corr", "Corr.", True),
("l1_error", "L1", False),
("mean_reward", "Mean R", True)],
}
def welch_p(a, b):
from math import erfc, sqrt
a, b = np.array(a, float), np.array(b, float)
if len(a) < 2 or len(b) < 2:
return None
se = np.sqrt(a.var(ddof=1) / len(a) + b.var(ddof=1) / len(b))
if se == 0:
return None
return float(erfc(abs((a.mean() - b.mean()) / se) / sqrt(2)))
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--dir", default="../outputs/scaled")
ap.add_argument("--save", default="../outputs/summary_scaled.json")
args = ap.parse_args()
data = defaultdict(lambda: defaultdict(list))
for p in glob.glob(os.path.join(args.dir, "**", "*.json"), recursive=True):
if os.path.basename(p).startswith("summary"):
continue
try:
with open(p) as f:
r = json.load(f)
if "env" in r and "method" in r:
data[r["env"]][r["method"]].append(r)
except (json.JSONDecodeError, KeyError):
continue
summary = {}
for env, metrics in METRICS.items():
if env not in data:
continue
cfg = data[env][list(data[env])[0]][0]["config"]
scale = (f"grid {cfg['grid_size']}x{cfg['grid_size']}, period {cfg['period']}"
if env == "hypergrid" else
f"{cfg['n_genes']} choose {cfg['k_genes']}")
print(f"\n{'='*88}\n{env.upper()} — SCALED on HF GPU Job ({scale}), "
f"{cfg['iters']} iters, mean ± 95% CI\n{'='*88}")
print(f"{'Method':22s} {'n':>2s} " + " ".join(f"{n:>18s}" for _, n, _ in metrics))
summary[env] = {"scale": scale, "iters": cfg["iters"], "methods": {}}
base = {k: [r["final"].get(k) for r in data[env].get("stgfn", [])]
for k, _, _ in metrics}
for m in ORDER:
if m not in data[env]:
continue
runs, cells, entry = data[env][m], [], {}
for key, _, _ in metrics:
vals = [r["final"].get(key) for r in runs if r["final"].get(key) is not None]
if not vals:
cells.append(f"{'—':>18s}")
continue
mu = float(np.mean(vals))
ci = float(1.96 * np.std(vals, ddof=1) / np.sqrt(len(vals))) if len(vals) > 1 else 0.0
star = ""
if m != "stgfn":
bv = [x for x in base.get(key, []) if x is not None]
if len(bv) > 1 and len(vals) > 1:
p = welch_p(bv, vals)
entry[key + "_p_vs_stgfn"] = p
if p is not None and p < 0.05:
star = "*"
entry[key] = {"mean": mu, "ci95": ci, "values": vals}
cells.append(f"{mu:13.3f}±{ci:4.3f}{star}"[:18].rjust(18))
summary[env]["methods"][m] = entry
print(f"{LABEL.get(m,m):22s} {len(runs):2d} " + " ".join(cells))
print(" * = p<0.05 (Welch) vs ST-GFN")
with open(args.save, "w") as f:
json.dump(summary, f, indent=2)
print(f"\nwrote {args.save}")