feat(spatial): 悬空关系与未知槽位,让"缺哪一段"落到位置而不是计数

此前"少了一条接触"只是全局计数,模型只能说"我在猜";它无法区分"目标根本没支撑"
和"目标的那条支撑被挡住了"。现在:
- Observation.dangling:一端可见、另一端不可见的关系,锚在可见那一端,不带身份。
  它说的是无知挂在哪儿,不是答案是什么。
- 模型多一个未知槽位(位置 1),悬空边的远端指向它;有悬空关系的锚定实体与它
  相距一跳。一条链走到它上面,就是一条链走进了问题。
- 悬空边不参与连通计算、不进入实体的入射边求和、边特征里带 dangling 标志。
- 新增 area.free 家族:T 的唯一接触连到一个自身悬空的块,什么也没藏、什么也不悬空,
  所以"没有支撑"是事实而非缺口,正确答案是 false,弃权才是错的。
  它与 area.sup2h 构成最小对:同样是一条接触,一个通到未知、一个通到死路。
This commit is contained in:
liuhuajie committed 2026-12-03 18:49:45 +08:00
1 parent 68380900ce
commit 40f6bb52fa
8 files changed
+251 -141

No files matched your search

+89 -89
View File
@@ -1,89 +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"], 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}")
"""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"], t["dangling"])
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}")