Files
liuhuajie f31288bf06 feat(spatial): M0 契约、生成器、检查器与关系主干
按 mm/SPATIAL_FOUNDATION.md 落一个 CPU 可跑的 M0:数据契约把「可见观测」和
「完整状态」分开,标签只由检查器从完整状态算出,可见世界与完整世界答案不一致
时降级为 unknown。

- schema: Observation / FullState / Query / Label,整数几何,digest 可复现
- generator: 3 域 10 族(导通 / 支撑 / 约束),含隐藏支路与冗余约束
- checker: 三种判定 + 证据校验 + 三值标签(同观测不同真值 → 不足)
- model: 双向注意力,边类型作非对称 bias,三头(答案 / 变化 / 证据)
- train: 原子 checkpoint(含优化器、步数、RNG),可续训
- cli: smoke 覆盖切分不相交、同种子复现、标签可复算、单位与相机不变、
  一次更新 + 断点恢复

审查中修掉的缺陷(前三项致命):
1. query.edit 根本没有进入输入,模型看不到「删了哪条边」,单族训练只能达到
   多数类基线(0.719 = 0.719)。补上 edit token 与边级 removed 标记后到 1.0。
2. 证据头只用两端实体相加打分,看不到边特征,无法排除被删的边 → 有效率 0.464。
   改为把边类型与被删标记并入证据打分后到 1.0。
3. 证据监督把检查器选的那一条路径当唯一正解,同构的合法路径被当成负例。
   改为「任意合法路径上的边都算正」。
4. 生成器把隐藏支路的孤立 via 放进了观测,构成泄漏。
5. 注意力 bias 的 batch 索引张量维度错误;edit token 广播成 (B,B,d)。
6. resume 时 RNG 状态被带到 GPU、优化器状态留在 CPU。

实测(4 层 / 192 宽 / 1.8M,cond.p3 单族,400 步 / 3.9s):
answer 1.000,change 1.000,evidence_valid 1.000,多数类基线 0.719。
2026-12-03 16:13:38 +08:00

159 lines
7.6 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.
* **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,
}