File size: 11,662 Bytes
fb47aa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
"""Pre-registered analysis for the v2 harness.

Implements exactly what `PREREGISTRATION.md` commits to:

  * primary endpoint: Clotho five-caption T2A R@1;
  * secondary: Clotho A2T R@1, AudioCaps T2A R@1, AudioCaps A2T R@1;
  * effect: unfused minus fused, paired by query;
  * cluster bootstrap that resamples CLIPS (five captions per clip are not
    independent), 2000 resamples, fixed seed;
  * Holm correction across the four endpoints;
  * TOST equivalence at a pre-committed margin, so "no difference" is a claim.

    python analysis_v2.py results_v2 --prereg PREREGISTRATION.md
"""
from __future__ import annotations

import argparse
import json
import math
from pathlib import Path

import numpy as np

SEED = 20261027
N_BOOT = 2000
EQUIV_MARGIN = 0.03          # pre-registered, do not tune after seeing results
ENDPOINTS = [
    ("clotho5", "t2a", "r@1", "primary"),
    ("clotho5", "a2t", "r@1", "secondary"),
    ("audiocaps", "t2a", "r@1", "secondary"),
    ("audiocaps", "a2t", "r@1", "secondary"),
]


# ---------------------------------------------------------------- estimators

def _hit(r: int, k: int) -> float:
    return 1.0 if r <= k else 0.0


def cluster_bootstrap_mean(values: np.ndarray, clusters: np.ndarray, stat,
                           n_boot: int = N_BOOT, seed: int = SEED):
    """Resample clusters with replacement; recompute the mean over all their rows."""
    rng = np.random.default_rng(seed)
    uniq = np.unique(clusters)
    idx_by_cluster = {c: np.flatnonzero(clusters == c) for c in uniq}
    draws = np.empty(n_boot)
    for i in range(n_boot):
        pick = rng.choice(uniq, size=len(uniq), replace=True)
        idx = np.concatenate([idx_by_cluster[c] for c in pick])
        draws[i] = stat(values[idx])
    return (float(np.percentile(draws, 2.5)),
            float(np.percentile(draws, 97.5)),
            float(draws.std(ddof=1)))


def cluster_bootstrap_delta(a: np.ndarray, b: np.ndarray, clusters: np.ndarray,
                            n_boot: int = N_BOOT, seed: int = SEED):
    """Paired bootstrap over clusters: the same resample is applied to both arms."""
    rng = np.random.default_rng(seed)
    uniq = np.unique(clusters)
    idx_by_cluster = {c: np.flatnonzero(clusters == c) for c in uniq}
    draws = np.empty(n_boot)
    for i in range(n_boot):
        pick = rng.choice(uniq, size=len(uniq), replace=True)
        idx = np.concatenate([idx_by_cluster[c] for c in pick])
        draws[i] = b[idx].mean() - a[idx].mean()
    return (float(np.percentile(draws, 2.5)), float(np.percentile(draws, 97.5)),
            float(draws.std(ddof=1)))


def tost(delta: float, se: float, margin: float = EQUIV_MARGIN, alpha: float = 0.05):
    """Two one-sided tests on a paired difference.

    Equivalent if the (1 - 2*alpha) CI lies inside [-margin, +margin]. Returned
    p-value is the larger of the two one-sided p-values, which is the standard
    TOST statistic. Normal approximation, appropriate at these n.
    """
    if se <= 0:
        return {"equivalent": abs(delta) < margin, "p": 0.0 if abs(delta) < margin else 1.0,
                "ci90": [delta, delta]}
    z = delta / se
    p_lower = 1.0 - _norm_cdf(z + margin / se)   # H0: delta <= -margin
    p_upper = _norm_cdf(z - margin / se)         # H0: delta >= +margin
    p = max(p_lower, p_upper)
    ci90 = [delta - 1.6448536269514722 * se, delta + 1.6448536269514722 * se]
    return {"equivalent": bool(p < alpha), "p": float(p),
            "ci90": [float(ci90[0]), float(ci90[1])]}


def _norm_cdf(x: float) -> float:
    return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))


def cluster_sign_flip(a_hits: np.ndarray, b_hits: np.ndarray, clusters: np.ndarray,
                      n_perm: int = 10000, seed: int = SEED) -> dict:
    """Permutation test at the clip level.

    McNemar assumes independent pairs, but five captions of one clip share their
    audio, so those five pairs are correlated and McNemar's p is anti-conservative.
    Here the labels are swapped *per cluster*: under the null the two checkpoints are
    exchangeable within a clip, so each clip contributes either +d or -d, where d is
    that clip's (b - a) contribution. Captions never move independently.
    """
    uniq, inv = np.unique(clusters, return_inverse=True)
    sa = np.bincount(inv, weights=a_hits.astype(float), minlength=len(uniq))
    sb = np.bincount(inv, weights=b_hits.astype(float), minlength=len(uniq))
    d = sb - sa
    total = float(len(a_hits))
    obs = float(d.sum() / total)

    rng = np.random.default_rng(seed)
    hits = 0
    done = 0
    while done < n_perm:
        chunk = min(1000, n_perm - done)
        signs = rng.choice(np.array([-1.0, 1.0]), size=(chunk, len(uniq)))
        sims = signs @ d / total
        hits += int(np.sum(np.abs(sims) >= abs(obs) - 1e-15))
        done += chunk
    p = (1.0 + hits) / (n_perm + 1.0)
    return {"delta": obs, "p_cluster_perm": float(p),
            "n_permutations": n_perm, "n_clusters": int(len(uniq))}


def mcnemar_exact(a_hits: np.ndarray, b_hits: np.ndarray) -> tuple[float, int, int]:
    """Exact two-sided McNemar on paired binary outcomes.

    Returns (p, b_only, a_only) where b_only counts queries only b gets right.
    This is the difference test; TOST answers a different question and must not be
    substituted for it.
    """
    n01 = int((~a_hits & b_hits).sum())
    n10 = int((a_hits & ~b_hits).sum())
    m = n01 + n10
    if m == 0:
        return 1.0, n01, n10
    tail = sum(math.comb(m, i) for i in range(0, min(n01, n10) + 1)) / 2 ** m
    return min(1.0, 2 * tail), n01, n10


def holm(pvals: dict[str, float], alpha: float = 0.05) -> dict[str, float]:
    """Holm-Bonferroni step-down. Returns adjusted p-values, monotone in the input."""
    items = sorted(pvals.items(), key=lambda kv: kv[1])
    m = len(items)
    adj, running = {}, 0.0
    for i, (name, p) in enumerate(items):
        val = min(1.0, (m - i) * p)
        running = max(running, val)
        adj[name] = running
    return adj


def mdd(se: float, alpha: float = 0.05, power: float = 0.8) -> float:
    """Minimum detectable difference at the given power (normal approximation)."""
    return float((1.959963984540054 + 0.8416212335729143) * se)


# ---------------------------------------------------------------- loading

def load_cell(path: Path) -> dict:
    d = json.loads(path.read_text(encoding="utf-8"))
    need = ("first_hit_rank", "cluster")
    if d["metrics"]["t2a"].get("cluster") is None:
        raise SystemExit(f"{path.name}: missing per-query clusters; rerun the cell")
    return d


def arm(d: dict, direction: str, k: int):
    m = d["metrics"][direction]
    ranks = np.asarray(m["first_hit_rank"], dtype=np.int64)
    clusters = np.asarray(m["cluster"], dtype=np.int64)
    return np.array([_hit(r, k) for r in ranks]), clusters


def summarise(d: dict, direction: str, k: int) -> dict:
    hits, clusters = arm(d, direction, k)
    lo, hi, se = cluster_bootstrap_mean(hits, clusters, lambda v: float(v.mean()))
    return {"value": float(hits.mean()), "ci95": [lo, hi], "se_cluster": se,
            "n_queries": int(len(hits)), "n_clusters": int(clusters.max() + 1)}


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("dir", nargs="?", default="results_v2")
    ap.add_argument("--out", default="analysis_v2.json")
    ap.add_argument("--prereg", default="PREREGISTRATION.md")
    args = ap.parse_args()

    if not Path(args.prereg).exists():
        raise SystemExit("PREREGISTRATION.md missing: analysis must follow a committed plan")

    root = Path(args.dir)
    cells = {}
    for f in sorted(root.glob("*__canon.json")):
        d = load_cell(f)
        cells[(d["dataset"], d["model"])] = d

    models = sorted({m for (_, m) in cells})
    if len(models) != 2:
        raise SystemExit(f"expected two checkpoints, found {models}")

    report = {"prereg": args.prereg, "equivalence_margin": EQUIV_MARGIN,
              "cells": {}, "endpoints": {}}
    for ds in sorted({d for (d, _) in cells}):
        for m in models:
            key = f"{m}|{ds}"
            report["cells"][key] = {
                "t2a_r1": summarise(cells[(ds, m)], "t2a", 1),
                "a2t_r1": summarise(cells[(ds, m)], "a2t", 1),
                "t2a_mrr": summarise_rank(cells[(ds, m)], "t2a"),
                "a2t_map": summarise_ap(cells[(ds, m)]),
            }

    fused = next(m for m in models if m.endswith("fused"))
    unfused = next(m for m in models if m.endswith("unfused"))
    pvals = {}
    for ds, direction, metric, role in ENDPOINTS:
        if (ds, fused) not in cells or (ds, unfused) not in cells:
            continue
        k = int(metric.split("@")[1])
        a, clusters = arm(cells[(ds, fused)], direction, k)
        b, _ = arm(cells[(ds, unfused)], direction, k)
        delta = float(b.mean() - a.mean())
        lo, hi, se = cluster_bootstrap_delta(a, b, clusters)
        eq = tost(delta, se)
        # difference test at the clip level: captions within a clip are correlated,
        # so McNemar's independent-pairs p is reported only for reference
        perm = cluster_sign_flip(a > 0.5, b > 0.5, clusters)
        mcn_p, n01, n10 = mcnemar_exact(a > 0.5, b > 0.5)
        name = f"{ds}_{direction}_{metric}"
        pvals[name] = perm["p_cluster_perm"]
        report["endpoints"][name] = {
            "role": role, "dataset": ds, "direction": direction, "metric": metric,
            "delta_unfused_minus_fused": delta,
            "ci95": [lo, hi], "se_cluster": se, "mdd80": mdd(se),
            "p_cluster_perm": perm["p_cluster_perm"],
            "n_permutations": perm["n_permutations"],
            "mcnemar_p_reference_only": mcn_p, "b_only": n01, "a_only": n10,
            "tost_p": eq["p"], "equivalent_at_margin": eq["equivalent"],
            "ci90_for_tost": eq["ci90"],
        }

    holm_adj = holm(pvals)
    for name, adj in holm_adj.items():
        report["endpoints"][name]["holm_adjusted_p"] = adj
        report["endpoints"][name]["significant_after_holm"] = bool(adj < 0.05)

    Path(args.out).write_text(json.dumps(report, indent=2), encoding="utf-8",
                              newline="\n")

    print(f"{'endpoint':<24}{'delta':>8}  {'95% CI':<19}{'perm p':>9}{'Holm':>8}"
          f"{'TOST':>8}  verdict")
    for name, e in report["endpoints"].items():
        ci = f"[{e['ci95'][0]:+.3f}, {e['ci95'][1]:+.3f}]"
        if e["significant_after_holm"]:
            verdict = "difference"
        elif e["equivalent_at_margin"]:
            verdict = "equivalent within +/-0.03"
        else:
            verdict = "inconclusive"
        print(f"{name:<24}{e['delta_unfused_minus_fused']:>+8.3f}  {ci:<19}"
              f"{e['p_cluster_perm']:>9.2g}{e['holm_adjusted_p']:>8.2g}"
              f"{e['tost_p']:>8.2g}  {verdict}")
    print(f"\nwrote {args.out}")
    return 0


def summarise_rank(d: dict, direction: str) -> dict:
    m = d["metrics"][direction]
    ranks = np.asarray(m["first_hit_rank"], dtype=np.float64)
    clusters = np.asarray(m["cluster"], dtype=np.int64)
    lo, hi, se = cluster_bootstrap_mean(ranks, clusters, lambda v: float((1.0 / v).mean()))
    return {"value": float((1.0 / ranks).mean()), "ci95": [lo, hi], "se_cluster": se}


def summarise_ap(d: dict) -> dict:
    m = d["metrics"]["a2t"]
    ap = np.asarray(m["ap"], dtype=np.float64)
    clusters = np.asarray(m["cluster"], dtype=np.int64)
    lo, hi, se = cluster_bootstrap_mean(ap, clusters, lambda v: float(v.mean()))
    return {"value": float(ap.mean()), "ci95": [lo, hi], "se_cluster": se}


if __name__ == "__main__":
    raise SystemExit(main())