diff --git a/spatial/model.py b/spatial/model.py index 8763a28..97dbfbb 100644 --- a/spatial/model.py +++ b/spatial/model.py @@ -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: