From 03e8db3f649a6720b7d02d94706342994c4c7ef4 Mon Sep 17 00:00:00 2001 From: lhj <403133128@qq.com> Date: Thu, 3 Dec 2026 18:17:30 +0800 Subject: [PATCH] =?UTF-8?q?feat(spatial):=20=E6=8C=89=E5=AE=B6=E6=97=8F?= =?UTF-8?q?=E6=8B=86=E5=BC=80=E7=9A=84=E8=AF=8A=E6=96=AD=E8=A1=A8=EF=BC=8C?= =?UTF-8?q?=E6=8A=8A"=E7=AD=94=E5=AF=B9"=E5=92=8C"=E7=BB=99=E5=87=BA?= =?UTF-8?q?=E7=90=86=E7=94=B1"=E5=88=86=E5=BC=80=E6=8A=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 聚合指标会把最关键的对比藏起来:模型可以在 held-out 家族上答案准确率 1.000, 同时一次都不肯弃权、并且它给出的凭证五次里错四次。只看准确率区分不了"学到规则" 和"学到这个家族的标签分布"。 report 每行分开报四件事:可判行的准确率、不可判行的弃权率、它敢断言时的凭证 有效率、以及平均置信度。 --- spatial/cli.py | 11 +++++- spatial/report.py | 89 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 spatial/report.py diff --git a/spatial/cli.py b/spatial/cli.py index 5a75b48..2174f35 100644 --- a/spatial/cli.py +++ b/spatial/cli.py @@ -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) diff --git a/spatial/report.py b/spatial/report.py new file mode 100644 index 0000000..8a98e52 --- /dev/null +++ b/spatial/report.py @@ -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}")