same-pinout / src /score.py
shimmerhuang's picture
SamePinout v0: 204 questions, preregistered evaluation of 20 models, raw runs, audit, scripts
1b2c3dd verified
Raw History Blame Contribute Delete
16.2 kB
#!/usr/bin/env python3
"""判分。规则与预注册「判定规则」一一对应,冻结后不改。
用法:score.py <questions.jsonl> <runs_dir> [--audit <人工核对记录.tsv>] [--json]
runs_dir:run_eval.py 的输出目录(<模型>.<closed|open>.jsonl 和同名 .manifest.json)
人工核对记录:一行一题,制表符分隔:题号 <TAB> ok|wrong|unknown <TAB> 依据(必填)。wrong 的题从计分里剔除。
"""
import collections
import datetime
import hashlib
import json
import pathlib
import re
import sys
import urllib.parse
sys.path.insert(0, str(pathlib.Path(__file__).parent))
import sample_check # noqa: E402
VOID_FORMAT = 0.20 # 格式失败率超过这个数,这一栏作废
VOID_WRONG = 7 # 人工核出库有错的题达到这个数,整个实验作废
CHANNEL_ORDER = ["api", "claude-cli", "codex-cli"]
CUTOFF = datetime.datetime.fromisoformat("2026-12-18T23:59:59+08:00")
# 验证性名单:模型名 → (通道, 接口)。甲通道的接口按 https 地址的主机名精确比对;乙通道的接口就是通道名。
# 不在这里的栏只进探索性结果。
CONFIRMATORY = {
"deepseek-v4-pro": ("api", "api.deepseek.com"), "deepseek-flash": ("api", "api.deepseek.com"),
"kimi-k3.1-pro": ("api", "ollama.com"), "glm-5.4": ("api", "ollama.com"), "gpt-oss:120b": ("api", "ollama.com"),
"gemma4:31b": ("api", "ollama.com"), "mistral-large-4": ("api", "ollama.com"), "nemotron-3-ultra": ("api", "ollama.com"),
"qwen/qwen4-max": ("api", "openrouter.ai"), "qwen/qwen3.8-flash": ("api", "openrouter.ai"),
"minimax/minimax-m4": ("api", "openrouter.ai"), "stepfun/step-5": ("api", "openrouter.ai"),
"x-ai/grok-4.7": ("api", "openrouter.ai"),
"google/gemma-3-4b-it": ("api", "openrouter.ai"), "meta-llama/llama-3.2-3b-instruct": ("api", "openrouter.ai"),
"mistralai/ministral-3b-2512": ("api", "openrouter.ai"),
"claude-fable-5-2": ("claude-cli", "claude-cli"), "claude-haiku-5-5": ("claude-cli", "claude-cli"),
"gpt-6.2-astra": ("codex-cli", "codex-cli"), "gpt-6.2-sol": ("codex-cli", "codex-cli"),
}
SMALL = ("google/gemma-3-4b-it", "meta-llama/llama-3.2-3b-instruct", "mistralai/ministral-3b-2512") # H3 的三个小模型
IDENTITY = ("model_requested", "setting", "channel", "questions_sha256", "prompts_sha256", "endpoint", "temperature")
def lenient_json(text):
"""宽松解析只限两件事:去掉代码块围栏;去掉 JSON 前后的文字。别的不救。"""
if not isinstance(text, str) or not text:
return None
t = re.sub(r"```[a-zA-Z]*", "", text).replace("```", "").strip()
i, j = t.find("{"), t.rfind("}")
if i < 0 or j <= i:
return None
try:
return json.loads(t[i:j + 1])
except Exception:
return None
def parse_answer(text):
"""返回 (same_pinout, set(different_pins));格式不对返回 None。
脚号只收字符串和整数;字符串去掉两端空白,整数转成字符串。小数、布尔、别的类型都算格式不对。"""
d = lenient_json(text)
if not isinstance(d, dict):
return None
s, p = d.get("same_pinout"), d.get("different_pins")
if not isinstance(s, bool) or not isinstance(p, list):
return None
if not all(isinstance(x, (str, int)) and not isinstance(x, bool) for x in p):
return None
return s, {str(x).strip() for x in p}
def bucket(n):
return "3-5" if n <= 5 else ("6-16" if n <= 16 else "17+")
def load_column(path, all_ids, q_sha, p_sha):
"""读一栏的 final 行并核对身份。任何对不上都停。"""
man_path = path.with_name(path.name[:-len(".jsonl")] + ".manifest.json")
if not man_path.exists():
sys.exit(f"停:{path.name} 没有 manifest。")
man = json.loads(man_path.read_text())
if man["questions_sha256"] != q_sha:
sys.exit(f"停:{path.name} 不是用这份题库跑的。")
if man["prompts_sha256"] != p_sha:
sys.exit(f"停:{path.name} 不是用这份提示词跑的。")
rows, counts = {}, collections.Counter()
for n, l in enumerate(open(path), 1):
try:
r = json.loads(l)
ev, qid = r["ev"], r["id"]
except Exception:
sys.exit(f"停:{path.name} 第 {n} 行不是完整的记录。")
if ev not in ("sent", "noresp", "unknown_outcome", "final") or qid not in all_ids:
sys.exit(f"停:{path.name} 第 {n} 行是不认识的记录,或者题号不在题库里。")
if qid in rows:
sys.exit(f"停:{path.name} 第 {n} 行:{qid} 已经有 final,之后不该再有记录。")
counts[ev] += 1
if ev != "final":
continue
for k in IDENTITY:
if r.get(k) != man.get(k):
sys.exit(f"停:{path.name} 第 {n} 行的 {k} 和 manifest 不一致。")
rows[qid] = r
man["_log_counts"] = dict(counts)
return man, rows
def metrics(rows, qs):
"""在给定的计分题上算全部指标。"""
n = len(qs)
fmt_fail = judge_ok = full_ok = truncated = tool_rows = tool_calls = 0
tp = fp = fn = 0 # 正类 =「排列不同」
f1_sum = f1_n = 0
by_bucket = collections.defaultdict(lambda: [0, 0, 0]) # 题数、判断对、整题全对
for q in qs:
gold_same = q["answer"]["same_pinout"]
gold_set = set(q["answer"]["different_pins"])
b = by_bucket[bucket(len(q["pins_a"]))]
b[0] += 1
r = rows.get(q["id"])
ans = parse_answer(r.get("content")) if r is not None else None
used_tool = bool(r and r.get("tool_calls"))
if r is not None:
truncated += r.get("finish_reason") == "length"
tool_rows += used_tool
tool_calls += r.get("tool_calls") or 0
if ans is None:
fmt_fail += 1 # 没跑到,或者格式不对
if ans is None or used_tool:
# 没有有效答案,或者调过工具:这题零分。工具违规不算进格式失败率。
if not gold_same:
fn += 1
f1_n += 1
continue
same, pins = ans
ok = same == gold_same
judge_ok += ok
b[1] += ok
if not gold_same and not same:
tp += 1
elif gold_same and not same:
fp += 1
elif not gold_same and same:
fn += 1
if ok and pins == gold_set:
full_ok += 1
b[2] += 1
if not gold_same:
inter = len(pins & gold_set)
pr = inter / len(pins) if pins else 0.0
rc = inter / len(gold_set)
f1_sum += 2 * pr * rc / (pr + rc) if pr + rc else 0.0
f1_n += 1
return {
"n": n, "base_rate_different": sum(1 for q in qs if not q["answer"]["same_pinout"]) / n,
"judge_acc": judge_ok / n,
"diff_precision": tp / (tp + fp) if tp + fp else None,
"diff_recall": tp / (tp + fn) if tp + fn else None,
"full_correct": full_ok / n,
"a_set_f1": f1_sum / f1_n if f1_n else None,
"format_fail": fmt_fail / n, "void": fmt_fail / n > VOID_FORMAT,
"tool_violation_questions": tool_rows, "tool_calls_total": tool_calls,
"truncated": truncated / n,
"by_pins": {k: {"n": v[0], "judge_acc": v[1] / v[0], "full_correct": v[2] / v[0]}
for k, v in sorted(by_bucket.items())},
}
def endpoint_is(endpoint, want):
"""乙通道:接口就是通道名。甲通道:必须是 https,且主机名与名单里写的完全相同。"""
if want in CHANNEL_ORDER:
return endpoint == want
u = urllib.parse.urlparse(str(endpoint))
return u.scheme == "https" and u.hostname == want and u.username is None
def score_column(man, rows, all_qs, qs):
"""all_qs:冻结的整份题库,用来判这一栏跑没跑完。qs:剔除后的计分题。"""
s = metrics(rows, qs)
missing = sum(1 for q in all_qs if q["id"] not in rows)
last = max((r["called_at"] for r in rows.values()), default=None,
key=lambda x: datetime.datetime.strptime(x, "%Y-%m-%dT%H:%M:%S%z"))
want = CONFIRMATORY.get(man["model_requested"])
in_list = bool(want and want[0] == man["channel"] and endpoint_is(man["endpoint"], want[1]))
in_time = bool(last and datetime.datetime.strptime(last, "%Y-%m-%dT%H:%M:%S%z") <= CUTOFF)
complete = missing == 0
why = [] if in_list else ["不在验证性名单(或通道、接口不是名单里写的)"]
why += [] if complete else [f"没跑完,缺 {missing} 题"]
why += [] if (in_time or not complete) else ["最后一题在截止日之后"]
why += ["格式失败率超过 20%,作废"] if s["void"] else []
s.update({
"model": man["model_requested"], "setting": man["setting"], "channel": man["channel"],
"endpoint": man["endpoint"], "temperature": man["temperature"],
"missing_of_full_set": missing, "complete": complete, "last_called_at": last,
"valid": complete and not s["void"],
"confirmatory": in_list and in_time and complete and not s["void"], "not_confirmatory_because": why,
"before_exclusion": {k: v for k, v in metrics(rows, all_qs).items() if k != "by_pins"},
"model_returned": dict(collections.Counter(str(r.get("model_returned")) for r in rows.values())),
"providers": dict(collections.Counter(str(r.get("provider")) for r in rows.values())),
"requests_without_response": man.get("_log_counts", {}).get("noresp", 0),
"requests_with_unknown_outcome": man.get("_log_counts", {}).get("unknown_outcome", 0),
})
return s
def load_audit(path, all_qs):
"""读人工核对记录。只收预注册抽出的那 30 题;每行都要有依据。"""
sample = set(sum(sample_check.sample(all_qs).values(), []))
recs = {}
for n, l in enumerate(open(path), 1):
if not l.strip() or l.startswith("#"):
continue
parts = l.rstrip("\n").split("\t")
if len(parts) < 3 or parts[1] not in ("ok", "wrong", "unknown") or not parts[2].strip():
sys.exit(f"停:核对记录第 {n} 行格式不对(要三列:题号、ok|wrong|unknown、依据)。")
if parts[0] not in sample:
sys.exit(f"停:核对记录第 {n} 行的 {parts[0]} 不在抽出的 30 题里。")
if parts[0] in recs:
sys.exit(f"停:核对记录里 {parts[0]} 出现两次。")
recs[parts[0]] = {"verdict": parts[1], "basis": parts[2].strip()}
return {"sha256": hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest(),
"sampled": len(sample), "checked": len(recs), "complete": set(recs) == sample,
"wrong": sorted(k for k, v in recs.items() if v["verdict"] == "wrong"),
"unknown": sorted(k for k, v in recs.items() if v["verdict"] == "unknown"),
"not_checked_yet": sorted(sample - set(recs)), "records": recs}
def main(argv):
q_path, runs_dir = pathlib.Path(argv[1]), pathlib.Path(argv[2])
q_sha = hashlib.sha256(q_path.read_bytes()).hexdigest()
p_sha = hashlib.sha256((pathlib.Path(__file__).parent / "prompts.py").read_bytes()).hexdigest()
all_qs = [json.loads(l) for l in open(q_path)]
all_ids = {q["id"] for q in all_qs}
audit = load_audit(argv[argv.index("--audit") + 1], all_qs) if "--audit" in argv else None
wrong = set(audit["wrong"]) if audit else set()
qs = [q for q in all_qs if q["id"] not in wrong]
if not qs:
sys.exit("停:剔除后没有题了。")
experiment_void = len(wrong) >= VOID_WRONG
audit_done = bool(audit and audit["complete"])
cols, seen = [], {}
for f in sorted(runs_dir.glob("*.jsonl")):
man, rows = load_column(f, all_ids, q_sha, p_sha)
key = (man["model_requested"], man["setting"])
if key in seen:
sys.exit(f"停:{seen[key]} 和 {f.name} 是同一个模型的同一种设置。一栏只认一个日志,不挑分高的。")
seen[key] = f.name
cols.append(score_column(man, rows, all_qs, qs))
cols.sort(key=lambda s: (CHANNEL_ORDER.index(s["channel"]), s["model"], s["setting"]))
conf = [s for s in cols if s["confirmatory"]]
c_closed = [s for s in conf if s["setting"] == "closed"]
c_open = [s for s in conf if s["setting"] == "open"]
small = [s for s in c_open if s["model"] in SMALL]
b1 = max(c_closed, key=lambda s: s["judge_acc"]) if c_closed else None
b2 = max(c_open, key=lambda s: s["full_correct"]) if c_open else None
status = ("整个实验作废,不出成立与否的结论" if experiment_void
else "正式" if audit_done else "暂定:30 题人工核对还没做完,不能当验证性结论发布")
hyp = {"status": status, "uses": "只用验证性的栏,剔除后的数字",
"confirmatory_columns": len(conf), "of_expected": 2 * len(CONFIRMATORY)}
if not experiment_void:
hyp.update({
"H1_closed_best_judge_acc": "未检验" if b1 is None else {"model": b1["model"], "value": b1["judge_acc"], "holds": b1["judge_acc"] < 0.80},
"H2_open_best_full_correct": "未检验" if b2 is None else {"model": b2["model"], "value": b2["full_correct"], "holds": b2["full_correct"] >= 0.95},
"H3_small_open_full_correct": "未检验" if not small else {"values": {s["model"]: s["full_correct"] for s in small}, "holds": all(s["full_correct"] < 0.80 for s in small)}})
if "--json" in argv:
print(json.dumps({"questions_sha256": q_sha, "prompts_sha256": p_sha, "audit": audit,
"experiment_void": experiment_void, "scored_questions": len(qs),
"hypotheses": hyp, "columns": cols}, ensure_ascii=False, indent=1))
return
def pct(x):
return " — " if x is None else f"{100 * x:5.1f}"
na = sum(1 for q in qs if not q["answer"]["same_pinout"])
print(f"题库 {q_sha[:12]} · 计分题数 {len(qs)}(排列不同 {na},排列相同 {len(qs) - na})· 人工核对剔除 {len(wrong)} 题")
if audit:
print(f"人工核对:抽 {audit['sampled']},已核 {audit['checked']},库有错 {len(audit['wrong'])},核不了 {len(audit['unknown'])},还没核 {len(audit['not_checked_yet'])}")
else:
print("人工核对:还没有记录")
if experiment_void:
print(f"!!库有错的题达到 {VOID_WRONG} 道:整个实验作废,下面的数字不能当结论。")
last = None
for s in cols:
if s["channel"] != last:
last = s["channel"]
print(f"\n── 通道 {last} ──")
print(f"{'模型':30s} {'设置':6s} {'温度':>4s} {'判断准':>6s} {'不同·精':>6s} {'不同·召':>6s} {'全对':>6s} {'A类F1':>6s} "
f"{'格式败':>6s} {'截断':>5s} {'工具题/次':>8s} | 按脚数判断准 3-5 / 6-16 / 17+ | 剔除前 判断准/全对 | 托管方 | 备注")
bp = " / ".join(pct(s["by_pins"][k]["judge_acc"]).strip() if k in s["by_pins"] else "—" for k in ("3-5", "6-16", "17+"))
be = s["before_exclusion"]
prov = ",".join(f"{k}×{v}" for k, v in s["providers"].items() if k != "None") or "—"
note = "验证性" if s["confirmatory"] else "探索性:" + ";".join(s["not_confirmatory_because"])
if s["requests_without_response"] or s["requests_with_unknown_outcome"]:
note += f";没返回的请求 {s['requests_without_response']} 次,结果不明的 {s['requests_with_unknown_outcome']} 次"
print(f"{s['model']:32s} {s['setting']:6s} {str(s['temperature']):>6s} {pct(s['judge_acc'])} {pct(s['diff_precision'])} "
f"{pct(s['diff_recall'])} {pct(s['full_correct'])} {pct(s['a_set_f1'])} {pct(s['format_fail'])} {pct(s['truncated'])} "
f"{s['tool_violation_questions']:>4d}/{s['tool_calls_total']:<4d} | {bp} | {pct(be['judge_acc']).strip()}/{pct(be['full_correct']).strip()} | {prov} | {note}")
print("\n" + json.dumps(hyp, ensure_ascii=False))
if __name__ == "__main__":
main(sys.argv)