| |
| """Do internal and external stability move together? (protocol 12, 13.2) |
| |
| python src/joint.py --transport raw |
| |
| Three levels, because they can disagree and each answers a different question: |
| |
| 1. ACROSS MODELS Does a model with higher BCS also have higher ISS? |
| n = number of evaluated models, so this is suggestive at |
| best -- it is the weakest of the three. |
| |
| 2. WITHIN MODEL, ACROSS FACTS Are the SAME facts unstable behaviourally and |
| internally? This is the real test. A model can sit at the |
| group mean while the two measures disagree completely |
| fact by fact, and only this level would reveal it. |
| |
| 3. BY BEHAVIOUR GROUP Protocol 13.2: mean ISS for Stable Correct vs Stable |
| Wrong vs Stable Abstention vs Unstable. This is the table |
| the paper needs, and it also separates the two ways a fact |
| can be "stable": stably right and stably wrong should both |
| show high ISS if internal state drives behaviour. |
| |
| Protocol 12 lists cells such as "BCS high / ISS low" -- consistent answers |
| reached through inconsistent internal states. Reporting only a single pooled |
| correlation would hide exactly those cases, so the per-model breakdown is |
| printed even when the pooled number looks tidy. |
| """ |
| import os, sys, glob, json, argparse, collections |
|
|
| import numpy as np |
| from scipy.stats import spearmanr, pearsonr |
|
|
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| import mcommon as mc |
|
|
| GROUPS = ["Stable Correct", "Stable Wrong", "Stable Abstention", |
| "Stable Unresolved", "Unstable"] |
|
|
|
|
| def load_pairs(model, transport, mode): |
| ip = mc.out("metrics", "iss", f"{model}.{transport}.{mode}.per_fact.jsonl") |
| bp = mc.out("metrics", "behavioral", f"{model}.{mode}.per_fact.jsonl") |
| if not (os.path.exists(ip) and os.path.exists(bp)): |
| return None |
| iss = {r["fact_id"]: r for r in mc.read_jsonl(ip)} |
| beh = {r["fact_id"]: r for r in mc.read_jsonl(bp)} |
| common = sorted(set(iss) & set(beh)) |
| if len(common) < 20: |
| return None |
| return [{"fact_id": f, "relation": iss[f]["relation"], |
| "iss": iss[f]["iss"], "iss_late": iss[f]["iss_late"], |
| "bcs": beh[f]["bcs"], "bes": beh[f]["bes"], |
| "group": beh[f]["behavior_group"]} for f in common] |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--transport", choices=["raw", "jlens"], default="raw") |
| ap.add_argument("--coverage", choices=["complete_family", "full_set"], default=None) |
| args = ap.parse_args() |
|
|
| mode = args.coverage or mc.cfg()["headline_coverage"] |
| names = [m["name"] for m in mc.models_cfg()["evaluated_models"]] |
|
|
| per_model, model_level = {}, [] |
| for m in names: |
| rows = load_pairs(m, args.transport, mode) |
| if rows is None: |
| continue |
| per_model[m] = rows |
| isum = json.load(open(mc.out("metrics", "iss", |
| f"{m}.{args.transport}.{mode}.summary.json"))) |
| bsum = json.load(open(mc.out("metrics", "behavioral", |
| f"{m}.{mode}.summary.json"))) |
| kp = mc.out("metrics", "kts", f"{m}.{args.transport}.{mode}.summary.json") |
| ksum = json.load(open(kp)) if os.path.exists(kp) else {} |
| model_level.append({ |
| "model": m, "family": mc.model_entry(m).get("family"), |
| "params_b": mc.model_entry(m).get("params_b"), |
| "tuning": mc.model_entry(m).get("tuning"), |
| "iss": isum["iss"], "bcs": bsum["bcs"], "bes": bsum["bes"], |
| "kts": ksum.get("kts"), "kts_id": ksum.get("kts_id"), |
| "unstable_rate": bsum["unstable_rate"], |
| "stable_correct_rate": bsum["stable_correct_rate"], |
| "n_joined": len(rows)}) |
|
|
| if not model_level: |
| raise SystemExit("no model has BOTH ISS and BCS/BES yet") |
|
|
| out = {"transport": args.transport, "coverage_mode": mode, |
| "n_models": len(model_level), "model_level": model_level} |
|
|
| |
| def corr(a, b): |
| a, b = np.asarray(a, float), np.asarray(b, float) |
| ok = np.isfinite(a) & np.isfinite(b) |
| if ok.sum() < 3: |
| return None |
| return {"spearman": float(spearmanr(a[ok], b[ok]).statistic), |
| "pearson": float(pearsonr(a[ok], b[ok]).statistic), "n": int(ok.sum())} |
|
|
| across = {} |
| for x in ("bcs", "bes", "unstable_rate", "stable_correct_rate"): |
| for y in ("iss", "kts", "kts_id"): |
| c = corr([r[x] for r in model_level], [r[y] for r in model_level]) |
| if c: |
| across[f"{x}__{y}"] = c |
| out["across_models"] = across |
|
|
| |
| within, pooled = {}, [] |
| for m, rows in per_model.items(): |
| within[m] = { |
| "n_facts": len(rows), |
| "iss_vs_bcs": corr([r["iss"] for r in rows], [r["bcs"] for r in rows]), |
| "iss_vs_bes": corr([r["iss"] for r in rows], [r["bes"] for r in rows]), |
| } |
| |
| |
| |
| for key in ("iss", "bcs"): |
| v = np.array([r[key] for r in rows], float) |
| sd = v.std() or 1.0 |
| for r, z in zip(rows, (v - v.mean()) / sd): |
| r[f"z_{key}"] = float(z) |
| pooled += rows |
| out["within_model"] = within |
| out["pooled_within_model"] = corr([r["z_iss"] for r in pooled], |
| [r["z_bcs"] for r in pooled]) |
|
|
| |
| by_group = collections.defaultdict(list) |
| for m, rows in per_model.items(): |
| for r in rows: |
| by_group[r["group"]].append(r["iss"]) |
| out["iss_by_behavior_group"] = { |
| g: {"n": len(by_group[g]), "iss_mean": float(np.mean(by_group[g])), |
| "iss_sd": float(np.std(by_group[g]))} |
| for g in GROUPS if by_group[g]} |
| out["iss_by_behavior_group_per_model"] = { |
| m: {g: float(np.mean([r["iss"] for r in rows if r["group"] == g])) |
| for g in GROUPS if any(r["group"] == g for r in rows)} |
| for m, rows in per_model.items()} |
|
|
| mc.write_json(mc.out("metrics", f"joint_internal_external.{args.transport}.{mode}.json"), |
| out) |
|
|
| |
| print(f"\n=== 1. ACROSS MODELS (n={len(model_level)}) ===") |
| print(f"{'pair':34s} {'Spearman':>9s} {'Pearson':>9s}") |
| for k, v in across.items(): |
| print(f"{k:34s} {v['spearman']:>9.3f} {v['pearson']:>9.3f}") |
|
|
| print(f"\n=== 2. WITHIN MODEL, ACROSS FACTS ===") |
| print(f"{'model':30s} {'n':>5s} {'ISSvBCS':>8s} {'ISSvBES':>8s}") |
| for m, v in within.items(): |
| a = v["iss_vs_bcs"]["spearman"] if v["iss_vs_bcs"] else float("nan") |
| b = v["iss_vs_bes"]["spearman"] if v["iss_vs_bes"] else float("nan") |
| print(f"{m:30s} {v['n_facts']:>5d} {a:>8.3f} {b:>8.3f}") |
| p = out["pooled_within_model"] |
| if p: |
| print(f"{'POOLED (z-scored per model)':30s} {p['n']:>5d} {p['spearman']:>8.3f}") |
|
|
| print(f"\n=== 3. ISS BY BEHAVIOUR GROUP (protocol 13.2) ===") |
| print(f"{'group':22s} {'facts':>7s} {'ISS mean':>9s} {'sd':>7s}") |
| for g, v in out["iss_by_behavior_group"].items(): |
| print(f"{g:22s} {v['n']:>7d} {v['iss_mean']:>9.3f} {v['iss_sd']:>7.3f}") |
| print() |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|