File size: 4,476 Bytes
6f2ed01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/usr/bin/env python
"""The main results table: model x {BCS, BES, ISS, KTS}.   (protocol 13, 20)

    python src/make_table.py                 # markdown to stdout + outputs/
    python src/make_table.py --transport raw # the ablation table

ISS is reported from the J-Lens transported states. Raw-ISS is an
identity-transport ablation and is labelled as such (J-Lens spec 11); a model
whose J-Lens estimator failed validation shows "--" for ISS rather than a raw
number wearing the official name (spec 12).
"""
import os, sys, json, argparse

import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import mcommon as mc


def load(kind, name):
    p = mc.out("metrics", kind, name)
    return json.load(open(p)) if os.path.exists(p) else None


def fmt(v, nd=3, pct=False):
    if v is None or (isinstance(v, float) and not np.isfinite(v)):
        return "--"
    return f"{100 * v:.1f}" if pct else f"{v:.{nd}f}"


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--transport", choices=["jlens", "raw"], default="jlens")
    ap.add_argument("--coverage", choices=["complete_family", "full_set"], default=None)
    ap.add_argument("--models", nargs="*", default=None)
    args = ap.parse_args()

    C = mc.cfg()
    mode = args.coverage or C["headline_coverage"]
    names = args.models or [m["name"] for m in mc.models_cfg()["evaluated_models"]]

    rows = []
    for m in names:
        beh = load("behavioral", f"{m}.{mode}.summary.json")
        iss = load("iss", f"{m}.{args.transport}.{mode}.summary.json")
        kts = load("kts", f"{m}.{args.transport}.{mode}.summary.json")
        if not any([beh, iss, kts]):
            continue
        e = mc.model_entry(m)
        rows.append({
            "model": m, "family": e.get("family", ""), "tier": e.get("tier", ""),
            "params_b": e.get("params_b"), "tuning": e.get("tuning", ""),
            "bcs": beh and beh["bcs"], "bes": beh and beh["bes"],
            "scr": beh and beh["stable_correct_rate"],
            "swr": beh and beh["stable_wrong_rate"],
            "sar": beh and beh["stable_abstention_rate"],
            "ur": beh and beh["unstable_rate"],
            "iss": iss and iss["iss"], "iss_ci": iss and iss["iss_ci95"],
            "iss_peak": iss and iss["iss_peak"], "iss_late": iss and iss["iss_late"],
            "kts_geo": kts and kts["kts_geo"], "kts_id": kts and kts["kts_id"],
            "kts": kts and kts["kts"],
            "n_facts": (beh or iss or kts).get("n_facts"),
        })
    if not rows:
        raise SystemExit("nothing to tabulate yet")
    rows.sort(key=lambda r: (r["family"], r["params_b"] or 0))

    label = "ISS (J-Lens)" if args.transport == "jlens" else "Raw-ISS (ablation)"
    L = []
    L.append(f"# BCS / BES / ISS / KTS  ({mode}, transport={args.transport})\n")
    L.append(f"Fact set: fixed benchmark, {rows[0]['n_facts']} facts scored per model. "
             f"ISS column is **{label}**.\n")
    L.append("| Model | Family | Tier | BCS | BES | " + label +
             " | KTS-Geo | KTS-ID | KTS |")
    L.append("|---|---|---|---:|---:|---:|---:|---:|---:|")
    for r in rows:
        L.append(f"| {r['model']} | {r['family']} | {r['tier']} | "
                 f"{fmt(r['bcs'])} | {fmt(r['bes'])} | {fmt(r['iss'])} | "
                 f"{fmt(r['kts_geo'])} | {fmt(r['kts_id'])} | {fmt(r['kts'])} |")

    L.append("\n## Behaviour composition (protocol 6, %)\n")
    L.append("| Model | Stable Correct | Stable Wrong | Stable Abstention | Unstable |")
    L.append("|---|---:|---:|---:|---:|")
    for r in rows:
        L.append(f"| {r['model']} | {fmt(r['scr'], pct=True)} | {fmt(r['swr'], pct=True)} "
                 f"| {fmt(r['sar'], pct=True)} | {fmt(r['ur'], pct=True)} |")

    L.append("\n## ISS detail (protocol 7.10)\n")
    L.append("| Model | ISS | 95% CI | Peak | Late |")
    L.append("|---|---:|---|---:|---:|")
    for r in rows:
        ci = f"[{fmt(r['iss_ci'][0])}, {fmt(r['iss_ci'][1])}]" if r["iss_ci"] else "--"
        L.append(f"| {r['model']} | {fmt(r['iss'])} | {ci} | "
                 f"{fmt(r['iss_peak'])} | {fmt(r['iss_late'])} |")

    md = "\n".join(L) + "\n"
    dest = mc.out("metrics", f"main_table.{args.transport}.{mode}.md")
    with open(dest, "w") as f:
        f.write(md)
    mc.write_json(mc.out("metrics", f"main_table.{args.transport}.{mode}.json"), rows)
    print(md)
    print(f"written -> {dest}")


if __name__ == "__main__":
    main()