Files
tiny-gpt/spatial/report.py
T
liuhuajie 08153b987d fix(spatial): 补上"观测自己承认缺失了什么"的输入,cond.p1/cond.p1h 不再是同一张量
hidden_layers 和 hidden_faces 一直只在 digest 里,没进过张量。于是
"不存在隐藏支路"和"有隐藏支路但在视野外"到达模型时是同一个输入、标签却相反
(前者 false,后者 unknown)。这不是欠拟合,是契约承诺了、张量化却丢掉了的信息。

现在把观测的"缺失声明"投影到 query token 上:隐藏层 1..3 指示位、未见面的数量、
"确有东西被隐藏"一位、场景规模。模型因此有机会说"我看不到决定这件事的那部分"。
2026-12-03 18:31:25 +08:00

90 lines
3.6 KiB
Python

"""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"], t["scene"])
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}")