"""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. * **no positional encoding** -- entity order in a scene carries no meaning, so the only ordering signal is structural: a learned bias indexed by graph 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, 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 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 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 DOF_AXES, EDGE_KINDS, ENTITY_KINDS 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, dangling flag, # then the three local predicates a contact needs before it can carry load: # do the faces meet in z, is the upper block's centroid inside the overlap, and # how much of the upper footprint is covered. They are measurements, not # answers -- the same numbers a caliper and a straight edge would give. # The last slot is the disputed flag: two sources name this relation and # disagree. Without it a disputed edge and an agreed edge are the same input, and # "the proof goes through the disputed wire" is unlearnable. EDGE_FEAT_DIM = N_EDGE + N_AXIS + 4 + 3 + 1 QUERY_KINDS = ("connection", "stability", "freedom") HOP_MAX = 4 # longer paths collapse into one bucket FAR = HOP_MAX + 1 # unreachable, or "involves the query token" # what the observation admits it is missing: hidden layer markers, unseen faces, # one count per entity kind and per edge kind, an "anything withheld" bit, and # the scene size. Without this the two worlds "no hidden branch exists" and "a # hidden branch exists off-view" are literally the same tensor, and no amount of # reasoning can separate them. SCENE_DIM = 4 + N_KIND + N_EDGE + 2 + 4 # the first block is derived from the full state (what is hidden by kind); # the last four are derived from the declared inventory (scope), which a real # provider can state without endpoints. They live in separate slices so an # ablation can remove one without touching the other. SCENE_HIDDEN = slice(0, 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. 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): 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, v_extra=None): B, T, d = x.shape h = self.ln1(x) 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 = 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, T, 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, rounds: int = 2, n_evidence: int = 4): super().__init__() self.d = d self.n_head = n_head 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.edge_proj = nn.Sequential(nn.Linear(EDGE_FEAT_DIM, d), nn.GELU(), nn.Linear(d, d)) # a linear path for edge content, alongside the nonlinear one. "Are all # six axes locked" is a statement about the cardinality of a set, and the # sum of a *nonlinear* projection of one-hots is no longer a count -- # GELU mixes the axes and the bag loses which of them it saw. The linear # skip keeps the sum an exact count vector, so a threshold can read it. self.edge_lin = nn.Linear(EDGE_FEAT_DIM, d, bias=False) 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) # the relations attached to the entity the question names, delivered to # the question directly. Letting the query pick them up through attention # means averaging them with a dozen unrelated positions, and "are all six # axes locked" is a conjunction of six per-axis thresholds -- measured: at # chance (0.49) even on a single family, with the training loss stuck at # ln 2. The bag of incident relations is the evidence the question asks # for; it should not have to survive a softmax to arrive. self.q_inc = nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Linear(d, 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.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)) 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.answer_round = nn.Embedding(self.rounds, d) 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) 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, 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 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 = ENT0 + n_ent + K hop = torch.full((B, T, T), FAR, dtype=torch.long, device=device) 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(ENT0 + n_ent, T, device=device) hop[:, slots, slots] = 0 if top is not None: ar = torch.arange(B, device=device) 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 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 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] 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) 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) if dangling is not None: add((dangling > 0) & edge_mask, self.dangling_bias) return bias.permute(0, 3, 1, 2) 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 = 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, 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, dangling=None): B, n_ent, _ = feat.shape E = edge_index.size(1) 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) 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: 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. Removed edges are excluded too, for # the same reason the hop distance excludes them: the question is about # the graph after the cut, and an entity whose value still sums a cut # constraint has to un-learn it before it can answer. 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) live = edge_mask & ~has_unk if edge_removed is not None: live = live & ~(edge_removed > 0) inc = inc * live.unsqueeze(1).to(inc.dtype) msg = torch.bmm(inc, ef) + torch.bmm(inc, self.edge_lin(edge_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) 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[ar, a_idx].unsqueeze(1), torch.zeros_like(q)) q = q + torch.where(valid_b.unsqueeze(-1), h[ar, b_idx].unsqueeze(1), torch.zeros_like(q)) # and the relations hanging off those entities, without the detour q = q + torch.where(valid_a.unsqueeze(-1), self.q_inc(msg[ar, a_idx]).unsqueeze(1), torch.zeros_like(q)) q = q + torch.where(valid_b.unsqueeze(-1), self.q_inc(msg[ar, 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: # separate clamps: an entity index can exceed the padded edge count tgt_ent = h[ar, edit_idx.clamp(min=0, max=n_ent - 1)] pair = edge_index[ar, edit_idx.clamp(min=0, max=E - 1)] 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) has = (edit_op > 0).unsqueeze(-1).to(q.dtype) q = q + self.edit_op_emb(edit_op).unsqueeze(1) + (tgt * has).unsqueeze(1) # what the observation says it cannot see is part of the question, not a # property of any entity, so it rides on the query token where every # entity can attend to it 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, 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 & ~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, 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: 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, 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[:, :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[:, :ENT0 + n_ent], ~filled], dim=1) return { "answer": self.answer_head(q_out) * temp, "change": self.change_head(q_out) * temp, "evidence": ev_logits * temp, "temp": temp.detach(), }