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

+15
View File
@@ -0,0 +1,15 @@
{
"seed": 0,
"model": {
"d": 192, "n_layer": 4, "n_head": 6, "dropout": 0.1, "max_entities": 32,
"rounds": 2, "n_evidence": 4
},
"data": {
"train_families": ["cond.p1", "area.sup2", "dof.c6"],
"val_families": ["cond.p1h", "area.sup2h", "dof.c6h"],
"test_families": ["cond.p3h", "area.sup3", "dof.c6r"]
},
"optim": { "lr": 0.003, "weight_decay": 0.01, "steps": 1200, "batch": 32, "log_every": 200 },
"eval": { "n": 192 },
"out_dir": "out_spatial/cross"
}
+4 -1
View File
@@ -1,6 +1,9 @@
{ {
"seed": 0, "seed": 0,
"model": { "d": 192, "n_layer": 4, "n_head": 6, "dropout": 0.0, "max_entities": 32 }, "model": {
"d": 192, "n_layer": 4, "n_head": 6, "dropout": 0.0, "max_entities": 32,
"rounds": 2, "n_evidence": 4
},
"data": { "data": {
"train_families": ["cond.p3"], "train_families": ["cond.p3"],
"val_families": ["cond.p3"], "val_families": ["cond.p3"],
+41 -4
View File
@@ -11,8 +11,8 @@ import torch
from collections import deque from collections import deque
from .schema import ANSWERS, CHANGES, EDGE_KINDS, ENTITY_KINDS, Scenario from .schema import ANSWERS, CHANGES, DOF_AXES, EDGE_KINDS, ENTITY_KINDS, Scenario
from .model import FEAT_DIM, QUERY_KINDS from .model import EDGE_FEAT_DIM, FEAT_DIM, N_AXIS, N_EDGE, QUERY_KINDS
def _reach(edges, src: str, alive) -> set: def _reach(edges, src: str, alive) -> set:
@@ -74,6 +74,39 @@ def entity_features(sc: Scenario, e) -> list:
return f return f
def _contact_area(by_id: dict, ed, per_unit: int = 1) -> float:
"""Overlap area of two boxes, normalised so a unit change cannot move it.
Stability depends on how much material two blocks share, not on the fact
that they touch; without this the model has to recompute geometry from two
coordinate vectors that the value stream never even carried.
"""
a, b = by_id.get(ed.a), by_id.get(ed.b)
if a is None or b is None:
return 0.0
ba, bb = a.attrs.get("box"), b.attrs.get("box")
if not ba or not bb:
return 0.0
ox = min(ba[3], bb[3]) - max(ba[0], bb[0])
oy = min(ba[4], bb[4]) - max(ba[1], bb[1])
if ox <= 0 or oy <= 0:
return 0.0
return min(1.0, ox * oy / (400.0 * max(1, per_unit) ** 2))
def edge_features(sc: Scenario, ed, removed: bool) -> list:
f = [0.0] * EDGE_FEAT_DIM
f[EDGE_KINDS.index(ed.kind)] = 1.0
ax = ed.attrs.get("axis")
if ax in DOF_AXES:
f[N_EDGE + DOF_AXES.index(ax)] = 1.0
f[N_EDGE + N_AXIS] = 1.0 if removed else 0.0
f[N_EDGE + N_AXIS + 1] = ed.layer / 6.0
by_id = {e.eid: e for e in sc.obs.entities}
f[N_EDGE + N_AXIS + 2] = _contact_area(by_id, ed, sc.obs.units.get("per_unit", 1))
return f
def collate(batch, max_entities: int = 32): def collate(batch, max_entities: int = 32):
B = len(batch) B = len(batch)
N = max(1, max(len(sc.obs.entities) for sc in batch)) N = max(1, max(len(sc.obs.entities) for sc in batch))
@@ -86,6 +119,7 @@ def collate(batch, max_entities: int = 32):
pad_mask = torch.ones(B, N, dtype=torch.bool) pad_mask = torch.ones(B, N, dtype=torch.bool)
edge_index = torch.zeros(B, E, 2, dtype=torch.long) edge_index = torch.zeros(B, E, 2, dtype=torch.long)
edge_type = torch.zeros(B, E, dtype=torch.long) edge_type = torch.zeros(B, E, dtype=torch.long)
edge_feat = torch.zeros(B, E, EDGE_FEAT_DIM)
edge_mask = torch.zeros(B, E, dtype=torch.bool) edge_mask = torch.zeros(B, E, dtype=torch.bool)
evidence = torch.zeros(B, E) evidence = torch.zeros(B, E)
edge_removed = torch.zeros(B, E) edge_removed = torch.zeros(B, E)
@@ -102,14 +136,16 @@ def collate(batch, max_entities: int = 32):
feat[i, j] = torch.tensor(entity_features(sc, e)) feat[i, j] = torch.tensor(entity_features(sc, e))
pad_mask[i, j] = False pad_mask[i, j] = False
ev = evidence_target(sc) ev = evidence_target(sc)
removed_eid = (sc.query.edit or {}).get("edge")
for k, ed in enumerate(sc.obs.edges): for k, ed in enumerate(sc.obs.edges):
edge_index[i, k, 0] = ids.get(ed.a, 0) edge_index[i, k, 0] = ids.get(ed.a, 0)
edge_index[i, k, 1] = ids.get(ed.b, 0) edge_index[i, k, 1] = ids.get(ed.b, 0)
edge_type[i, k] = EDGE_KINDS.index(ed.kind) edge_type[i, k] = EDGE_KINDS.index(ed.kind)
edge_mask[i, k] = True edge_mask[i, k] = True
evidence[i, k] = 1.0 if ed.eid in ev else 0.0 evidence[i, k] = 1.0 if ed.eid in ev else 0.0
if (sc.query.edit or {}).get("edge") == ed.eid: rm = ed.eid == removed_eid
edge_removed[i, k] = 1.0 edge_removed[i, k] = 1.0 if rm else 0.0
edge_feat[i, k] = torch.tensor(edge_features(sc, ed, rm))
q_ents[i, 0] = ids.get(sc.query.a, -1) q_ents[i, 0] = ids.get(sc.query.a, -1)
q_ents[i, 1] = ids.get(sc.query.b, -1) q_ents[i, 1] = ids.get(sc.query.b, -1)
q_kind[i] = QUERY_KINDS.index(sc.query.kind) q_kind[i] = QUERY_KINDS.index(sc.query.kind)
@@ -130,6 +166,7 @@ def collate(batch, max_entities: int = 32):
return { return {
"feat": feat, "pad_mask": pad_mask, "feat": feat, "pad_mask": pad_mask,
"edge_index": edge_index, "edge_type": edge_type, "edge_mask": edge_mask, "edge_index": edge_index, "edge_type": edge_type, "edge_mask": edge_mask,
"edge_feat": edge_feat,
"q_ents": q_ents, "q_kind": q_kind, "q_ents": q_ents, "q_kind": q_kind,
"edit_op": edit_op, "edit_idx": edit_idx, "edit_op": edit_op, "edit_idx": edit_idx,
"edge_removed": edge_removed, "edge_removed": edge_removed,
+223 -58
View File
@@ -5,11 +5,22 @@ Differences from ``mm/model.py``, and why they are not negotiable here:
* **no causal mask** -- a query may sit on any entity and relations are * **no causal mask** -- a query may sit on any entity and relations are
symmetric; an autoregressive mask would make the answer depend on an symmetric; an autoregressive mask would make the answer depend on an
arbitrary serialisation order. arbitrary serialisation order.
* **edge types are attention biases** -- adjacency alone cannot express * **no positional encoding** -- entity order in a scene carries no meaning, so
"contact" vs "constraint" vs "conduct", and those three mean different things the only ordering signal is structural: a learned bias indexed by graph
for the same pair of nodes. hop distance. Renumbering the scene must not move the output.
* **edge types are attention biases *and* values** -- a bias alone says "look
this way" but never tells the token *what* the relation is (layer, contact
area, which axis a mate locks). Edge content is folded into the value stream
so an entity actually receives its incident relations.
* **one query token, not a token per entity** -- the output is about a query, * **one query token, not a token per entity** -- the output is about a query,
not about the next token. not about the next token.
* **two rounds of read-out** -- round 1 selects a few edges as a candidate
certificate, round 2 lets every entity attend to those edges. This is the
cheap version of "grab evidence, then decide"; without it the evidence head
and the answer head never see the same object.
* **a learned temperature** -- the answer/change/evidence logits are divided by
``exp(log_temp)``, so "unknown" is a decision made on a calibrated scale
rather than the argmax of an over-confident 3-way classifier.
The size is a smoke-test size (2 layers, 64 wide). The plan's 6/384 is a The size is a smoke-test size (2 layers, 64 wide). The plan's 6/384 is a
config change; nothing in this file assumes 64. config change; nothing in this file assumes 64.
@@ -22,13 +33,54 @@ import torch
import torch.nn as nn import torch.nn as nn
import torch.nn.functional as F import torch.nn.functional as F
from .schema import EDGE_KINDS, ENTITY_KINDS from .schema import DOF_AXES, EDGE_KINDS, ENTITY_KINDS
N_KIND = len(ENTITY_KINDS) N_KIND = len(ENTITY_KINDS)
N_EDGE = len(EDGE_KINDS) N_EDGE = len(EDGE_KINDS)
N_AXIS = len(DOF_AXES)
FEAT_DIM = N_KIND + 2 + 3 + 7 # kind, source, unit, (x,y,z,layer,w,h,d) FEAT_DIM = N_KIND + 2 + 3 + 7 # kind, source, unit, (x,y,z,layer,w,h,d)
# type one-hot, axis one-hot, removed flag, layer, contact area
EDGE_FEAT_DIM = N_EDGE + N_AXIS + 3
QUERY_KINDS = ("connection", "stability", "freedom") QUERY_KINDS = ("connection", "stability", "freedom")
HOP_MAX = 4 # longer paths collapse into one bucket
FAR = HOP_MAX + 1 # unreachable, or "involves the query token"
def hop_distance(edge_index, edge_mask, edge_removed, n_ent: int) -> torch.Tensor:
"""Truncated all-pairs shortest path over the *post-intervention* graph.
A removed edge is not traversed: the question "still connected after cutting
the trunk" is about the graph after the cut, and a hop count that still
walks through the cut edge is a lie the model would have to unlearn.
"""
device = edge_index.device
B = edge_index.size(0)
ar = torch.arange(B, device=device)
adj = torch.zeros(B, n_ent, n_ent, dtype=torch.bool, device=device)
live = edge_mask if edge_removed is None else (edge_mask & (edge_removed < 0.5))
for k in range(edge_index.size(1)):
m = live[:, k]
if not m.any():
continue
b = ar[m]
s = edge_index[m, k, 0].clamp(min=0, max=n_ent - 1)
t = edge_index[m, k, 1].clamp(min=0, max=n_ent - 1)
adj[b, s, t] = True
adj[b, t, s] = True
dist = torch.full((B, n_ent, n_ent), FAR, dtype=torch.long, device=device)
idx = torch.arange(n_ent, device=device)
dist[:, idx, idx] = 0
dist = torch.where(adj, torch.ones_like(dist), dist)
reach = adj.clone()
front = adj.clone()
for d in range(2, HOP_MAX + 1):
front = (torch.bmm(front.float(), adj.float()) > 0) & ~reach
reach = reach | front
dist = torch.where(front, torch.full_like(dist, d), dist)
return dist
class Block(nn.Module): class Block(nn.Module):
def __init__(self, d: int, n_head: int, dropout: float = 0.0): def __init__(self, d: int, n_head: int, dropout: float = 0.0):
@@ -41,15 +93,20 @@ class Block(nn.Module):
self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d)) self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
self.drop = nn.Dropout(dropout) self.drop = nn.Dropout(dropout)
def forward(self, x, bias, pad_mask): def forward(self, x, bias, pad_mask, v_extra=None):
B, N, d = x.shape B, T, d = x.shape
h = self.ln1(x) h = self.ln1(x)
q, k, v = self.qkv(h).view(B, N, 3, self.n_head, d // self.n_head).permute(2, 0, 3, 1, 4) q, k, v = self.qkv(h).view(B, T, 3, self.n_head, d // self.n_head).permute(2, 0, 3, 1, 4)
if v_extra is not None:
# the relations an entity touches, injected straight into its value:
# edge type as attention bias only says "look there", not "it is a
# 0.8 mm2 contact on layer 2"
v = v + v_extra.view(B, T, self.n_head, d // self.n_head).permute(0, 2, 1, 3)
att = (q @ k.transpose(-2, -1)) / math.sqrt(d // self.n_head) att = (q @ k.transpose(-2, -1)) / math.sqrt(d // self.n_head)
att = att + bias att = att + bias
att = att.masked_fill(pad_mask[:, None, None, :], float("-inf")) att = att.masked_fill(pad_mask[:, None, None, :], float("-inf"))
att = self.drop(att.softmax(dim=-1)) att = self.drop(att.softmax(dim=-1))
y = (att @ v).transpose(1, 2).reshape(B, N, d) y = (att @ v).transpose(1, 2).reshape(B, T, d)
x = x + self.drop(self.proj(y)) x = x + self.drop(self.proj(y))
x = x + self.drop(self.mlp(self.ln2(x))) x = x + self.drop(self.mlp(self.ln2(x)))
return x return x
@@ -57,11 +114,17 @@ class Block(nn.Module):
class RelationBackbone(nn.Module): class RelationBackbone(nn.Module):
def __init__(self, d: int = 64, n_layer: int = 2, n_head: int = 4, def __init__(self, d: int = 64, n_layer: int = 2, n_head: int = 4,
dropout: float = 0.0, max_entities: int = 32): dropout: float = 0.0, max_entities: int = 32,
rounds: int = 2, n_evidence: int = 4):
super().__init__() super().__init__()
self.d = d self.d = d
self.n_head = n_head
self.max_entities = max_entities self.max_entities = max_entities
self.rounds = max(1, rounds)
self.n_evidence = max(0, n_evidence)
self.ent_proj = nn.Sequential(nn.Linear(FEAT_DIM, d), nn.GELU(), nn.Linear(d, d)) self.ent_proj = nn.Sequential(nn.Linear(FEAT_DIM, d), nn.GELU(), nn.Linear(d, d))
self.edge_proj = nn.Sequential(nn.Linear(EDGE_FEAT_DIM, d), nn.GELU(), nn.Linear(d, d))
self.query_emb = nn.Embedding(len(QUERY_KINDS), d) self.query_emb = nn.Embedding(len(QUERY_KINDS), d)
self.edit_op_emb = nn.Embedding(3, d) # none / remove_edge / remove_entity self.edit_op_emb = nn.Embedding(3, d) # none / remove_edge / remove_entity
# direction matters: a constraint points from the part to the fixture, a # direction matters: a constraint points from the part to the fixture, a
@@ -73,86 +136,188 @@ class RelationBackbone(nn.Module):
# something was removed, not which edge, and the evidence head needs the # something was removed, not which edge, and the evidence head needs the
# latter to exclude the removed edge from its certificate # latter to exclude the removed edge from its certificate
self.removed_bias = nn.Parameter(torch.zeros(n_head)) self.removed_bias = nn.Parameter(torch.zeros(n_head))
# structural order, not positional order: one bias per hop bucket
self.hop_bias = nn.Parameter(torch.zeros(HOP_MAX + 2, n_head))
self.blocks = nn.ModuleList([Block(d, n_head, dropout) for _ in range(n_layer)]) self.blocks = nn.ModuleList([Block(d, n_head, dropout) for _ in range(n_layer)])
self.ln_f = nn.LayerNorm(d) self.ln_f = nn.LayerNorm(d)
self.answer_head = nn.Linear(d, 3) self.answer_head = nn.Linear(d, 3)
self.change_head = nn.Linear(d, 3) self.change_head = nn.Linear(d, 3)
self.answer_round = nn.Embedding(self.rounds, d)
self.evidence_head = nn.Sequential(nn.Linear(2 * d, d), nn.GELU(), nn.Linear(d, 1)) self.evidence_head = nn.Sequential(nn.Linear(2 * d, d), nn.GELU(), nn.Linear(d, 1))
# the evidence head used to see only the two endpoint embeddings, so it # the evidence head used to see only the two endpoint embeddings, so it
# could not tell a removed edge from a live one. Edge identity has to be # could not tell a removed edge from a live one. Edge identity has to be
# part of the score, not just part of the attention bias. # part of the score, not just part of the attention bias.
self.edge_emb = nn.Embedding(N_EDGE, d) self.edge_emb = nn.Embedding(N_EDGE, d)
self.removed_emb = nn.Embedding(2, d) self.removed_emb = nn.Embedding(2, d)
self.ev_proj = nn.Linear(EDGE_FEAT_DIM, d)
self.round_emb = nn.Embedding(max(1, self.rounds - 1), d)
# calibration: logits / exp(log_temp). Learned, not tuned on a split, so
# the temperature is supervised by the same labels as the heads.
self.log_temp = nn.Parameter(torch.zeros(1))
# ------------------------------------------------------------------
def _hop_matrix(self, dist_ent, top, edge_index, n_ent: int, K: int) -> torch.Tensor:
"""(B, 1+N+K, 1+N+K) hop buckets, including the query token and the
evidence slots so every pair of positions has an entry."""
B = dist_ent.size(0)
device = dist_ent.device
T = 1 + n_ent + K
hop = torch.full((B, T, T), FAR, dtype=torch.long, device=device)
hop[:, 1:1 + n_ent, 1:1 + n_ent] = dist_ent
hop[:, 0, 0] = 0
if K == 0:
return hop
slots = torch.arange(1 + n_ent, T, device=device)
hop[:, slots, slots] = 0
if top is not None:
ar = torch.arange(B, device=device)
pair = edge_index[ar.unsqueeze(1), top.clamp(min=0)]
a, b = pair[..., 0].clamp(min=0), pair[..., 1].clamp(min=0)
pad = torch.full((B, K, n_ent), FAR, dtype=torch.long, device=device)
d = torch.minimum(dist_ent.gather(2, a.unsqueeze(-1).expand(B, K, n_ent)),
dist_ent.gather(2, b.unsqueeze(-1).expand(B, K, n_ent)))
d = torch.where(d >= FAR, pad, d + 1)
d = d.clamp(max=FAR)
hop[:, slots, 1:1 + n_ent] = d
hop[:, 1:1 + n_ent, slots] = d.transpose(1, 2)
return hop
def _bias(self, edge_index, edge_type, edge_mask, edge_removed, hop):
"""(B, n_head, T, T) additive attention bias, built in (B,T,T,H) so the
advanced indexing below is unambiguous."""
B, T, _ = hop.shape
H = self.n_head
bias = self.none_bias.view(1, 1, 1, H).expand(B, T, T, H).clone()
bias = bias + self.hop_bias[hop]
# accumulate through a flat linear index: parallel edges between the same
# pair of nodes hit the same cell, and fancy-index assignment would keep
# only the last of them
flat = bias.view(-1, H)
src = edge_index[..., 0] + 1
dst = edge_index[..., 1] + 1
bidx = torch.arange(B, device=edge_index.device).unsqueeze(1).expand_as(src)
def add(mask, vec, flip=False):
if not mask.any():
return
b_, s_, d_ = bidx[mask], src[mask], dst[mask]
if flip:
s_, d_ = d_, s_
lin = b_ * (T * T) + s_ * T + d_
flat.index_put_((lin,), vec.expand(lin.size(0), H), accumulate=True)
for t in range(N_EDGE):
m = (edge_type == t) & edge_mask
add(m, self.edge_bias[t])
add(m, self.edge_bias_inv[t], flip=True)
if edge_removed is not None:
rm = (edge_removed > 0) & edge_mask
add(rm, self.removed_bias)
add(rm, self.removed_bias, flip=True)
return bias.permute(0, 3, 1, 2)
def _evidence(self, x, n_ent, edge_index, edge_type, edge_removed, edge_feat_emb, q_out):
B = x.size(0)
ent = x[:, 1:1 + n_ent]
ar = torch.arange(B, device=x.device).unsqueeze(1)
ea = ent[ar, edge_index[..., 0].clamp(min=0, max=n_ent - 1)]
eb = ent[ar, edge_index[..., 1].clamp(min=0, max=n_ent - 1)]
e_feat = self.edge_emb(edge_type)
if edge_removed is not None:
e_feat = e_feat + self.removed_emb((edge_removed > 0).long())
# endpoints + query + the edge's own content: without the last term the
# head cannot exclude a removed edge from its own certificate
pair = torch.cat([ea + eb + e_feat + edge_feat_emb,
q_out.unsqueeze(1).expand(-1, ea.size(1), -1)], dim=-1)
return self.evidence_head(pair).squeeze(-1)
# ------------------------------------------------------------------
def forward(self, feat, pad_mask, edge_index, edge_type, edge_mask, q_ents, q_kind, def forward(self, feat, pad_mask, edge_index, edge_type, edge_mask, q_ents, q_kind,
edit_op=None, edit_idx=None, edge_removed=None): edit_op=None, edit_idx=None, edge_removed=None, edge_feat=None):
B, N, _ = feat.shape B, n_ent, _ = feat.shape
E = edge_index.size(1)
device = feat.device device = feat.device
K = min(self.n_evidence, E) if self.rounds > 1 else 0
ar = torch.arange(B, device=device)
if edge_feat is None:
edge_feat = torch.zeros(B, E, EDGE_FEAT_DIM, device=device)
h = self.ent_proj(feat) h = self.ent_proj(feat)
ef = self.edge_proj(edge_feat) # edge content, (B, E, d)
# fold incident edge content into each entity's value. Incidence is built
# as a dense (B,N,E) matrix and applied as one matmul: index_put_ with
# accumulate keeps the backward pass simple, but a matmul keeps it
# obvious that an entity receiving three edges sums three vectors.
inc = torch.zeros(B, n_ent, E, device=device)
cols = torch.arange(E, device=device).view(1, E).expand(B, E)
ones = torch.ones_like(cols, dtype=inc.dtype)
inc.index_put_((ar.unsqueeze(1).expand(B, E),
edge_index[..., 0].clamp(min=0, max=n_ent - 1), cols), ones)
inc.index_put_((ar.unsqueeze(1).expand(B, E),
edge_index[..., 1].clamp(min=0, max=n_ent - 1), cols), ones)
inc = inc * edge_mask.unsqueeze(1).to(inc.dtype)
msg = torch.bmm(inc, ef)
# query token is read out of the two entities it names # query token is read out of the two entities it names
q = self.query_emb(q_kind).unsqueeze(1).expand(B, 1, self.d).clone() q = self.query_emb(q_kind).unsqueeze(1).expand(B, 1, self.d).clone()
valid_a = (q_ents[:, 0] >= 0).unsqueeze(-1) valid_a = (q_ents[:, 0] >= 0).unsqueeze(-1)
valid_b = (q_ents[:, 1] >= 0).unsqueeze(-1) valid_b = (q_ents[:, 1] >= 0).unsqueeze(-1)
ent_pad = torch.cat([torch.ones(B, 1, dtype=torch.bool, device=device), pad_mask], dim=1)
a_idx = q_ents[:, 0].clamp(min=0) a_idx = q_ents[:, 0].clamp(min=0)
b_idx = q_ents[:, 1].clamp(min=0) b_idx = q_ents[:, 1].clamp(min=0)
q = q + torch.where(valid_a.unsqueeze(-1), h[torch.arange(B), a_idx].unsqueeze(1), q = q + torch.where(valid_a.unsqueeze(-1), h[ar, a_idx].unsqueeze(1), torch.zeros_like(q))
torch.zeros_like(q)) q = q + torch.where(valid_b.unsqueeze(-1), h[ar, b_idx].unsqueeze(1), torch.zeros_like(q))
q = q + torch.where(valid_b.unsqueeze(-1), h[torch.arange(B), b_idx].unsqueeze(1),
torch.zeros_like(q))
# the intervention itself: which edge or entity the question removes # the intervention itself: which edge or entity the question removes
if edit_op is not None and edit_idx is not None: if edit_op is not None and edit_idx is not None:
ar = torch.arange(B, device=device)
# separate clamps: an entity index can exceed the padded edge count # separate clamps: an entity index can exceed the padded edge count
tgt_ent = h[ar, edit_idx.clamp(min=0, max=N - 1)] tgt_ent = h[ar, edit_idx.clamp(min=0, max=n_ent - 1)]
pair = edge_index[ar, edit_idx.clamp(min=0, max=edge_index.size(1) - 1)] pair = edge_index[ar, edit_idx.clamp(min=0, max=E - 1)]
tgt_edge = h[ar, pair[:, 0].clamp(min=0)] + h[ar, pair[:, 1].clamp(min=0)] tgt_edge = h[ar, pair[:, 0].clamp(min=0, max=n_ent - 1)] + \
h[ar, pair[:, 1].clamp(min=0, max=n_ent - 1)]
tgt = torch.where((edit_op == 1).unsqueeze(-1), tgt_edge, tgt_ent) tgt = torch.where((edit_op == 1).unsqueeze(-1), tgt_edge, tgt_ent)
has = (edit_op > 0).unsqueeze(-1).to(q.dtype) has = (edit_op > 0).unsqueeze(-1).to(q.dtype)
q = q + self.edit_op_emb(edit_op).unsqueeze(1) + (tgt * has).unsqueeze(1) q = q + self.edit_op_emb(edit_op).unsqueeze(1) + (tgt * has).unsqueeze(1)
x = torch.cat([q, h], dim=1) # (B, 1+N, d) zeros_ev = torch.zeros(B, K, self.d, device=device)
pad = ent_pad # (B, 1+N) x_tok = torch.cat([q, h, zeros_ev], dim=1) # (B, 1+N+K, d)
v_extra = torch.cat([torch.zeros(B, 1, self.d, device=device), msg, zeros_ev], dim=1)
pad = torch.cat([torch.zeros(B, 1, dtype=torch.bool, device=device), pad_mask,
torch.ones(B, K, dtype=torch.bool, device=device)], dim=1)
# edge-type bias: only where an edge exists, and asymmetric per direction dist = hop_distance(edge_index, edge_mask, edge_removed, n_ent)
n_head = self.blocks[0].n_head top = None
bias = self.none_bias.view(1, n_head, 1, 1).expand(B, n_head, N + 1, N + 1).clone() ev_logits = None
src = edge_index[..., 0] + 1 q_out = None
dst = edge_index[..., 1] + 1 temp = torch.exp(-self.log_temp)
bidx = torch.arange(B, device=device).unsqueeze(1).expand_as(src)
for t in range(N_EDGE):
m = (edge_type == t) & edge_mask
if not m.any():
continue
b_idx, s_idx, d_idx = bidx[m], src[m], dst[m]
bias[b_idx, :, s_idx, d_idx] = bias[b_idx, :, s_idx, d_idx] + self.edge_bias[t].unsqueeze(0)
bias[b_idx, :, d_idx, s_idx] = bias[b_idx, :, d_idx, s_idx] + self.edge_bias_inv[t].unsqueeze(0)
if edge_removed is not None: for r in range(self.rounds):
rm = (edge_removed > 0) & edge_mask hop = self._hop_matrix(dist, top, edge_index, n_ent, K)
if rm.any(): bias = self._bias(edge_index, edge_type, edge_mask, edge_removed, hop)
b_idx, s_idx, d_idx = bidx[rm], src[rm], dst[rm] x = x_tok
bias[b_idx, :, s_idx, d_idx] = bias[b_idx, :, s_idx, d_idx] + self.removed_bias.unsqueeze(0) for blk in self.blocks:
bias[b_idx, :, d_idx, s_idx] = bias[b_idx, :, d_idx, s_idx] + self.removed_bias.unsqueeze(0) x = blk(x, bias, pad, v_extra)
x = self.ln_f(x)
for blk in self.blocks: q_out = x[:, 0] + self.answer_round.weight[r]
x = blk(x, bias, pad) ev_logits = self._evidence(x, n_ent, edge_index, edge_type, edge_removed, ef, q_out)
x = self.ln_f(x) if r + 1 < self.rounds and K > 0:
q_out, ent_out = x[:, 0], x[:, 1:] # round 1 hands back the strongest candidate edges as tokens, so
# every entity can attend to the certificate it is part of
# evidence: score every edge by its endpoints and the query top = ev_logits.detach().masked_fill(~edge_mask, float("-inf")).topk(K, -1).indices
ea = ent_out[torch.arange(B).unsqueeze(1), edge_index[..., 0].clamp(min=0)] filled = torch.cat([edge_mask.gather(1, top[:, kk:kk + 1]) for kk in range(K)], 1)
eb = ent_out[torch.arange(B).unsqueeze(1), edge_index[..., 1].clamp(min=0)] x_tok = torch.cat([x_tok[:, :1 + n_ent],
e_feat = self.edge_emb(edge_type) self.ev_proj(edge_feat[ar.unsqueeze(1), top.clamp(min=0)])
if edge_removed is not None: + self.round_emb.weight[r]], dim=1)
e_feat = e_feat + self.removed_emb((edge_removed > 0).long()) pad = torch.cat([pad[:, :1 + n_ent], ~filled], dim=1)
pair = torch.cat([ea + eb + e_feat, q_out.unsqueeze(1).expand_as(ea)], dim=-1)
ev_logits = self.evidence_head(pair).squeeze(-1)
return { return {
"answer": self.answer_head(q_out), "answer": self.answer_head(q_out) * temp,
"change": self.change_head(q_out), "change": self.change_head(q_out) * temp,
"evidence": ev_logits, "evidence": ev_logits * temp,
"temp": temp.detach(),
} }
+35 -6
View File
@@ -35,7 +35,8 @@ def make_batch(families, seed: int, step: int, batch_size: int):
def batch_loss(model, tensors): def batch_loss(model, tensors):
out = model(tensors["feat"], tensors["pad_mask"], tensors["edge_index"], out = model(tensors["feat"], tensors["pad_mask"], tensors["edge_index"],
tensors["edge_type"], tensors["edge_mask"], tensors["q_ents"], tensors["q_kind"], 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_ans = F.cross_entropy(out["answer"], tensors["answer"])
l_chg = F.cross_entropy(out["change"], tensors["change"]) l_chg = F.cross_entropy(out["change"], tensors["change"])
ev_logits = out["evidence"][tensors["edge_mask"]] 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 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 total = l_ans + 0.5 * l_chg + 0.5 * l_ev
return total, {"answer": float(l_ans.detach()), "change": float(l_chg.detach()), 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() @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)) valid += int(bool(picked) and checker.validate_evidence(sc.full, sc.query, picked))
model.train() model.train()
ece = _ece(torch.softmax(out["answer"], -1), tensors["answer"])
return { return {
"answer_acc": correct / max(1, len(answerable)), "answer_acc": correct / max(1, len(answerable)),
"answerable": 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)), "change_acc": chg_correct / max(1, len(chg_rows)),
"evidence_valid": valid / max(1, total), "evidence_valid": valid / max(1, total),
"n_true_pred": total, "n_true_pred": total,
"ece": ece,
"temp": float(out["temp"]),
"loss": losses, "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 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"): def load(path: str, device="cpu"):
# always restore on CPU: map_location=device would drag the RNG state (a # 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 # ByteTensor) onto the GPU, and set_rng_state only accepts a CPU one
ck = torch.load(path, map_location="cpu", weights_only=False) ck = torch.load(path, map_location="cpu", weights_only=False)
cfg = ck["config"]["model"] cfg = ck["config"]["model"]
model = RelationBackbone(d=cfg["d"], n_layer=cfg["n_layer"], n_head=cfg["n_head"], model = _build(cfg)
dropout=cfg["dropout"], max_entities=cfg["max_entities"])
model.load_state_dict(ck["model"]) model.load_state_dict(ck["model"])
opt = torch.optim.AdamW(model.parameters(), lr=ck["config"]["optim"]["lr"], opt = torch.optim.AdamW(model.parameters(), lr=ck["config"]["optim"]["lr"],
weight_decay=ck["config"]["optim"]["weight_decay"]) 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}") print(f"resume from step {start}")
else: else:
m = config["model"] m = config["model"]
model = RelationBackbone(d=m["d"], n_layer=m["n_layer"], n_head=m["n_head"], model = _build(m)
dropout=m["dropout"], max_entities=m["max_entities"])
opt = torch.optim.AdamW(model.parameters(), lr=config["optim"]["lr"], opt = torch.optim.AdamW(model.parameters(), lr=config["optim"]["lr"],
weight_decay=config["optim"]["weight_decay"]) weight_decay=config["optim"]["weight_decay"])
start = 0 start = 0