feat(spatial): 悬空关系与未知槽位,让"缺哪一段"落到位置而不是计数
此前"少了一条接触"只是全局计数,模型只能说"我在猜";它无法区分"目标根本没支撑" 和"目标的那条支撑被挡住了"。现在: - Observation.dangling:一端可见、另一端不可见的关系,锚在可见那一端,不带身份。 它说的是无知挂在哪儿,不是答案是什么。 - 模型多一个未知槽位(位置 1),悬空边的远端指向它;有悬空关系的锚定实体与它 相距一跳。一条链走到它上面,就是一条链走进了问题。 - 悬空边不参与连通计算、不进入实体的入射边求和、边特征里带 dangling 标志。 - 新增 area.free 家族:T 的唯一接触连到一个自身悬空的块,什么也没藏、什么也不悬空, 所以"没有支撑"是事实而非缺口,正确答案是 false,弃权才是错的。 它与 area.sup2h 构成最小对:同样是一条接触,一个通到未知、一个通到死路。
This commit is contained in:
1 parent
68380900ce
commit
40f6bb52fa
8 files changed
+251
-141
No files matched your search
+77
-38
@@ -14,6 +14,10 @@ Differences from ``mm/model.py``, and why they are not negotiable here:
|
||||
so an entity actually receives its incident relations.
|
||||
* **one query token, not a token per entity** -- the output is about a query,
|
||||
not about the next token.
|
||||
* **one unknown slot** -- a dangling relation (one end visible, one end not)
|
||||
points at a single dedicated token instead of at an entity. A chain that ends
|
||||
there is a chain that ends in a question, which is what "I cannot decide this"
|
||||
has to look like in the input.
|
||||
* **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
|
||||
@@ -39,8 +43,8 @@ N_KIND = len(ENTITY_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)
|
||||
# type one-hot, axis one-hot, removed flag, layer, contact area
|
||||
EDGE_FEAT_DIM = N_EDGE + N_AXIS + 3
|
||||
# type one-hot, axis one-hot, removed flag, layer, contact area, dangling flag
|
||||
EDGE_FEAT_DIM = N_EDGE + N_AXIS + 4
|
||||
QUERY_KINDS = ("connection", "stability", "freedom")
|
||||
|
||||
HOP_MAX = 4 # longer paths collapse into one bucket
|
||||
@@ -52,6 +56,9 @@ FAR = HOP_MAX + 1 # unreachable, or "involves the query token"
|
||||
# reasoning can separate them.
|
||||
SCENE_DIM = 4 + N_KIND + N_EDGE + 2
|
||||
|
||||
UNK = 1 # position of the unknown slot
|
||||
ENT0 = 2 # first entity position
|
||||
|
||||
|
||||
def hop_distance(edge_index, edge_mask, edge_removed, n_ent: int) -> torch.Tensor:
|
||||
"""Truncated all-pairs shortest path over the *post-intervention* graph.
|
||||
@@ -132,6 +139,7 @@ class RelationBackbone(nn.Module):
|
||||
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.scene_proj = nn.Sequential(nn.Linear(SCENE_DIM, d), nn.GELU(), nn.Linear(d, d))
|
||||
self.unk_tok = nn.Parameter(torch.zeros(d))
|
||||
self.query_emb = nn.Embedding(len(QUERY_KINDS), d)
|
||||
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
|
||||
@@ -143,6 +151,7 @@ class RelationBackbone(nn.Module):
|
||||
# something was removed, not which edge, and the evidence head needs the
|
||||
# latter to exclude the removed edge from its certificate
|
||||
self.removed_bias = nn.Parameter(torch.zeros(n_head))
|
||||
self.dangling_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))
|
||||
|
||||
@@ -166,33 +175,41 @@ class RelationBackbone(nn.Module):
|
||||
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."""
|
||||
def _hop_matrix(self, dist_ent, anchor, top, pos, n_ent: int, K: int) -> torch.Tensor:
|
||||
"""(B, T, T) hop buckets over *positions*, not entity indices.
|
||||
|
||||
The unknown slot sits one hop from every entity that has a dangling
|
||||
relation anchored on it, and is far from everything else. That is the
|
||||
whole point of the slot: "the chain continues, but not visibly".
|
||||
"""
|
||||
B = dist_ent.size(0)
|
||||
device = dist_ent.device
|
||||
T = 1 + n_ent + K
|
||||
T = ENT0 + 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[:, ENT0:ENT0 + n_ent, ENT0:ENT0 + n_ent] = dist_ent
|
||||
hop[:, 0, 0] = 0
|
||||
hop[:, UNK, UNK] = 0
|
||||
one = torch.ones(B, n_ent, dtype=torch.long, device=device)
|
||||
d_unk = torch.where(anchor, one, torch.full_like(one, FAR))
|
||||
hop[:, UNK, ENT0:ENT0 + n_ent] = d_unk
|
||||
hop[:, ENT0:ENT0 + n_ent, UNK] = d_unk
|
||||
if K == 0:
|
||||
return hop
|
||||
slots = torch.arange(1 + n_ent, T, device=device)
|
||||
slots = torch.arange(ENT0 + 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)]
|
||||
pair = pos[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)
|
||||
d = torch.where(d >= FAR, pad, d + 1).clamp(max=FAR)
|
||||
hop[:, slots, ENT0:ENT0 + n_ent] = d
|
||||
hop[:, ENT0:ENT0 + n_ent, slots] = d.transpose(1, 2)
|
||||
return hop
|
||||
|
||||
def _bias(self, edge_index, edge_type, edge_mask, edge_removed, hop):
|
||||
def _bias(self, pos, edge_type, edge_mask, edge_removed, dangling, 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
|
||||
@@ -200,13 +217,13 @@ class RelationBackbone(nn.Module):
|
||||
bias = self.none_bias.view(1, 1, 1, H).expand(B, T, T, H).clone()
|
||||
bias = bias + self.hop_bias[hop]
|
||||
|
||||
src, dst = pos[..., 0], pos[..., 1]
|
||||
bidx = torch.arange(B, device=pos.device).unsqueeze(1).expand_as(src)
|
||||
|
||||
# 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():
|
||||
@@ -225,26 +242,29 @@ class RelationBackbone(nn.Module):
|
||||
rm = (edge_removed > 0) & edge_mask
|
||||
add(rm, self.removed_bias)
|
||||
add(rm, self.removed_bias, flip=True)
|
||||
if dangling is not None:
|
||||
add((dangling > 0) & edge_mask, self.dangling_bias)
|
||||
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]
|
||||
def _evidence(self, x, pos, edge_type, edge_removed, edge_feat_emb, q_out):
|
||||
B, T, _ = x.shape
|
||||
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)]
|
||||
ea = x[ar, pos[..., 0].clamp(min=0, max=T - 1)]
|
||||
eb = x[ar, pos[..., 1].clamp(min=0, max=T - 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
|
||||
# head cannot exclude a removed edge from its own certificate, and
|
||||
# without the dangling flag it cannot tell a support from a question
|
||||
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,
|
||||
edit_op=None, edit_idx=None, edge_removed=None, edge_feat=None, scene=None):
|
||||
edit_op=None, edit_idx=None, edge_removed=None, edge_feat=None, scene=None,
|
||||
dangling=None):
|
||||
B, n_ent, _ = feat.shape
|
||||
E = edge_index.size(1)
|
||||
device = feat.device
|
||||
@@ -253,14 +273,31 @@ class RelationBackbone(nn.Module):
|
||||
|
||||
if edge_feat is None:
|
||||
edge_feat = torch.zeros(B, E, EDGE_FEAT_DIM, device=device)
|
||||
if dangling is None:
|
||||
dangling = torch.zeros(B, E, device=device)
|
||||
|
||||
# an edge endpoint is either an entity (entity index < n_ent) or the
|
||||
# unknown slot; mapping to positions once keeps every downstream use --
|
||||
# bias, hop, evidence -- reading the same coordinates
|
||||
pos = torch.where(edge_index < n_ent, edge_index + ENT0,
|
||||
torch.full_like(edge_index, UNK))
|
||||
has_unk = (dangling > 0) & edge_mask
|
||||
anchor = torch.zeros(B, n_ent, dtype=torch.bool, device=device)
|
||||
if has_unk.any():
|
||||
b_ = ar.unsqueeze(1).expand(B, E)[has_unk]
|
||||
e_ = edge_index[..., 0][has_unk].clamp(min=0, max=n_ent - 1)
|
||||
anchor.index_put_((b_, e_), torch.ones(b_.size(0), dtype=torch.bool, device=device))
|
||||
unk_absent = ~anchor.any(dim=1) # no mouth: the slot is not shown
|
||||
|
||||
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.
|
||||
# as a dense (B,N,E) matrix and applied as one matmul: it keeps the
|
||||
# backward pass simple and it makes "an entity receiving three edges sums
|
||||
# three vectors" obvious. Dangling edges are excluded: their far end is
|
||||
# not an entity, and pretending otherwise would credit an arbitrary node
|
||||
# with a relation it does not have.
|
||||
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)
|
||||
@@ -268,7 +305,7 @@ class RelationBackbone(nn.Module):
|
||||
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)
|
||||
inc = inc * (edge_mask & ~has_unk).unsqueeze(1).to(inc.dtype)
|
||||
msg = torch.bmm(inc, ef)
|
||||
|
||||
# query token is read out of the two entities it names
|
||||
@@ -297,36 +334,38 @@ class RelationBackbone(nn.Module):
|
||||
if scene is not None:
|
||||
q = q + self.scene_proj(scene).unsqueeze(1)
|
||||
|
||||
unk = self.unk_tok.view(1, 1, self.d).expand(B, 1, self.d)
|
||||
zeros_ev = torch.zeros(B, K, self.d, device=device)
|
||||
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)
|
||||
x_tok = torch.cat([q, unk, h, zeros_ev], dim=1) # (B, 2+N+K, d)
|
||||
v_extra = torch.cat([torch.zeros(B, 2, self.d, device=device), msg, zeros_ev], dim=1)
|
||||
pad = torch.cat([torch.zeros(B, 2, dtype=torch.bool, device=device),
|
||||
pad_mask, torch.ones(B, K, dtype=torch.bool, device=device)], dim=1)
|
||||
pad[:, UNK] = unk_absent # no dangling relation: no unknown slot
|
||||
|
||||
dist = hop_distance(edge_index, edge_mask, edge_removed, n_ent)
|
||||
dist = hop_distance(edge_index, edge_mask & ~has_unk, edge_removed, n_ent)
|
||||
top = None
|
||||
ev_logits = None
|
||||
q_out = None
|
||||
temp = torch.exp(-self.log_temp)
|
||||
|
||||
for r in range(self.rounds):
|
||||
hop = self._hop_matrix(dist, top, edge_index, n_ent, K)
|
||||
bias = self._bias(edge_index, edge_type, edge_mask, edge_removed, hop)
|
||||
hop = self._hop_matrix(dist, anchor, top, pos, n_ent, K)
|
||||
bias = self._bias(pos, edge_type, edge_mask, edge_removed, dangling, hop)
|
||||
x = x_tok
|
||||
for blk in self.blocks:
|
||||
x = blk(x, bias, pad, v_extra)
|
||||
x = self.ln_f(x)
|
||||
q_out = x[:, 0] + self.answer_round.weight[r]
|
||||
ev_logits = self._evidence(x, n_ent, edge_index, edge_type, edge_removed, ef, q_out)
|
||||
ev_logits = self._evidence(x, pos, edge_type, edge_removed, ef, q_out)
|
||||
if r + 1 < self.rounds and K > 0:
|
||||
# round 1 hands back the strongest candidate edges as tokens, so
|
||||
# every entity can attend to the certificate it is part of
|
||||
top = ev_logits.detach().masked_fill(~edge_mask, float("-inf")).topk(K, -1).indices
|
||||
filled = torch.cat([edge_mask.gather(1, top[:, kk:kk + 1]) for kk in range(K)], 1)
|
||||
x_tok = torch.cat([x_tok[:, :1 + n_ent],
|
||||
x_tok = torch.cat([x_tok[:, :ENT0 + n_ent],
|
||||
self.ev_proj(edge_feat[ar.unsqueeze(1), top.clamp(min=0)])
|
||||
+ self.round_emb.weight[r]], dim=1)
|
||||
pad = torch.cat([pad[:, :1 + n_ent], ~filled], dim=1)
|
||||
pad = torch.cat([pad[:, :ENT0 + n_ent], ~filled], dim=1)
|
||||
|
||||
return {
|
||||
"answer": self.answer_head(q_out) * temp,
|
||||
|
||||
Reference in new issue
Block a user