"""Bidirectional relation backbone (deliberately small). 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 symmetric; an autoregressive mask would make the answer depend on an arbitrary serialisation order. * **edge types are attention biases** -- adjacency alone cannot express "contact" vs "constraint" vs "conduct", and those three mean different things for the same pair of nodes. * **one query token, not a token per entity** -- the output is about a query, not about the next token. 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. """ from __future__ import annotations import math import torch import torch.nn as nn import torch.nn.functional as F from .schema import EDGE_KINDS, ENTITY_KINDS N_KIND = len(ENTITY_KINDS) N_EDGE = len(EDGE_KINDS) FEAT_DIM = N_KIND + 2 + 3 + 7 # kind, source, unit, (x,y,z,layer,w,h,d) QUERY_KINDS = ("connection", "stability", "freedom") class Block(nn.Module): def __init__(self, d: int, n_head: int, dropout: float = 0.0): super().__init__() self.n_head = n_head self.ln1 = nn.LayerNorm(d) self.qkv = nn.Linear(d, 3 * d, bias=False) self.proj = nn.Linear(d, d, bias=False) self.ln2 = nn.LayerNorm(d) self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d)) self.drop = nn.Dropout(dropout) def forward(self, x, bias, pad_mask): B, N, d = x.shape 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) att = (q @ k.transpose(-2, -1)) / math.sqrt(d // self.n_head) att = att + bias att = att.masked_fill(pad_mask[:, None, None, :], float("-inf")) att = self.drop(att.softmax(dim=-1)) y = (att @ v).transpose(1, 2).reshape(B, N, d) x = x + self.drop(self.proj(y)) x = x + self.drop(self.mlp(self.ln2(x))) return x class RelationBackbone(nn.Module): def __init__(self, d: int = 64, n_layer: int = 2, n_head: int = 4, dropout: float = 0.0, max_entities: int = 32): super().__init__() self.d = d self.max_entities = max_entities self.ent_proj = nn.Sequential(nn.Linear(FEAT_DIM, d), nn.GELU(), nn.Linear(d, 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 # conduct edge from source to sink. Two tables, not one symmetric table. self.edge_bias = nn.Parameter(torch.zeros(N_EDGE, n_head)) self.edge_bias_inv = nn.Parameter(torch.zeros(N_EDGE, n_head)) self.none_bias = nn.Parameter(torch.zeros(n_head)) # the intervention as an edge flag: a global token tells the model that # 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.blocks = nn.ModuleList([Block(d, n_head, dropout) for _ in range(n_layer)]) self.ln_f = nn.LayerNorm(d) self.answer_head = nn.Linear(d, 3) self.change_head = nn.Linear(d, 3) 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 # 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. self.edge_emb = nn.Embedding(N_EDGE, d) self.removed_emb = nn.Embedding(2, d) 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): B, N, _ = feat.shape device = feat.device h = self.ent_proj(feat) # 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() valid_a = (q_ents[:, 0] >= 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) b_idx = q_ents[:, 1].clamp(min=0) q = q + torch.where(valid_a.unsqueeze(-1), h[torch.arange(B), a_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 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 tgt_ent = h[ar, edit_idx.clamp(min=0, max=N - 1)] pair = edge_index[ar, edit_idx.clamp(min=0, max=edge_index.size(1) - 1)] tgt_edge = h[ar, pair[:, 0].clamp(min=0)] + h[ar, pair[:, 1].clamp(min=0)] tgt = torch.where((edit_op == 1).unsqueeze(-1), tgt_edge, tgt_ent) has = (edit_op > 0).unsqueeze(-1).to(q.dtype) 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) pad = ent_pad # (B, 1+N) # edge-type bias: only where an edge exists, and asymmetric per direction n_head = self.blocks[0].n_head bias = self.none_bias.view(1, n_head, 1, 1).expand(B, n_head, N + 1, N + 1).clone() src = edge_index[..., 0] + 1 dst = edge_index[..., 1] + 1 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: rm = (edge_removed > 0) & edge_mask if rm.any(): b_idx, s_idx, d_idx = bidx[rm], src[rm], dst[rm] bias[b_idx, :, s_idx, d_idx] = bias[b_idx, :, s_idx, d_idx] + self.removed_bias.unsqueeze(0) bias[b_idx, :, d_idx, s_idx] = bias[b_idx, :, d_idx, s_idx] + self.removed_bias.unsqueeze(0) for blk in self.blocks: x = blk(x, bias, pad) x = self.ln_f(x) q_out, ent_out = x[:, 0], x[:, 1:] # evidence: score every edge by its endpoints and the query ea = ent_out[torch.arange(B).unsqueeze(1), edge_index[..., 0].clamp(min=0)] eb = ent_out[torch.arange(B).unsqueeze(1), edge_index[..., 1].clamp(min=0)] e_feat = self.edge_emb(edge_type) if edge_removed is not None: e_feat = e_feat + self.removed_emb((edge_removed > 0).long()) 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 { "answer": self.answer_head(q_out), "change": self.change_head(q_out), "evidence": ev_logits, }