File size: 10,343 Bytes
4968ea3 | 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 | """跨切分消融的评测结果分析器(读 11_eval 产出的 data/eval/*.jsonl)。
干两件既有单模型 stats.json 给不了的事:
1. **横向对比表**:把 by-query 2:1 / 1:2 + by-user 2:1 / 1:2 各自的 SFT 与 DAPO
checkpoint 的 judge_acc / EM / F1 / strategy / hallucination / cost 并排,一眼看
「翻转比例」「按 user 解耦」「SFT→DAPO 增量」三个对比。
2. **DAPO seen / unseen 拆分(by-user 实验的核心问题)**:dataset_eval100 的 308 条
query 每一条要么属于该切分的 RL 训练集(DAPO 见过该 query)、要么属于 SFT 训练集
(DAPO 没在这条上更新过)。按 user 切分时 SFT/RL 用户 disjoint → 「unseen」= DAPO
从没见过的用户。拆开两组的 judge_acc,回答「DAPO 学到的策略能否迁移到没训过的用户」。
(by-query 切分用户重叠,unseen 只是 query 级 held-out,仍作参考但解释力弱。)
用法:
python scripts/train/analyze_eval_splits.py # 全部 + CSV
python scripts/train/analyze_eval_splits.py --eval-dir data/eval
"""
import argparse
import csv
import json
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src.evaluation.eval_metrics import aggregate
from src.utils import load_json, setup_logger
logger = setup_logger(__name__)
def _r(p):
return p if os.path.isabs(p) else os.path.join(PROJECT_ROOT, p)
# 每个被评 checkpoint: (展示名, eval jsonl, 该切分的 split 目录). split 目录用来判 seen/unseen
# 和 by-user(by-user 切分的 rl/sft 是 disjoint 用户). 顺序即对比表行序。
SPLIT_DIR = {
"1to2": "data/processed/metamem_5k/splits_1to2", # by-query 1:2
"bu_2to1": "data/processed/metamem_5k/splits_bu_2to1", # by-user 2:1
"bu_1to2": "data/processed/metamem_5k/splits_bu_1to2", # by-user 1:2
"2to1": "data/processed/metamem_5k/splits", # by-query 2:1 (原始,SFT 已评)
}
# by-user 切分用户 disjoint → unseen 解释力强; by-query 用户重叠 → 仅 query 级 held-out
BY_USER = {"bu_2to1", "bu_1to2"}
# 🔴 dataset_eval100 的 query 不带 ms_label → 11_eval 写出的记录 oracle_ms 全 None →
# aggregate 的 strategy_accuracy / over·under_retrieval / hallucination / by_ms 全部失效
# (核心 MetaMem 指标). ms_label 在 data/labeled/ms_labels/<model>/<uid>/<qid>_label.json
# 已存在 → 在分析期按 query_id 回填 oracle_ms,把这些指标点亮(不动评测产出本身)。
MS_LABEL_DIR = "data/labeled/ms_labels/Qwen2.5-7B-Instruct"
def backfill_oracle_ms(recs, ms_dir):
"""就地回填 oracle_ms(若记录里已是 None). 返回命中数."""
hit = 0
for r in recs:
if r.get("oracle_ms"):
hit += 1
continue
p = os.path.join(ms_dir, r.get("user_id", ""), f'{r.get("query_id")}_label.json')
if os.path.exists(p):
try:
r["oracle_ms"] = load_json(p)["ms_label"]
hit += 1
except Exception:
pass
return hit
ROWS = [
# (stage, split_tag, eval_jsonl_basename)
("sft", "2to1", "eval_metamem_trainset_qwen25_sft_lora"), # 既有(已跑)
("sft", "2to1", "eval_metamem_trainset_qwen25_sft_full"), # 既有(已跑)
("sft", "1to2", "eval_trainset_qwen25_sft_lora_1to2"),
("sft", "1to2", "eval_trainset_qwen25_sft_full_1to2"),
("sft", "bu_2to1", "eval_trainset_qwen25_sft_lora_bu_2to1"),
("sft", "bu_2to1", "eval_trainset_qwen25_sft_full_bu_2to1"),
("sft", "bu_1to2", "eval_trainset_qwen25_sft_lora_bu_1to2"),
("sft", "bu_1to2", "eval_trainset_qwen25_sft_full_bu_1to2"),
("dapo", "1to2", "eval_trainset_qwen25_dapo_lora_1to2"),
("dapo", "1to2", "eval_trainset_qwen25_dapo_full_1to2"),
("dapo", "bu_2to1", "eval_trainset_qwen25_dapo_lora_bu_2to1"),
("dapo", "bu_2to1", "eval_trainset_qwen25_dapo_full_bu_2to1"),
("dapo", "bu_1to2", "eval_trainset_qwen25_dapo_lora_bu_1to2"),
("dapo", "bu_1to2", "eval_trainset_qwen25_dapo_full_bu_1to2"),
]
def _mode(name):
return "full" if "_full" in name else "lora"
def load_records(path):
recs = []
with open(path) as f:
for line in f:
line = line.strip()
if line:
recs.append(json.loads(line))
return recs
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--eval-dir", default="data/eval")
ap.add_argument("--csv", default="data/eval/splits_comparison.csv")
ap.add_argument("--ms-dir", default=MS_LABEL_DIR,
help="ms_label dir to backfill oracle_ms (lights up strategy/by_ms metrics)")
args = ap.parse_args()
eval_dir = _r(args.eval_dir)
ms_dir = _r(args.ms_dir)
# cache split membership (rl_ids / sft_ids) per tag
split_cache = {}
for tag, d in SPLIT_DIR.items():
dd = _r(d)
try:
rl = set(load_json(os.path.join(dd, "rl_ids.json")))
sft = set(load_json(os.path.join(dd, "sft_ids.json")))
split_cache[tag] = (rl, sft)
except Exception as e:
logger.warning(f"split {tag} ids missing ({d}): {e}")
split_cache[tag] = (set(), set())
table = []
for stage, tag, base in ROWS:
path = os.path.join(eval_dir, base + ".jsonl")
if not os.path.exists(path):
logger.info(f"skip (no eval jsonl yet): {base}")
continue
recs = load_records(path)
if not recs:
continue
n_ms = backfill_oracle_ms(recs, ms_dir) # light up strategy/by_ms (oracle_ms None otherwise)
rl_ids, sft_ids = split_cache.get(tag, (set(), set()))
# tag each record
seen = [r for r in recs if r.get("query_id") in rl_ids] # DAPO trained on this query
unseen = [r for r in recs if r.get("query_id") in sft_ids] # DAPO never updated on it
overall = aggregate(recs)
row = {
"model": base, "stage": stage, "split": tag, "mode": _mode(base),
"n": overall["n"],
"judge_acc": overall.get("judge_acc"),
"judge_correct": overall.get("judge_correct_rate"),
"em": round(overall["em"], 4), "f1": round(overall["f1"], 4),
"strategy_acc": overall.get("strategy_accuracy"),
"over_retr": overall.get("over_retrieval_rate"),
"under_retr": overall.get("under_retrieval_rate"),
"hallu": overall.get("hallucinated_rate"),
"avg_retr_calls": overall.get("avg_retrieval_calls"),
"n_seen": len(seen), "n_unseen": len(unseen),
"judge_seen": aggregate(seen).get("judge_acc") if seen else None,
"judge_unseen": aggregate(unseen).get("judge_acc") if unseen else None,
"by_user": tag in BY_USER,
"judge_by_ms": overall.get("judge_by_ms") or {},
}
table.append(row)
if not table:
logger.warning("没有可分析的 eval jsonl(模型还没评)。先跑 run_eval_splits.sh。")
return
# ---- 1. 横向对比表 ----
def fmt(v):
return " — " if v is None else f"{v:.3f}"
print("\n" + "=" * 120)
print("跨切分对比(评测集 dataset_eval100, 100 用户 / 308 QA, 同集可比)")
print("=" * 120)
hdr = (f"{'model':52s} {'stage':4s} {'split':8s} {'mode':4s} "
f"{'judge':>6s} {'corr':>6s} {'EM':>6s} {'F1':>6s} {'strat':>6s} {'hallu':>6s}")
print(hdr); print("-" * 120)
for r in table:
print(f"{r['model']:52s} {r['stage']:4s} {r['split']:8s} {r['mode']:4s} "
f"{fmt(r['judge_acc']):>6s} {fmt(r['judge_correct']):>6s} {fmt(r['em']):>6s} "
f"{fmt(r['f1']):>6s} {fmt(r['strategy_acc']):>6s} {fmt(r['hallu']):>6s}")
# ---- 2. DAPO seen / unseen 拆分(只对 DAPO 行有意义) ----
print("\n" + "=" * 120)
print("DAPO seen(RL训练过该query) vs unseen(仅SFT见过) judge_acc 拆分")
print(" ⚠️ by-user 切分: unseen = DAPO 从没训过的【用户】(SFT/RL 用户 disjoint) → 真·泛化")
print(" ⚠️ by-query 切分: 用户重叠, unseen 仅 query 级 held-out → 解释力弱,仅参考")
print("=" * 120)
print(f"{'model':52s} {'by_user':7s} {'n_seen':>6s} {'judge_seen':>11s} "
f"{'n_unseen':>8s} {'judge_unseen':>13s} {'Δ(seen-unseen)':>15s}")
print("-" * 120)
for r in table:
if r["stage"] != "dapo":
continue
js, ju = r["judge_seen"], r["judge_unseen"]
delta = (f"{js - ju:+.3f}" if (js is not None and ju is not None) else " — ")
print(f"{r['model']:52s} {str(r['by_user']):7s} {r['n_seen']:>6d} {fmt(js):>11s} "
f"{r['n_unseen']:>8d} {fmt(ju):>13s} {delta:>15s}")
# ---- 2b. 按 MS 的 judge_acc(校准信号: 期望 SM > PM > VM > NM) ----
print("\n" + "=" * 120)
print("judge_acc by FIR state(校准信号: 模型记得越多答得越准 → 期望 SM ≥ PM ≥ VM ≥ NM)")
print("=" * 120)
print(f"{'model':52s} {'split':8s} {'mode':4s} {'SM':>7s} {'PM':>7s} {'VM':>7s} {'NM':>7s}")
print("-" * 120)
for r in table:
bm = r["judge_by_ms"]
print(f"{r['model']:52s} {r['split']:8s} {r['mode']:4s} "
f"{fmt(bm.get('SM')):>7s} {fmt(bm.get('PM')):>7s} "
f"{fmt(bm.get('VM')):>7s} {fmt(bm.get('NM')):>7s}")
# ---- 3. CSV ----
csv_path = _r(args.csv)
os.makedirs(os.path.dirname(csv_path), exist_ok=True)
# flatten judge_by_ms into scalar columns; drop the dict itself
fields = [k for k in table[0].keys() if k != "judge_by_ms"] + \
["judge_SM", "judge_PM", "judge_VM", "judge_NM"]
with open(csv_path, "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
for r in table:
bm = r.get("judge_by_ms") or {}
row = {k: v for k, v in r.items() if k != "judge_by_ms"}
row.update({"judge_SM": bm.get("SM"), "judge_PM": bm.get("PM"),
"judge_VM": bm.get("VM"), "judge_NM": bm.get("NM")})
w.writerow(row)
print(f"\nCSV → {csv_path}")
if __name__ == "__main__":
main()
|