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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Multi-seed + TOST equivalence analysis for the representation A/B.
|
| 3 |
+
|
| 4 |
+
Responds to the review request for ">=5 seeds, TOST/equivalence analysis instead of
|
| 5 |
+
a 'bounded null'" on the trained OpenPOM-vs-Morgan comparison.
|
| 6 |
+
|
| 7 |
+
Consumes the per-seed frozen-eval JSONs produced by the multi-seed GPU job
|
| 8 |
+
(``frozen_eval_{arm}_seed{seed}.json``), pairs the two arms by seed, and runs a
|
| 9 |
+
TOST (two one-sided tests) equivalence analysis on the prospective family-profile
|
| 10 |
+
cosine and on val_total. Where the arms are statistically indistinguishable, TOST
|
| 11 |
+
establishes *equivalence within a margin* (delta) rather than merely failing to
|
| 12 |
+
reject a difference.
|
| 13 |
+
|
| 14 |
+
Inputs: a directory of frozen-eval JSONs + a seeds list. The script auto-discovers
|
| 15 |
+
``frozen_eval_{arm}_seed{seed}.json`` for arms morgan/openpom_256.
|
| 16 |
+
Outputs: artifacts/multiseed_tost_analysis.json + human summary. Exit 0 always.
|
| 17 |
+
|
| 18 |
+
Stats: paired per-seed differences; TOST via two one-sided Welch t CIs (equivalently,
|
| 19 |
+
a (1-2*alpha) CI fully inside [-delta, +delta]); plus mean +/- sd across seeds.
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import glob
|
| 25 |
+
import json
|
| 26 |
+
import math
|
| 27 |
+
import sys
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
from scipy import stats
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _load_eval(path: str) -> dict:
|
| 35 |
+
return json.loads(Path(path).read_text())
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _metric(eval_json: dict, key: str):
|
| 39 |
+
"""Pull a scalar metric out of a frozen-eval JSON."""
|
| 40 |
+
if key == "val_total":
|
| 41 |
+
return eval_json.get("final_val_total")
|
| 42 |
+
if key == "prospective_cosine":
|
| 43 |
+
pf = eval_json.get("prospective_formulas", {})
|
| 44 |
+
return pf.get("mean_family_profile_cosine")
|
| 45 |
+
if key == "prospective_cosine_novelty":
|
| 46 |
+
pf = eval_json.get("prospective_formulas", {})
|
| 47 |
+
return pf.get("openpom_overlap", {}).get("novelty_weighted_mean_cosine")
|
| 48 |
+
if key == "triplet_accuracy":
|
| 49 |
+
return eval_json.get("substitution_triplets", {}).get("accuracy")
|
| 50 |
+
return None
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def tost_paired(diffs: np.ndarray, delta: float, alpha: float = 0.05) -> dict:
|
| 54 |
+
"""Two one-sided tests on paired per-seed differences."""
|
| 55 |
+
n = len(diffs)
|
| 56 |
+
if n < 2:
|
| 57 |
+
return {"error": "need >=2 paired seeds", "n": n}
|
| 58 |
+
mean = float(np.mean(diffs))
|
| 59 |
+
sd = float(np.std(diffs, ddof=1))
|
| 60 |
+
se = sd / math.sqrt(n)
|
| 61 |
+
dfree = n - 1
|
| 62 |
+
# TOST: test H0a: mean <= -delta vs H1a: mean > -delta (lower)
|
| 63 |
+
# test H0b: mean >= +delta vs H1b: mean < +delta (upper)
|
| 64 |
+
t_lower = (mean + delta) / se if se > 0 else math.inf
|
| 65 |
+
t_upper = (delta - mean) / se if se > 0 else math.inf
|
| 66 |
+
p_lower = 1 - stats.t.cdf(t_lower, dfree)
|
| 67 |
+
p_upper = 1 - stats.t.cdf(t_upper, dfree)
|
| 68 |
+
p_tost = max(p_lower, p_upper)
|
| 69 |
+
# (1-2*alpha) CI; equivalence iff fully inside [-delta, +delta]
|
| 70 |
+
ci_half = stats.t.ppf(1 - alpha, dfree) * se
|
| 71 |
+
ci_lo, ci_hi = mean - ci_half, mean + ci_half
|
| 72 |
+
equivalent = (p_tost < alpha) and (ci_lo > -delta) and (ci_hi < delta)
|
| 73 |
+
return {
|
| 74 |
+
"n_seeds": n,
|
| 75 |
+
"mean_diff": round(mean, 4),
|
| 76 |
+
"sd_diff": round(sd, 4),
|
| 77 |
+
"delta_margin": delta,
|
| 78 |
+
"alpha": alpha,
|
| 79 |
+
"tost_p": round(float(p_tost), 4),
|
| 80 |
+
"ci_90": [round(float(ci_lo), 4), round(float(ci_hi), 4)],
|
| 81 |
+
"equivalent_within_margin": bool(equivalent),
|
| 82 |
+
"interpretation": (
|
| 83 |
+
f"Arms EQUIVALENT within +/-{delta} (TOST p={p_tost:.4f} < {alpha})"
|
| 84 |
+
if equivalent else
|
| 85 |
+
f"Equivalence NOT established within +/-{delta} (TOST p={p_tost:.4f}); "
|
| 86 |
+
+ ("difference detected" if (ci_lo > 0 or ci_hi < 0) else "indeterminate (underpowered at this n)")
|
| 87 |
+
),
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def main() -> int:
|
| 92 |
+
ap = argparse.ArgumentParser()
|
| 93 |
+
ap.add_argument("--eval-dir", default="artifacts")
|
| 94 |
+
ap.add_argument("--glob", default="frozen_eval_{arm}_seed{seed}.json",
|
| 95 |
+
help="Filename pattern with {arm} and {seed} placeholders.")
|
| 96 |
+
ap.add_argument("--arm-a", default="openpom_256")
|
| 97 |
+
ap.add_argument("--arm-b", default="morgan")
|
| 98 |
+
ap.add_argument("--seeds", default="1,2,3,4,5")
|
| 99 |
+
ap.add_argument("--metric", default="prospective_cosine",
|
| 100 |
+
choices=["prospective_cosine", "prospective_cosine_novelty", "val_total", "triplet_accuracy"])
|
| 101 |
+
ap.add_argument("--delta", type=float, default=0.05, help="Equivalence margin (cosine units / loss units).")
|
| 102 |
+
ap.add_argument("--output", default="artifacts/multiseed_tost_analysis.json")
|
| 103 |
+
args = ap.parse_args()
|
| 104 |
+
|
| 105 |
+
seeds = [int(s) for s in args.seeds.split(",") if s.strip()]
|
| 106 |
+
a_vals, b_vals, used_seeds = [], [], []
|
| 107 |
+
missing = []
|
| 108 |
+
for s in seeds:
|
| 109 |
+
fa = Path(args.eval_dir) / args.glob.format(arm=args.arm_a, seed=s)
|
| 110 |
+
fb = Path(args.eval_dir) / args.glob.format(arm=args.arm_b, seed=s)
|
| 111 |
+
if not fa.exists() or not fb.exists():
|
| 112 |
+
missing.append({"seed": s, "missing": [str(p) for p in (fa, fb) if not p.exists()]})
|
| 113 |
+
continue
|
| 114 |
+
va = _metric(_load_eval(str(fa)), args.metric)
|
| 115 |
+
vb = _metric(_load_eval(str(fb)), args.metric)
|
| 116 |
+
if va is None or vb is None:
|
| 117 |
+
missing.append({"seed": s, "missing_metric": True})
|
| 118 |
+
continue
|
| 119 |
+
a_vals.append(va)
|
| 120 |
+
b_vals.append(vb)
|
| 121 |
+
used_seeds.append(s)
|
| 122 |
+
|
| 123 |
+
report = {
|
| 124 |
+
"arm_a": args.arm_a, "arm_b": args.arm_b, "metric": args.metric,
|
| 125 |
+
"delta_margin": args.delta,
|
| 126 |
+
"requested_seeds": seeds, "paired_seeds_used": used_seeds,
|
| 127 |
+
"missing": missing,
|
| 128 |
+
"arm_a_values": dict(zip(used_seeds, a_vals)),
|
| 129 |
+
"arm_b_values": dict(zip(used_seeds, b_vals)),
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
if len(used_seeds) >= 2:
|
| 133 |
+
diffs = np.array(a_vals) - np.array(b_vals)
|
| 134 |
+
report["arm_a_mean_sd"] = [round(float(np.mean(a_vals)), 4), round(float(np.std(a_vals, ddof=1)), 4)]
|
| 135 |
+
report["arm_b_mean_sd"] = [round(float(np.mean(b_vals)), 4), round(float(np.std(b_vals, ddof=1)), 4)]
|
| 136 |
+
report["tost"] = tost_paired(diffs, args.delta)
|
| 137 |
+
else:
|
| 138 |
+
report["tost"] = {"error": "insufficient paired seeds", "n": len(used_seeds)}
|
| 139 |
+
|
| 140 |
+
out = Path(args.output)
|
| 141 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 142 |
+
out.write_text(json.dumps(report, indent=2))
|
| 143 |
+
|
| 144 |
+
print("=" * 70)
|
| 145 |
+
print(f"MULTI-SEED TOST EQUIVALENCE: {args.arm_a} vs {args.arm_b} ({args.metric})")
|
| 146 |
+
print("=" * 70)
|
| 147 |
+
print(f"Paired seeds: {used_seeds} (n={len(used_seeds)})")
|
| 148 |
+
if "arm_a_mean_sd" in report:
|
| 149 |
+
print(f"{args.arm_a}: {report['arm_a_mean_sd'][0]} +/- {report['arm_a_mean_sd'][1]}")
|
| 150 |
+
print(f"{args.arm_b}: {report['arm_b_mean_sd'][0]} +/- {report['arm_b_mean_sd'][1]}")
|
| 151 |
+
t = report["tost"]
|
| 152 |
+
print(f"mean diff: {t.get('mean_diff')} (sd {t.get('sd_diff')}) | 90% CI {t.get('ci_90')}")
|
| 153 |
+
print(f"TOST p={t.get('tost_p')} within +/-{args.delta}: {t.get('interpretation')}")
|
| 154 |
+
else:
|
| 155 |
+
print("Insufficient paired seeds:", report["tost"].get("error"))
|
| 156 |
+
for m in missing:
|
| 157 |
+
print(" missing:", m)
|
| 158 |
+
print(f"Report: {out}")
|
| 159 |
+
print("=" * 70)
|
| 160 |
+
return 0
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
if __name__ == "__main__":
|
| 164 |
+
raise SystemExit(main())
|