fix(spatial): 证据槽的跳数按实体索引取,不能拿位置当索引

悬空边的远端是哨兵值(未知槽位),直接拿位置去 gather dist_ent 会越界。
现在按实体空间取,越界的那一端置 FAR,另一端的距离照常 +1。
This commit is contained in:
liuhuajie committed 2026-12-03 18:50:35 +08:00
1 parent 40f6bb52fa
commit e4c314b31a
1 file changed
+10 -8
+10 -8
View File
@@ -175,7 +175,7 @@ class RelationBackbone(nn.Module):
self.log_temp = nn.Parameter(torch.zeros(1))
# ------------------------------------------------------------------
def _hop_matrix(self, dist_ent, anchor, top, pos, n_ent: int, K: int) -> torch.Tensor:
def _hop_matrix(self, dist_ent, anchor, top, edge_index, 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
@@ -199,12 +199,14 @@ class RelationBackbone(nn.Module):
hop[:, slots, slots] = 0
if top is not None:
ar = torch.arange(B, device=device)
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).clamp(max=FAR)
sel = edge_index[ar.unsqueeze(1), top.clamp(min=0)] # (B, K, 2), entity space
ok = sel < n_ent # false for the unknown end
safe = sel.clamp(min=0, max=n_ent - 1)
far = torch.full((B, K, n_ent), FAR, dtype=torch.long, device=device)
da = dist_ent.gather(2, safe[..., 0].unsqueeze(-1).expand(B, K, n_ent))
db = dist_ent.gather(2, safe[..., 1].unsqueeze(-1).expand(B, K, n_ent))
d = torch.minimum(torch.where(ok[..., 0:1], da, far), torch.where(ok[..., 1:2], db, far))
d = torch.where(d >= FAR, far, d + 1).clamp(max=FAR)
hop[:, slots, ENT0:ENT0 + n_ent] = d
hop[:, ENT0:ENT0 + n_ent, slots] = d.transpose(1, 2)
return hop
@@ -349,7 +351,7 @@ class RelationBackbone(nn.Module):
temp = torch.exp(-self.log_temp)
for r in range(self.rounds):
hop = self._hop_matrix(dist, anchor, top, pos, n_ent, K)
hop = self._hop_matrix(dist, anchor, top, edge_index, n_ent, K)
bias = self._bias(pos, edge_type, edge_mask, edge_removed, dangling, hop)
x = x_tok
for blk in self.blocks: