clap-retrieval-benchmark / analysis_v2.py
b4ph's picture
CLAP audio-text retrieval: pinned-protocol measurement release (v15)
fb47aa2 verified
Raw History Blame Contribute Delete
11.7 kB
"""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())