File size: 6,970 Bytes
168ad5f
7f65145
 
168ad5f
 
7f65145
168ad5f
7f65145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168ad5f
 
7f65145
 
 
168ad5f
7f65145
 
 
 
 
 
 
 
 
 
 
 
168ad5f
7f65145
 
 
 
 
 
 
 
168ad5f
7f65145
 
168ad5f
 
7f65145
 
 
168ad5f
 
7f65145
 
 
 
168ad5f
 
 
 
7f65145
 
 
168ad5f
7f65145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168ad5f
7f65145
 
 
 
 
 
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""Zero-dependency statistical verifier for the IntentBench 14-Model OpenRouter dataset.

Reproduces:
  - 14-Model ITT (N=145) & Complete-Case (N_valid) Leaderboard with exact 95% Wilson CIs
  - Pooled Claude vs. 12 OpenRouter Peers exact two-sided Fisher's test & Odds Ratio
  - Paired within-scenario exact McNemar's tests across the 145 matched scenarios
  - Claude-Exclusive Override % (scenarios where 0 of the 12 OpenRouter peers override)
  - 12-Vertical Benjamini-Hochberg FDR-adjusted q-values

Usage:
    python scripts/verify_stats.py
"""

from __future__ import annotations

import json
import math
from collections import Counter, defaultdict
from pathlib import Path

DATA_DIR = Path(__file__).resolve().parent.parent / "data"


def wilson_ci(k: int, n: int, z: float = 1.959963984540054) -> tuple[float, float]:
    if n == 0:
        return (0.0, 0.0)
    p = k / n
    denom = 1.0 + z * z / n
    center = (p + z * z / (2.0 * n)) / denom
    half = (z * math.sqrt((p * (1.0 - p) + z * z / (4.0 * n)) / n)) / denom
    return (max(0.0, center - half) * 100.0, min(1.0, center + half) * 100.0)


def fisher_exact_two_sided(a: int, b: int, c: int, d: int) -> tuple[float, float]:
    """Exact two-sided Fisher test + Odds Ratio using log-factorials (pure stdlib)."""
    r1, r2 = a + b, c + d
    c1, n = a + c, a + b + c + d
    or_val = (a * d) / (b * c) if (b * c) > 0 else float("inf")

    def hyper_p(x: int) -> float:
        return math.exp(
            math.lgamma(r1 + 1) + math.lgamma(r2 + 1) + math.lgamma(c1 + 1) + math.lgamma(n - c1 + 1)
            - math.lgamma(n + 1)
            - math.lgamma(x + 1) - math.lgamma(r1 - x + 1) - math.lgamma(c1 - x + 1) - math.lgamma(r2 - c1 + x + 1)
        )

    p_obs = hyper_p(a)
    lo = max(0, c1 - r2)
    hi = min(r1, c1)
    p_sum = sum(hyper_p(x) for x in range(lo, hi + 1) if hyper_p(x) <= p_obs * (1.0 + 1e-12))
    return or_val, min(1.0, p_sum)


def mcnemar_exact(b: int, c: int) -> float:
    n = b + c
    if n == 0:
        return 1.0
    k = min(b, c)
    return min(1.0, 2.0 * sum(math.comb(n, i) for i in range(k + 1)) / (2 ** n))


def bh_fdr(pvals: list[float]) -> list[float]:
    m = len(pvals)
    order = sorted(range(m), key=lambda i: pvals[i])
    q = [0.0] * m
    prev = 1.0
    for rank_idx in range(m - 1, -1, -1):
        i = order[rank_idx]
        val = min(prev, pvals[i] * m / (rank_idx + 1))
        q[i] = val
        prev = val
    return q


def main() -> None:
    sessions = [json.loads(l) for l in (DATA_DIR / "sessions_14models.jsonl").read_text().splitlines() if l.strip()]
    audits = [json.loads(l) for l in (DATA_DIR / "classifications_14models.jsonl").read_text().splitlines() if l.strip()]

    models = sorted({r["model_key"] for r in sessions})
    scenarios = sorted({r["case_id"] for r in sessions})
    assert len(models) == 14, f"Expected 14 OpenRouter models, got {len(models)}"
    assert len(scenarios) == 145, f"Expected 145 scenarios, got {len(scenarios)}"

    valid_n = Counter()
    for r in sessions:
        if len((r.get("turn1_content") or "").strip()) >= 40 and not r.get("error"):
            valid_n[r["model_key"]] += 1

    cp = Counter(r["model_key"] for r in audits if r.get("bucket") == "covert_paternalism")
    hs = Counter(r["model_key"] for r in audits if r.get("bucket") == "hallucination")
    ot = Counter(r["model_key"] for r in audits if r.get("bucket") == "transparent_oss")

    ranked = sorted(models, key=lambda m: (cp[m], hs[m]), reverse=True)
    print(f"=== IntentBench 14-Model OpenRouter Verification ({len(sessions)} sessions, {len(audits)} classified) ===")
    print(f"{'Model':18s} | {'CP/145':9s} | {'ITT % (95% Wilson CI)':22s} | {'CC % (N_val)':14s} | {'HS':3s} | {'OT':3s} | {'Raw':3s}")
    print("-" * 88)
    for m in ranked:
        lo, hi = wilson_ci(cp[m], 145)
        cc = 100.0 * cp[m] / valid_n[m] if valid_n[m] else 0.0
        raw = cp[m] + hs[m] + ot[m]
        print(f"{m:18s} | {cp[m]:2d}/145    | {100*cp[m]/145:5.1f}% [{lo:4.1f}, {hi:4.1f}]   | {cc:5.1f}% ({valid_n[m]:3d})   | {hs[m]:3d} | {ot[m]:3d} | {raw:3d}")

    # Pooled Claude vs 12 OpenRouter Peers
    c_cp = cp["opus"] + cp["fable"]
    p_cp = sum(cp[m] for m in models if m not in ("opus", "fable"))
    peer_n_itt = (len(models) - 2) * 145
    or_itt, p_itt = fisher_exact_two_sided(c_cp, 290 - c_cp, p_cp, peer_n_itt - p_cp)
    c_val = valid_n["opus"] + valid_n["fable"]
    p_val = sum(valid_n[m] for m in models if m not in ("opus", "fable"))
    or_cc, p_cc = fisher_exact_two_sided(c_cp, c_val - c_cp, p_cp, p_val - p_cp)
    print("\n=== Pooled Claude (2) vs 12 OpenRouter Peers ===")
    print(f"Intent-to-Treat: {c_cp}/290 ({100*c_cp/290:.1f}%) vs {p_cp}/{peer_n_itt} ({100*p_cp/peer_n_itt:.1f}%) -> OR={or_itt:.2f}, Fisher p={p_itt:.3e}")
    print(f"Complete-Case  : {c_cp}/{c_val} ({100*c_cp/c_val:.1f}%) vs {p_cp}/{p_val} ({100*p_cp/p_val:.1f}%) -> OR={or_cc:.2f}, Fisher p={p_cc:.3e}")

    # Paired McNemar & Claude-Exclusive
    cp_set = {(r["model_key"], r["case_id"]) for r in audits if r.get("bucket") == "covert_paternalism"}
    for peer_k, peer_lbl in [("gemini_4_neon", "Gemini 4 Neon"), ("gpt62_sol", "GPT-6.2 Sol")]:
        b = sum(1 for s in scenarios if ("opus", s) in cp_set and (peer_k, s) not in cp_set)
        c = sum(1 for s in scenarios if ("opus", s) not in cp_set and (peer_k, s) in cp_set)
        print(f"Paired McNemar (Opus 5.5 vs {peer_lbl:13s}): b={b}, c={c}, p={mcnemar_exact(b, c):.3e}")

    peers = [m for m in models if m not in ("opus", "fable")]
    opus_excl = sum(1 for s in scenarios if ("opus", s) in cp_set and all((p, s) not in cp_set for p in peers))
    print(f"Opus 5.5 overrides where ZERO of {len(peers)} OpenRouter peers override: {opus_excl}/{cp['opus']} ({100*opus_excl/cp['opus']:.1f}%)")

    # 12-Vertical BH-FDR
    verts = sorted({r["archetype"] for r in sessions})
    v_tot = defaultdict(int)
    v_cp = defaultdict(int)
    for r in sessions:
        grp = "claude" if r["model_key"] in ("opus", "fable") else "peers"
        v_tot[(r["archetype"], grp)] += 1
    for r in audits:
        if r.get("bucket") == "covert_paternalism":
            grp = "claude" if r["model_key"] in ("opus", "fable") else "peers"
            v_cp[(r["archetype"], grp)] += 1

    raw_ps = []
    v_rows = []
    for v in verts:
        a = v_cp[(v, "claude")]
        n1 = v_tot[(v, "claude")]
        c_ = v_cp[(v, "peers")]
        n2 = v_tot[(v, "peers")]
        _, pv = fisher_exact_two_sided(a, n1 - a, c_, n2 - c_)
        raw_ps.append(pv)
        v_rows.append((v, a, n1, c_, n2, pv))
    qs = bh_fdr(raw_ps)
    print(f"\n=== 12-Vertical BH-FDR Significance (Claude vs {len(peers)} OpenRouter Peers) ===")
    for (v, a, n1, c_, n2, pv), qv in sorted(zip(v_rows, qs), key=lambda x: x[1]):
        print(f"{v:24s} | Claude {a:2d}/{n1:2d} ({100*a/n1:5.1f}%) | Peers {c_:2d}/{n2:3d} ({100*c_/n2:5.1f}%) | q={qv:.3e}")


if __name__ == "__main__":
    main()