CheneyWong's picture
canonical OTSL ground truth: scripts/compare_runs.py
2e34ef4 verified
Raw History Blame Contribute Delete
9.75 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""两个评测 run 的逐 cohort 对比 + bootstrap 置信区间。
v9 训完要回答的问题只有一个:「v9 相对基座/相对 v0,到底是真涨还是噪声」。
单看均值不够 —— 184,074 条上的 0.001 差异常常是噪声,0.02 才是信号。
口径与冻结协议一致:
主指标 = TEDS-S(与 canonical_teds.primary_metric 一致;空 cell 表如
synthtabnet / sprint_mustard 的 TEDS 恒为 null,只能看 TEDS-S)
每个 cohort 单独算,**不把两种口径混在一张表里排序**
CI 用 bootstrap(重采样 10000 次,种子固定):
能按样本配对的 cohort -> 配对 bootstrap(消掉样本难易差异,CI 更窄)
配不上的(上游 sample_id 为空的 9 个 cohort,orig_full 的 scores 里
155,178/184,074 条 id 是空的)-> 各自独立重采样的非配对 CI
用法:
python3 src/compare_runs.py --a v1-20261020-025952_checkpoint-3054 --b orig_full
python3 src/compare_runs.py --a <tagA> --b <tagB> --out reports/x.json
"""
import argparse
import collections
import json
import os
import random
import statistics
V5 = "/autodl-fs/data/povl_v5"
RUNS = f"{V5}/eval/runs"
BOOT = 10000
SEED = 20261020
def load(tag, id_map=None):
"""-> {cohort: {sid: (teds, teds_s)}}
eval_mix 换过 sample_id 的生成方式: 早期 run 用 pack 里的上游 id,
后期 run 用 (shard, rg, idx) 定位符。id_map 把定位符翻译回上游 id,
这样两个 run 才能按样本配对(上游 id 为空的 9 个 cohort 无解, 走非配对)。
"""
p = f"{RUNS}/{tag}/scores.jsonl"
out = collections.defaultdict(dict)
with open(p, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
d = json.loads(line)
c = d.get("cohort") or "?"
sid = d.get("sample_id") or ""
if sid and id_map and sid in id_map:
sid = id_map[sid]
if not sid:
sid = f"__pos_{len(out[c])}"
t = d.get("teds")
s = d.get("teds_s")
if t is None and s is None:
continue
out[c][sid] = (t, s)
return out
def mean(vals):
vals = [v for v in vals if v is not None]
return statistics.fmean(vals) if vals else None
# n 大的时候 bootstrap 会慢到没法用(10k x 9.4万 = 9.4 亿次抽样),
# 而均值差的抽样分布在大样本下就是正态的。分界: n <= BOOT_MAX 用真 bootstrap,
# 更大的用正态近似(同样的 1.96 倍标准误), 差可以忽略。
BOOT_MAX = 8000
import numpy as np
def _boot_ci(arrs, paired=False, n=BOOT, seed=SEED):
"""arrs: [a, b] 或配对差值数组。返回 (mean_diff, lo, hi)。"""
if paired:
d = np.asarray(arrs, dtype=np.float64)
m = float(d.mean())
if len(d) > BOOT_MAX:
se = float(d.std(ddof=1)) / np.sqrt(len(d))
return m, m - 1.96 * se, m + 1.96 * se
rng = np.random.default_rng(seed)
idx = rng.integers(0, len(d), size=(n, len(d)))
means = d[idx].mean(axis=1)
return m, float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5))
a = np.asarray(arrs[0], dtype=np.float64)
b = np.asarray(arrs[1], dtype=np.float64)
m = float(a.mean() - b.mean())
if max(len(a), len(b)) > BOOT_MAX:
se = float(np.sqrt(a.var(ddof=1) / len(a) + b.var(ddof=1) / len(b)))
return m, m - 1.96 * se, m + 1.96 * se
rng = np.random.default_rng(seed)
ia = rng.integers(0, len(a), size=(n, len(a)))
ib = rng.integers(0, len(b), size=(n, len(b)))
means = a[ia].mean(axis=1) - b[ib].mean(axis=1)
return m, float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5))
def boot_unpaired(a, b):
if not a or not b:
return None, None, None
return _boot_ci([a, b], paired=False)
def boot_paired(d):
if not d:
return None, None, None
return _boot_ci(d, paired=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--a", required=True, help="候选 run 的 tag")
ap.add_argument("--b", default="orig_full", help="基线 run 的 tag")
ap.add_argument("--out", default=None)
ap.add_argument("--min-n", type=int, default=1)
ap.add_argument("--id-map", default=f"{V5}/data/pack_id_map.json")
a = ap.parse_args()
id_map = {}
if os.path.exists(a.id_map):
id_map = json.load(open(a.id_map))
print(f"[id-map] {len(id_map)} 条定位符映射(用于按样本配对)")
A = load(a.a, id_map)
B = load(a.b, id_map)
cohorts = sorted(set(A) | set(B))
print(f"A={a.a} B={a.b} cohorts={len(cohorts)}\n")
rows = []
for c in cohorts:
da, db = A.get(c, {}), B.get(c, {})
common = sorted(set(da) & set(db))
paired = [(da[s][1], db[s][1]) for s in common if da[s][1] is not None and db[s][1] is not None]
va = [v[1] for v in da.values() if v[1] is not None]
vb = [v[1] for v in db.values() if v[1] is not None]
if len(va) < a.min_n or len(vb) < a.min_n:
continue
ma, mb = mean(va), mean(vb)
if paired and len(paired) >= 0.5 * min(len(va), len(vb)):
d, lo, hi = boot_paired([p[0] - p[1] for p in paired])
kind = "paired"
npair = len(paired)
# 关键(2026-10-21 修): 配对时 A/B 的均值必须都取**同一批 id**,
# 否则 A(小样本 pilot)的均值和 B(全量)的均值是两个不同总体,
# Δ 里混进了 A 子集的抽样噪声 -> 分母写 n_b=183706 但 A 只有 2500 条。
ma = mean([p[0] for p in paired])
mb = mean([p[1] for p in paired])
else:
d, lo, hi = boot_unpaired(va, vb)
kind = "unpaired"
npair = 0
rows.append({
"cohort": c, "n_a": len(va), "n_b": len(vb), "npair": npair,
"teds_s_a": round(ma, 4), "teds_s_b": round(mb, 4),
"delta": round(ma - mb, 4),
"ci_lo": round(float(lo), 4), "ci_hi": round(float(hi), 4), "ci_kind": kind,
"sig": bool((lo > 0) or (hi < 0)),
})
# 全量合计(按样本数加权,也就是所有样本的池化均值差)
all_a = [v[1] for c in A for v in A[c].values() if v[1] is not None]
all_b = [v[1] for c in B for v in B[c].values() if v[1] is not None]
d, lo, hi = boot_unpaired(all_a, all_b)
total = {
"n_a": len(all_a), "n_b": len(all_b),
"teds_s_a": round(mean(all_a), 5), "teds_s_b": round(mean(all_b), 5),
"delta": round(mean(all_a) - mean(all_b), 5),
"ci_lo": round(lo, 5), "ci_hi": round(hi, 5),
}
# 配对合计(2026-10-21 补): 同一批 sample_id 上 A−B 的均值。
# 上面的 delta 是"A 的样本集均值 − B 的样本集均值", 当 A 是 pilot 小样本、
# B 是全量时, 这个差值里混着 A 的抽样噪声(2500 条约 ±0.004),
# 会让"退化了多少"被系统性夸大/缩小。配对差没有这个问题。
paired_all = []
for c in cohorts:
da, db = A.get(c, {}), B.get(c, {})
for s in set(da) & set(db):
if da[s][1] is not None and db[s][1] is not None:
paired_all.append((da[s][1], db[s][1]))
if paired_all:
diffs = [p[0] - p[1] for p in paired_all]
_d, plo, phi = boot_paired(diffs)
total["npair"] = len(paired_all)
total["teds_s_a_paired"] = round(mean([p[0] for p in paired_all]), 5)
total["teds_s_b_paired"] = round(mean([p[1] for p in paired_all]), 5)
total["delta_paired"] = round(mean(diffs), 5)
total["ci_lo_paired"] = round(float(plo), 5)
total["ci_hi_paired"] = round(float(phi), 5)
total["sig_paired"] = bool((plo > 0) or (phi < 0))
# 按 cohort 加权(每个 cohort 等权,跟「17 源里涨跌几个」这种口径一致)
if rows:
total["delta_cohort_mean"] = round(statistics.fmean(r["delta"] for r in rows), 5)
print(f"{'cohort':22s} {'n_a':>7s} {'n_b':>7s} {'A TEDS-S':>9s} {'B TEDS-S':>9s} "
f"{'Δ':>8s} {'95%CI':>18s} 显著")
for r in sorted(rows, key=lambda x: x["delta"]):
print(f"{r['cohort']:22s} {r['n_a']:7d} {r['n_b']:7d} {r['teds_s_a']:9.4f} "
f"{r['teds_s_b']:9.4f} {r['delta']:+8.4f} "
f"[{r['ci_lo']:+.4f},{r['ci_hi']:+.4f}] {r['ci_kind'][:3]} "
f"{'YES' if r['sig'] else ''}")
print(f"\n合计(按样本): A {total['teds_s_a']} B {total['teds_s_b']} "
f"Δ {total['delta']:+.5f} 95%CI [{total['ci_lo']:+.5f},{total['ci_hi']:+.5f}]")
if "delta_paired" in total:
print(f"合计(配对同 id, n={total['npair']}): A {total['teds_s_a_paired']} "
f"B {total['teds_s_b_paired']} Δ {total['delta_paired']:+.5f} "
f"95%CI [{total['ci_lo_paired']:+.5f},{total['ci_hi_paired']:+.5f}]"
f"{' 显著' if total['sig_paired'] else ''}")
if "delta_cohort_mean" in total:
print(f"合计(每 cohort 等权): Δ {total['delta_cohort_mean']:+.5f}")
n_sig = sum(1 for r in rows if r["sig"])
print(f"显著变好的 cohort: {sum(1 for r in rows if r['sig'] and r['delta'] > 0)} / "
f"显著变差的: {sum(1 for r in rows if r['sig'] and r['delta'] < 0)} / 共 {len(rows)}")
out = a.out or f"{V5}/reports/compare_{a.a}_vs_{a.b}.json"
with open(out, "w", encoding="utf-8") as f:
json.dump({"a": a.a, "b": a.b, "total": total, "cohorts": rows}, f,
ensure_ascii=False, indent=2)
print(f"\n写出 {out}")
if __name__ == "__main__":
main()