feat(spatial): 跳数偏置、边内容进 value、证据回灌第二轮、学习温度

四件结构补齐,每件都有对应的失效模式:

- 跳数偏置:原来只靠 no-position 的注意力,实体顺序被打乱会让输出漂移。
  改为按截断最短路分桶的注意力偏置(HOP_MAX=4),并遵守干预语义——被切掉的
  边不参与连通,否则"剪掉主干后是否还连通"的跳数本身就是错的。
- 边内容进 value:边类型此前只是注意力偏置,只能表达"看那边",不能表达
  "那是一个 0.8 的接触面、锁的是 tz 轴"。现在把入射边的特征投影后累加进实体
  的 value,接触面积由两端 box 重叠算出,并按单位归一化。
- 证据回灌:第一轮选出 top-k 边作为候选凭证,第二轮让所有实体都能注意到
  自己所在的那张凭证。此前证据头和答案头看的根本不是同一个对象。
- 学习温度:答案/变化/证据 logits 统一除以 exp(log_temp),并在评估里加 ECE。
  只报准确率的话,置信度 0.99 而正确率 0.72 和直接报 0.72 是同一个数。

另外:把边偏置的累加改成扁平 index_put_(accumulate),平行边不再互相覆盖;
新增 configs/cross.json(训练 cond.p1/area.sup2/dof.c6,验证 held-out 家族)。
This commit is contained in:
liuhuajie committed 2026-12-03 18:14:19 +08:00
1 parent f31288bf06
commit 085ad1415f
5 files changed
+318 -69

No files matched your search

+35 -6
View File
@@ -35,7 +35,8 @@ def make_batch(families, seed: int, step: int, batch_size: int):
def batch_loss(model, tensors):
out = model(tensors["feat"], tensors["pad_mask"], tensors["edge_index"],
tensors["edge_type"], tensors["edge_mask"], tensors["q_ents"], tensors["q_kind"],
tensors.get("edit_op"), tensors.get("edit_idx"), tensors.get("edge_removed"))
tensors.get("edit_op"), tensors.get("edit_idx"), tensors.get("edge_removed"),
tensors.get("edge_feat"))
l_ans = F.cross_entropy(out["answer"], tensors["answer"])
l_chg = F.cross_entropy(out["change"], tensors["change"])
ev_logits = out["evidence"][tensors["edge_mask"]]
@@ -43,7 +44,28 @@ def batch_loss(model, tensors):
l_ev = F.binary_cross_entropy_with_logits(ev_logits, ev_target) if ev_logits.numel() else l_ans * 0
total = l_ans + 0.5 * l_chg + 0.5 * l_ev
return total, {"answer": float(l_ans.detach()), "change": float(l_chg.detach()),
"evidence": float(l_ev.detach())}, out
"evidence": float(l_ev.detach()),
"temp": float(out["temp"])}, out
def _ece(probs, correct, n_bin: int = 5) -> float:
"""Top-label expected calibration error.
Accuracy alone cannot show a miscalibrated head: a model that answers every
row with confidence 0.99 and is right 72% of the time scores the same
accuracy as one that says 0.72. The temperature is only meaningful if this
number is reported next to it.
"""
conf = probs.max(-1).values
hit = (probs.argmax(-1) == correct).float()
total = 0.0
for b in range(n_bin):
lo, hi = b / n_bin, (b + 1) / n_bin
m = (conf > lo) & (conf <= hi) if b else (conf <= hi)
n = int(m.sum())
if n:
total += n * abs(float(hit[m].mean()) - float(conf[m].mean()))
return total / max(1, probs.size(0))
@torch.no_grad()
@@ -78,6 +100,7 @@ def evaluate(model, families, seed: int, n: int, max_entities: int = 32) -> dict
valid += int(bool(picked) and checker.validate_evidence(sc.full, sc.query, picked))
model.train()
ece = _ece(torch.softmax(out["answer"], -1), tensors["answer"])
return {
"answer_acc": correct / max(1, len(answerable)),
"answerable": len(answerable),
@@ -86,6 +109,8 @@ def evaluate(model, families, seed: int, n: int, max_entities: int = 32) -> dict
"change_acc": chg_correct / max(1, len(chg_rows)),
"evidence_valid": valid / max(1, total),
"n_true_pred": total,
"ece": ece,
"temp": float(out["temp"]),
"loss": losses,
}
@@ -104,13 +129,18 @@ def save(path: str, model, opt, step: int, config: dict):
os.replace(tmp, path) # atomic: a crash leaves the old file intact
def _build(m: dict) -> RelationBackbone:
return RelationBackbone(d=m["d"], n_layer=m["n_layer"], n_head=m["n_head"],
dropout=m["dropout"], max_entities=m["max_entities"],
rounds=m.get("rounds", 2), n_evidence=m.get("n_evidence", 4))
def load(path: str, device="cpu"):
# always restore on CPU: map_location=device would drag the RNG state (a
# ByteTensor) onto the GPU, and set_rng_state only accepts a CPU one
ck = torch.load(path, map_location="cpu", weights_only=False)
cfg = ck["config"]["model"]
model = RelationBackbone(d=cfg["d"], n_layer=cfg["n_layer"], n_head=cfg["n_head"],
dropout=cfg["dropout"], max_entities=cfg["max_entities"])
model = _build(cfg)
model.load_state_dict(ck["model"])
opt = torch.optim.AdamW(model.parameters(), lr=ck["config"]["optim"]["lr"],
weight_decay=ck["config"]["optim"]["weight_decay"])
@@ -141,8 +171,7 @@ def run(config: dict, resume: bool = False, steps: int = None, verbose: bool = T
print(f"resume from step {start}")
else:
m = config["model"]
model = RelationBackbone(d=m["d"], n_layer=m["n_layer"], n_head=m["n_head"],
dropout=m["dropout"], max_entities=m["max_entities"])
model = _build(m)
opt = torch.optim.AdamW(model.parameters(), lr=config["optim"]["lr"],
weight_decay=config["optim"]["weight_decay"])
start = 0