feat(spatial): 按家族拆开的诊断表,把"答对"和"给出理由"分开报

聚合指标会把最关键的对比藏起来:模型可以在 held-out 家族上答案准确率 1.000,
同时一次都不肯弃权、并且它给出的凭证五次里错四次。只看准确率区分不了"学到规则"
和"学到这个家族的标签分布"。

report 每行分开报四件事:可判行的准确率、不可判行的弃权率、它敢断言时的凭证
有效率、以及平均置信度。
This commit is contained in:
liuhuajie committed 2026-12-03 18:17:30 +08:00
1 parent 085ad1415f
commit 03e8db3f64
2 files changed
+99 -1

No files matched your search

+10 -1
View File
@@ -178,16 +178,25 @@ def cmd_eval(args) -> int:
return 0
def cmd_report(args) -> int:
from . import report
report.report(args.config, n=args.n)
return 0
def main(argv=None) -> int:
p = argparse.ArgumentParser(prog="spatial")
sub = p.add_subparsers(dest="cmd", required=True)
for name, fn in (("smoke", cmd_smoke), ("train", cmd_train), ("eval", cmd_eval)):
for name, fn in (("smoke", cmd_smoke), ("train", cmd_train), ("eval", cmd_eval),
("report", cmd_report)):
sp = sub.add_parser(name)
sp.add_argument("--config", default=os.path.join(os.path.dirname(__file__), "configs", "smoke.json"))
if name != "eval":
sp.add_argument("--steps", type=int, default=None)
if name == "train":
sp.add_argument("--resume", action="store_true")
if name == "report":
sp.add_argument("--n", type=int, default=128)
sp.set_defaults(fn=fn)
args = p.parse_args(argv)
return args.fn(args)
+89
View File
@@ -0,0 +1,89 @@
"""Per-family report.
The aggregate metrics in ``train.evaluate`` hide the only comparison that
matters: a model can score 1.000 answer accuracy on a held-out family while
never once abstaining and while its certificates are wrong four times out of
five. Answer accuracy alone cannot tell "learned the rule" from "learned the
label distribution of this family".
So each row here reports the four things separately:
* ``acc`` -- accuracy on rows the observation can decide
* ``abst`` -- fraction of undecidable rows the model actually refuses
* ``cert`` -- certificate validity among the rows it calls "true"
* ``conf`` -- mean top-1 confidence, which is what ``cert`` and ``abst`` are
fighting against
"""
from __future__ import annotations
import json
import os
import torch
from . import checker, generator
from .data import collate
from .train import load
ANSWERS = ("true", "false", "unknown")
@torch.no_grad()
def family_row(model, family: str, seed: int, n: int, max_entities: int = 32) -> dict:
batch = [generator.make(family, seed=seed, index=i) for i in range(n)]
device = next(model.parameters()).device
t = collate(batch, max_entities)
t = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in t.items()}
out = model(t["feat"], t["pad_mask"], t["edge_index"], t["edge_type"], t["edge_mask"],
t["q_ents"], t["q_kind"], t["edit_op"], t["edit_idx"], t["edge_removed"],
t["edge_feat"])
pred = out["answer"].argmax(-1).tolist()
conf = torch.softmax(out["answer"], -1).max(-1).values.tolist()
probs = torch.sigmoid(out["evidence"])
ans_rows = [i for i, sc in enumerate(batch) if sc.label.answer != "unknown"]
unk_rows = [i for i, sc in enumerate(batch) if sc.label.answer == "unknown"]
hit = sum(1 for i in ans_rows if pred[i] == ANSWERS.index(batch[i].label.answer))
abst = sum(1 for i in unk_rows if pred[i] == 2)
# a certificate is only asked of rows the model is willing to assert
valid = total = 0
for i, sc in enumerate(batch):
if pred[i] != 0:
continue
ids = [e.eid for e in sc.obs.edges]
picked = [ids[k] for k in range(len(ids)) if probs[i, k] > 0.5]
total += 1
valid += int(bool(picked) and checker.validate_evidence(sc.full, sc.query, picked))
return {
"family": family,
"n": len(batch),
"decidable": len(ans_rows),
"unknown": len(unk_rows),
"acc": round(hit / max(1, len(ans_rows)), 3),
"abst": round(abst / max(1, len(unk_rows)), 3),
"cert": round(valid / max(1, total), 3),
"n_true": total,
"conf": round(sum(conf) / len(conf), 3),
}
def report(config_path: str, n: int = 128) -> None:
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ckpt = os.path.join(root, "out_spatial", os.path.basename(config_path).replace(".json", ""),
"ckpt.pt")
model, _, step, cfg = load(ckpt, "cuda" if torch.cuda.is_available() else "cpu")
model.eval()
print(f"step {step} families: train={cfg['data']['train_families']} "
f"val={cfg['data']['val_families']}")
head = f"{'family':11s} {'n':>3s} {'dec':>4s} {'unk':>4s} {'acc':>5s} {'abst':>5s} " \
f"{'cert':>5s} {'#true':>5s} {'conf':>5s}"
print(head)
print("-" * len(head))
for fam in generator.FAMILIES:
r = family_row(model, fam, cfg["seed"], n, cfg["model"]["max_entities"])
print(f"{r['family']:11s} {r['n']:3d} {r['decidable']:4d} {r['unknown']:4d} "
f"{r['acc']:5.3f} {r['abst']:5.3f} {r['cert']:5.3f} {r['n_true']:5d} "
f"{r['conf']:5.3f}")