fix(spatial): 补上"观测自己承认缺失了什么"的输入,cond.p1/cond.p1h 不再是同一张量

hidden_layers 和 hidden_faces 一直只在 digest 里,没进过张量。于是
"不存在隐藏支路"和"有隐藏支路但在视野外"到达模型时是同一个输入、标签却相反
(前者 false,后者 unknown)。这不是欠拟合,是契约承诺了、张量化却丢掉了的信息。

现在把观测的"缺失声明"投影到 query token 上:隐藏层 1..3 指示位、未见面的数量、
"确有东西被隐藏"一位、场景规模。模型因此有机会说"我看不到决定这件事的那部分"。
This commit is contained in:
liuhuajie committed 2026-12-03 18:31:25 +08:00
1 parent 1e0dcd6fb4
commit 08153b987d
4 files changed
+38 -4

No files matched your search

+23 -1
View File
@@ -12,7 +12,7 @@ import torch
from collections import deque from collections import deque
from .schema import ANSWERS, CHANGES, DOF_AXES, EDGE_KINDS, ENTITY_KINDS, Scenario from .schema import ANSWERS, CHANGES, DOF_AXES, EDGE_KINDS, ENTITY_KINDS, Scenario
from .model import EDGE_FEAT_DIM, FEAT_DIM, N_AXIS, N_EDGE, QUERY_KINDS from .model import EDGE_FEAT_DIM, FEAT_DIM, N_AXIS, N_EDGE, QUERY_KINDS, SCENE_DIM
def _reach(edges, src: str, alive) -> set: def _reach(edges, src: str, alive) -> set:
@@ -107,6 +107,25 @@ def edge_features(sc: Scenario, ed, removed: bool) -> list:
return f return f
def scene_features(sc: Scenario) -> list:
"""The observation's own admission of what it is missing.
``hidden_layers`` and ``hidden_faces`` are in the digest but were never in
the tensor, so "no hidden branch" and "a hidden branch off-view" arrived at
the model as the same input with opposite labels. That is not an
under-fitting problem; it is information the contract promised and the
tensorisation dropped.
"""
f = [0.0] * SCENE_DIM
for layer in sc.obs.hidden_layers:
if 1 <= layer <= 3:
f[layer - 1] = 1.0
f[3] = min(1.0, len(sc.obs.hidden_faces) / 6.0)
f[4] = 1.0 if (sc.obs.hidden_layers or sc.obs.hidden_faces) else 0.0
f[5] = len(sc.obs.entities) / 32.0
return f
def collate(batch, max_entities: int = 32): def collate(batch, max_entities: int = 32):
B = len(batch) B = len(batch)
N = max(1, max(len(sc.obs.entities) for sc in batch)) N = max(1, max(len(sc.obs.entities) for sc in batch))
@@ -116,6 +135,7 @@ def collate(batch, max_entities: int = 32):
"bucket it instead of truncating") "bucket it instead of truncating")
feat = torch.zeros(B, N, FEAT_DIM) feat = torch.zeros(B, N, FEAT_DIM)
scene = torch.zeros(B, SCENE_DIM)
pad_mask = torch.ones(B, N, dtype=torch.bool) pad_mask = torch.ones(B, N, dtype=torch.bool)
edge_index = torch.zeros(B, E, 2, dtype=torch.long) edge_index = torch.zeros(B, E, 2, dtype=torch.long)
edge_type = torch.zeros(B, E, dtype=torch.long) edge_type = torch.zeros(B, E, dtype=torch.long)
@@ -132,6 +152,7 @@ def collate(batch, max_entities: int = 32):
for i, sc in enumerate(batch): for i, sc in enumerate(batch):
ids = {e.eid: j for j, e in enumerate(sc.obs.entities)} ids = {e.eid: j for j, e in enumerate(sc.obs.entities)}
scene[i] = torch.tensor(scene_features(sc))
for j, e in enumerate(sc.obs.entities): for j, e in enumerate(sc.obs.entities):
feat[i, j] = torch.tensor(entity_features(sc, e)) feat[i, j] = torch.tensor(entity_features(sc, e))
pad_mask[i, j] = False pad_mask[i, j] = False
@@ -167,6 +188,7 @@ def collate(batch, max_entities: int = 32):
"feat": feat, "pad_mask": pad_mask, "feat": feat, "pad_mask": pad_mask,
"edge_index": edge_index, "edge_type": edge_type, "edge_mask": edge_mask, "edge_index": edge_index, "edge_type": edge_type, "edge_mask": edge_mask,
"edge_feat": edge_feat, "edge_feat": edge_feat,
"scene": scene,
"q_ents": q_ents, "q_kind": q_kind, "q_ents": q_ents, "q_kind": q_kind,
"edit_op": edit_op, "edit_idx": edit_idx, "edit_op": edit_op, "edit_idx": edit_idx,
"edge_removed": edge_removed, "edge_removed": edge_removed,
+13 -1
View File
@@ -45,6 +45,11 @@ QUERY_KINDS = ("connection", "stability", "freedom")
HOP_MAX = 4 # longer paths collapse into one bucket HOP_MAX = 4 # longer paths collapse into one bucket
FAR = HOP_MAX + 1 # unreachable, or "involves the query token" FAR = HOP_MAX + 1 # unreachable, or "involves the query token"
# what the observation admits it is missing: hidden layer markers, unseen faces,
# and one bit for "something was withheld at all". 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 = 6
def hop_distance(edge_index, edge_mask, edge_removed, n_ent: int) -> torch.Tensor: def hop_distance(edge_index, edge_mask, edge_removed, n_ent: int) -> torch.Tensor:
@@ -125,6 +130,7 @@ class RelationBackbone(nn.Module):
self.ent_proj = nn.Sequential(nn.Linear(FEAT_DIM, d), nn.GELU(), nn.Linear(d, d)) 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.edge_proj = nn.Sequential(nn.Linear(EDGE_FEAT_DIM, d), nn.GELU(), nn.Linear(d, d))
self.scene_proj = nn.Sequential(nn.Linear(SCENE_DIM, d), nn.GELU(), nn.Linear(d, d))
self.query_emb = nn.Embedding(len(QUERY_KINDS), d) self.query_emb = nn.Embedding(len(QUERY_KINDS), d)
self.edit_op_emb = nn.Embedding(3, d) # none / remove_edge / remove_entity 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 # direction matters: a constraint points from the part to the fixture, a
@@ -237,7 +243,7 @@ class RelationBackbone(nn.Module):
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def forward(self, feat, pad_mask, edge_index, edge_type, edge_mask, q_ents, q_kind, 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): edit_op=None, edit_idx=None, edge_removed=None, edge_feat=None, scene=None):
B, n_ent, _ = feat.shape B, n_ent, _ = feat.shape
E = edge_index.size(1) E = edge_index.size(1)
device = feat.device device = feat.device
@@ -284,6 +290,12 @@ class RelationBackbone(nn.Module):
has = (edit_op > 0).unsqueeze(-1).to(q.dtype) has = (edit_op > 0).unsqueeze(-1).to(q.dtype)
q = q + self.edit_op_emb(edit_op).unsqueeze(1) + (tgt * has).unsqueeze(1) 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)
zeros_ev = torch.zeros(B, K, self.d, device=device) 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) 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) v_extra = torch.cat([torch.zeros(B, 1, self.d, device=device), msg, zeros_ev], dim=1)
+1 -1
View File
@@ -36,7 +36,7 @@ def family_row(model, family: str, seed: int, n: int, max_entities: int = 32) ->
t = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in t.items()} t = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in t.items()}
out = model(t["feat"], t["pad_mask"], t["edge_index"], t["edge_type"], t["edge_mask"], out = model(t["feat"], t["pad_mask"], t["edge_index"], t["edge_type"], t["edge_mask"],
t["q_ents"], t["q_kind"], t["edit_op"], t["edit_idx"], t["edge_removed"], t["q_ents"], t["q_kind"], t["edit_op"], t["edit_idx"], t["edge_removed"],
t["edge_feat"]) t["edge_feat"], t["scene"])
pred = out["answer"].argmax(-1).tolist() pred = out["answer"].argmax(-1).tolist()
conf = torch.softmax(out["answer"], -1).max(-1).values.tolist() conf = torch.softmax(out["answer"], -1).max(-1).values.tolist()
probs = torch.sigmoid(out["evidence"]) probs = torch.sigmoid(out["evidence"])
+1 -1
View File
@@ -37,7 +37,7 @@ def batch_loss(model, tensors):
out = model(tensors["feat"], tensors["pad_mask"], tensors["edge_index"], out = model(tensors["feat"], tensors["pad_mask"], tensors["edge_index"],
tensors["edge_type"], tensors["edge_mask"], tensors["q_ents"], tensors["q_kind"], tensors["edge_type"], tensors["edge_mask"], tensors["q_ents"], tensors["q_kind"],
tensors.get("edit_op"), tensors.get("edit_idx"), tensors.get("edge_removed"), tensors.get("edit_op"), tensors.get("edit_idx"), tensors.get("edge_removed"),
tensors.get("edge_feat")) tensors.get("edge_feat"), tensors.get("scene"))
l_ans = F.cross_entropy(out["answer"], tensors["answer"]) l_ans = F.cross_entropy(out["answer"], tensors["answer"])
l_chg = F.cross_entropy(out["change"], tensors["change"]) l_chg = F.cross_entropy(out["change"], tensors["change"])
ev_logits = out["evidence"][tensors["edge_mask"]] ev_logits = out["evidence"][tensors["edge_mask"]]