File size: 9,723 Bytes
592942b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""Tier-1 re-analysis of cached results (no GPU, no refitting): reads results/*.jsonl and
produces the breakdowns the paper needs. Safe to run alongside / after the grid.

    python analyze.py shift        # per shift-type predictor ranking (paraphrase/domain/length)
    python analyze.py estimator    # cross-estimator: do logreg-based predictors predict mass-mean rotation?
    python analyze.py fidelity     # label-fidelity (NLI flip-rate) summary per dataset
    python analyze.py all
"""
from __future__ import annotations

import sys

import numpy as np

import metrics
from config import DATASETS
from baselines import PREDICTORS
from run_pipeline import _rot_mag, _mean_ood_drop, _read_results, _rank_predictors


def _pred_index(preds):
    return {(p["model"], p["dataset"], p["seed"]): p["predictors"] for p in preds}


def shift_breakdown():
    evals = _read_results("eval")
    pidx = _pred_index(_read_results("predictors"))
    print("\n########## SHIFT-TYPE BREAKDOWN (rotation target per shift) ##########")
    for shift in ["paraphrase", "domain", "length"]:
        rows = []
        for e in evals:
            if e.get("probe") != "logreg":
                continue
            key = (e["model"], e["dataset"], e["seed"])
            if key not in pidx:
                continue
            mag = _rot_mag(e.get("dists", {}).get(shift, {}).get("rotation"))
            if mag != mag:
                continue
            rows.append({"concept": DATASETS[e["dataset"]].concept, "rot": mag, **pidx[key]})
        if len(rows) < 8:
            print(f"\n[{shift}] only {len(rows)} configs — skipped")
            continue
        _rank_predictors(rows, "rot", f"rotation under {shift.upper()} (n={len(rows)})")


def estimator_cross():
    """Do logreg-derived predictors also forecast the MASS-MEAN probe's rotation? (S2 external validity)."""
    evals = _read_results("eval")
    pidx = _pred_index(_read_results("predictors"))
    print("\n########## ESTIMATOR EXTERNAL VALIDITY (predict mass-mean rotation) ##########")
    rows = []
    for e in evals:
        if e.get("probe") != "mass_mean":
            continue
        key = (e["model"], e["dataset"], e["seed"])
        if key not in pidx:
            continue
        rots = [_rot_mag(v.get("rotation")) for d, v in e.get("dists", {}).items() if d != "iid"]
        rots = [r for r in rots if r == r]
        if not rots:
            continue
        rows.append({"concept": DATASETS[e["dataset"]].concept, "rot": float(np.mean(rots)), **pidx[key]})
    if len(rows) < 8:
        print(f"only {len(rows)} configs — skipped")
        return
    _rank_predictors(rows, "rot", f"mass-mean rotation (n={len(rows)})")


def size_ladder():
    """Tier 3: does predictability of rotation / excess change with model size?
    (C4 / inverse-scaling check). Per model, correlate key predictors vs paraphrase rotation
    and vs excess rotation across its (dataset x seed) configs.
    """
    from config import MODELS
    evals = _read_results("eval")
    pidx = _pred_index(_read_results("predictors"))
    keypreds = ["raptor_stability", "augmentation_robustness", "pac"]
    # build per-model rows of (predictors, para_rot, excess)
    by_model = {}
    for e in evals:
        if e.get("probe") != "logreg":
            continue
        key = (e["model"], e["dataset"], e["seed"])
        if key not in pidx:
            continue
        para = _rot_mag(e.get("dists", {}).get("paraphrase", {}).get("rotation"))
        iids = _rot_mag(e.get("iid_split_rotation"))
        if para != para:
            continue
        excess = para - iids if iids == iids else float("nan")
        by_model.setdefault(e["model"], []).append({"para": para, "excess": excess, **pidx[key]})
    print("\n########## SIZE-LADDER: predictability vs model size ##########")
    print(f"{'model':16s}{'params_M':>9s}  | rho(predictor, target) for para-rot / excess")
    for m in sorted(by_model, key=lambda x: MODELS[x].params_m if x in MODELS else 0):
        rows = by_model[m]
        pm = MODELS[m].params_m if m in MODELS else 0
        cells = []
        for tgt in ("para", "excess"):
            y = np.array([r[tgt] for r in rows], dtype=float)
            for kp in keypreds:
                s = np.array([r.get(kp, np.nan) for r in rows], dtype=float)
                ok = ~(np.isnan(s) | np.isnan(y))
                rho = metrics.spearman(s[ok], -y[ok])[0] if ok.sum() >= 6 else float("nan")
                cells.append(f"{kp.split('_')[0][:4]}:{rho:+.2f}")
            cells.append("|")
        print(f"{m:16s}{pm:>9.0f}  | {' '.join(cells)}")
    print("(target order: para-rot [raptor aug pac] | excess [raptor aug pac])")


def _partial_spearman(x, y, z):
    """Partial Spearman of (x,y) controlling for z: rank-transform then residualise on z."""
    from scipy.stats import rankdata
    ok = ~(np.isnan(x) | np.isnan(y) | np.isnan(z))
    x, y, z = x[ok], y[ok], z[ok]
    if len(x) < 8:
        return float("nan"), 0
    rx, ry, rz = rankdata(x), rankdata(y), rankdata(z)
    Z = np.c_[np.ones_like(rz), rz]
    res = lambda a: a - Z @ np.linalg.lstsq(Z, a, rcond=None)[0]
    ex, ey = res(rx), res(ry)
    return float(np.corrcoef(ex, ey)[0, 1]), len(x)


def robust_circularity():
    """Reviewer rebuttal (R2 difference-score artefact, R1 pseudo-replication):
    (a) PARTIAL Spearman of (signal, paraphrase-rotation | placebo) — does a signal predict
        shift-rotation BEYOND the sampling-noise floor, without the naive-minus-placebo subtraction?
    (b) CLUSTER bootstrap (resampling CONCEPTS, not cells) for Δρ[aug−raptor] on excess.
    """
    evals = _read_results("eval")
    pidx = _pred_index(_read_results("predictors"))
    rows = []
    for e in evals:
        if e.get("probe") != "logreg":
            continue
        k = (e["model"], e["dataset"], e["seed"])
        if k not in pidx:
            continue
        para = _rot_mag(e.get("dists", {}).get("paraphrase", {}).get("rotation"))
        plac = _rot_mag(e.get("iid_split_rotation"))
        if para != para or plac != plac:
            continue
        rows.append({"concept": DATASETS[e["dataset"]].concept, "para": para, "plac": plac,
                     "excess": para - plac, **pidx[k]})
    print("\n########## ROBUST CIRCULARITY CHECK (reviewer R1/R2 rebuttal) ##########")
    print("PARTIAL Spearman rho(signal, paraphrase-rot | placebo)  [the artefact-free version]")
    print(f"{'predictor':26s}{'partial-rho':>12s}{'naive-rho':>11s}{'excess-rho':>11s}")
    para = np.array([r["para"] for r in rows]); plac = np.array([r["plac"] for r in rows])
    exc = np.array([r["excess"] for r in rows])
    for name in PREDICTORS:
        s = np.array([r.get(name, np.nan) for r in rows], float)
        pr, n = _partial_spearman(s, para, plac)
        nr = metrics.spearman(s[~np.isnan(s)], -para[~np.isnan(s)])[0] if (~np.isnan(s)).sum() >= 8 else float("nan")
        er = metrics.spearman(s[~np.isnan(s)], -exc[~np.isnan(s)])[0] if (~np.isnan(s)).sum() >= 8 else float("nan")
        print(f"{name:26s}{-pr:>12.3f}{nr:>11.3f}{er:>11.3f}")
    print("(partial-rho>0 => signal predicts shift-rotation beyond the sampling floor, non-circular,"
          " no difference-score subtraction)")

    # cluster bootstrap by concept for Delta rho[aug - raptor] on excess
    concepts = np.array([r["concept"] for r in rows])
    uc = list(np.unique(concepts))
    sa = np.array([r.get("augmentation_robustness", np.nan) for r in rows], float)
    sb = np.array([r.get("raptor_stability", np.nan) for r in rows], float)
    rng = np.random.default_rng(0)
    def drho(mask):
        m = mask & ~(np.isnan(sa) | np.isnan(sb) | np.isnan(exc))
        if m.sum() < 8:
            return np.nan
        return metrics.spearman(sa[m], -exc[m])[0] - metrics.spearman(sb[m], -exc[m])[0]
    base = drho(np.ones(len(rows), bool))
    boots = []
    for _ in range(2000):
        pick = rng.choice(uc, len(uc), replace=True)
        mask = np.isin(concepts, pick)
        # build resampled arrays by concept blocks
        idx = np.concatenate([np.where(concepts == c)[0] for c in pick])
        m = ~(np.isnan(sa[idx]) | np.isnan(sb[idx]) | np.isnan(exc[idx]))
        if m.sum() >= 8:
            boots.append(metrics.spearman(sa[idx][m], -exc[idx][m])[0] - metrics.spearman(sb[idx][m], -exc[idx][m])[0])
    lo, hi = np.percentile(boots, [2.5, 97.5])
    sig = "SIGNIFICANT" if lo > 0 else "n.s."
    print(f"\nCLUSTER bootstrap (resample {len(uc)} CONCEPTS): Δρ[aug−raptor] on EXCESS = {base:+.3f}"
          f"  95%CI [{lo:+.3f},{hi:+.3f}] -> {sig}")
    print("(this is the pseudo-replication-corrected version of the headline paired test)")


def fidelity_summary():
    audit = _read_results("audit")
    print("\n########## LABEL-FIDELITY (NLI flip-rate of paraphrase shift) ##########")
    by_ds = {}
    for a in audit:
        by_ds.setdefault(a["dataset"], []).append(a.get("flip_rate", float("nan")))
    print(f"{'dataset':18s}{'mean flip-rate':>16s}{'pass-rate':>12s}")
    for ds in sorted(by_ds):
        fr = float(np.nanmean(by_ds[ds]))
        print(f"{ds:18s}{fr:>16.3f}{1 - fr:>12.3f}")
    allfr = [v for vs in by_ds.values() for v in vs if v == v]
    if allfr:
        print(f"{'OVERALL':18s}{np.mean(allfr):>16.3f}{1 - np.mean(allfr):>12.3f}")


if __name__ == "__main__":
    mode = sys.argv[1] if len(sys.argv) > 1 else "all"
    if mode in ("shift", "all"):
        shift_breakdown()
    if mode in ("estimator", "all"):
        estimator_cross()
    if mode in ("size", "all"):
        size_ladder()
    if mode in ("robust", "all"):
        robust_circularity()
    if mode in ("fidelity", "all"):
        fidelity_summary()