四件结构补齐,每件都有对应的失效模式: - 跳数偏置:原来只靠 no-position 的注意力,实体顺序被打乱会让输出漂移。 改为按截断最短路分桶的注意力偏置(HOP_MAX=4),并遵守干预语义——被切掉的 边不参与连通,否则"剪掉主干后是否还连通"的跳数本身就是错的。 - 边内容进 value:边类型此前只是注意力偏置,只能表达"看那边",不能表达 "那是一个 0.8 的接触面、锁的是 tz 轴"。现在把入射边的特征投影后累加进实体 的 value,接触面积由两端 box 重叠算出,并按单位归一化。 - 证据回灌:第一轮选出 top-k 边作为候选凭证,第二轮让所有实体都能注意到 自己所在的那张凭证。此前证据头和答案头看的根本不是同一个对象。 - 学习温度:答案/变化/证据 logits 统一除以 exp(log_temp),并在评估里加 ECE。 只报准确率的话,置信度 0.99 而正确率 0.72 和直接报 0.72 是同一个数。 另外:把边偏置的累加改成扁平 index_put_(accumulate),平行边不再互相覆盖; 新增 configs/cross.json(训练 cond.p1/area.sup2/dof.c6,验证 held-out 家族)。
324 lines
16 KiB
Python
324 lines
16 KiB
Python
"""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.
|
|
* **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
|
|
EDGE_FEAT_DIM = N_EDGE + N_AXIS + 3
|
|
QUERY_KINDS = ("connection", "stability", "freedom")
|
|
|
|
HOP_MAX = 4 # longer paths collapse into one bucket
|
|
FAR = HOP_MAX + 1 # unreachable, or "involves the query token"
|
|
|
|
|
|
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))
|
|
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))
|
|
# 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, 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."""
|
|
B = dist_ent.size(0)
|
|
device = dist_ent.device
|
|
T = 1 + 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[:, 0, 0] = 0
|
|
if K == 0:
|
|
return hop
|
|
slots = torch.arange(1 + 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)]
|
|
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)
|
|
return hop
|
|
|
|
def _bias(self, edge_index, edge_type, edge_mask, edge_removed, 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]
|
|
|
|
# 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():
|
|
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)
|
|
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]
|
|
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)]
|
|
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
|
|
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):
|
|
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)
|
|
|
|
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.
|
|
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)
|
|
inc = inc * edge_mask.unsqueeze(1).to(inc.dtype)
|
|
msg = torch.bmm(inc, ef)
|
|
|
|
# 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))
|
|
|
|
# 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)
|
|
|
|
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)
|
|
|
|
dist = hop_distance(edge_index, edge_mask, 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)
|
|
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)
|
|
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],
|
|
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)
|
|
|
|
return {
|
|
"answer": self.answer_head(q_out) * temp,
|
|
"change": self.change_head(q_out) * temp,
|
|
"evidence": ev_logits * temp,
|
|
"temp": temp.detach(),
|
|
}
|