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。
This commit is contained in:
liuhuajie committed 2026-12-03 16:13:38 +08:00
1 parent 2517132a53
commit f31288bf06
10 files changed
+1375

No files matched your search

+137
View File
@@ -0,0 +1,137 @@
"""Tensorisation.
Padding lives here and only here. A scenario with more entities than
``max_entities`` is rejected explicitly -- the plan forbids silently truncating
a scene, because cutting a node can turn "still connected" into "disconnected"
and quietly corrupt the label.
"""
from __future__ import annotations
import torch
from collections import deque
from .schema import ANSWERS, CHANGES, EDGE_KINDS, ENTITY_KINDS, Scenario
from .model import FEAT_DIM, QUERY_KINDS
def _reach(edges, src: str, alive) -> set:
adj = {}
for e in edges:
if not alive(e):
continue
adj.setdefault(e.a, []).append(e.b)
adj.setdefault(e.b, []).append(e.a)
seen, q = {src}, deque([src])
while q:
u = q.popleft()
for v in adj.get(u, ()):
if v not in seen:
seen.add(v)
q.append(v)
return seen
def evidence_target(sc: Scenario) -> set:
"""Every edge that can appear in *some* valid certificate counts as positive.
For a connection the checker returns one shortest path, but any a-b path is
a correct answer; training against a single one marks its equally valid
siblings as negatives and the head learns nothing usable. An edge lies on
some a-b path exactly when it can be traversed from a towards b.
"""
if sc.query.kind == "connection" and sc.label.answer == "true":
removed = (sc.query.edit or {}).get("edge")
alive = lambda e: e.eid != removed
ra = _reach(sc.obs.edges, sc.query.a, alive)
rb = _reach(sc.obs.edges, sc.query.b, alive)
return {e.eid for e in sc.obs.edges
if e.eid != removed
and ((e.a in ra and e.b in rb) or (e.b in ra and e.a in rb))}
return set(sc.label.evidence or [])
def _unit_onehot(per_unit: int):
return {1: 0, 10: 1, 100: 2}.get(per_unit, 0)
def entity_features(sc: Scenario, e) -> list:
f = [0.0] * FEAT_DIM
f[ENTITY_KINDS.index(e.kind)] = 1.0
f[len(ENTITY_KINDS) + (0 if e.source == "given" else 1)] = 1.0
f[len(ENTITY_KINDS) + 2 + _unit_onehot(sc.obs.units.get("per_unit", 1))] = 1.0
base = len(ENTITY_KINDS) + 2 + 3
scale = 200.0 * max(1, sc.obs.units.get("per_unit", 1))
box = e.attrs.get("box")
if box:
cx, cy, cz = (box[0] + box[3]) / 2, (box[1] + box[4]) / 2, (box[2] + box[5]) / 2
d = [cx / scale, cy / scale, cz / scale, e.attrs.get("layer", 0) / 6.0,
(box[3] - box[0]) / scale, (box[4] - box[1]) / scale, (box[5] - box[2]) / scale]
else:
d = [e.attrs.get("x", 0) / scale, e.attrs.get("y", 0) / scale,
e.attrs.get("z", 0) / scale, e.attrs.get("layer", 0) / 6.0, 0.0, 0.0, 0.0]
f[base:base + 7] = d
return f
def collate(batch, max_entities: int = 32):
B = len(batch)
N = max(1, max(len(sc.obs.entities) for sc in batch))
E = max(1, max(len(sc.obs.edges) for sc in batch))
if N > max_entities:
raise ValueError(f"scene needs {N} entity slots > max_entities {max_entities}; "
"bucket it instead of truncating")
feat = torch.zeros(B, N, FEAT_DIM)
pad_mask = torch.ones(B, N, dtype=torch.bool)
edge_index = torch.zeros(B, E, 2, dtype=torch.long)
edge_type = torch.zeros(B, E, dtype=torch.long)
edge_mask = torch.zeros(B, E, dtype=torch.bool)
evidence = torch.zeros(B, E)
edge_removed = torch.zeros(B, E)
q_ents = torch.full((B, 2), -1, dtype=torch.long)
q_kind = torch.zeros(B, dtype=torch.long)
edit_op = torch.zeros(B, dtype=torch.long) # 0 none, 1 remove_edge, 2 remove_entity
edit_idx = torch.full((B,), -1, dtype=torch.long)
answer = torch.zeros(B, dtype=torch.long)
change = torch.zeros(B, dtype=torch.long)
for i, sc in enumerate(batch):
ids = {e.eid: j 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))
pad_mask[i, j] = False
ev = evidence_target(sc)
for k, ed in enumerate(sc.obs.edges):
edge_index[i, k, 0] = ids.get(ed.a, 0)
edge_index[i, k, 1] = ids.get(ed.b, 0)
edge_type[i, k] = EDGE_KINDS.index(ed.kind)
edge_mask[i, k] = True
evidence[i, k] = 1.0 if ed.eid in ev else 0.0
if (sc.query.edit or {}).get("edge") == ed.eid:
edge_removed[i, k] = 1.0
q_ents[i, 0] = ids.get(sc.query.a, -1)
q_ents[i, 1] = ids.get(sc.query.b, -1)
q_kind[i] = QUERY_KINDS.index(sc.query.kind)
# the intervention is part of the input, not something to infer from a
# missing edge: without it "removed the trunk" and "removed a branch"
# are the same tensor and the answer is unlearnable
edit = sc.query.edit or {}
if edit.get("op") == "remove_edge":
eid2idx = {e.eid: k for k, e in enumerate(sc.obs.edges)}
edit_op[i] = 1
edit_idx[i] = eid2idx.get(edit.get("edge"), -1)
elif edit.get("op") == "remove_entity":
edit_op[i] = 2
edit_idx[i] = ids.get(edit.get("entity"), -1)
answer[i] = ANSWERS.index(sc.label.answer)
change[i] = CHANGES.index(sc.label.change)
return {
"feat": feat, "pad_mask": pad_mask,
"edge_index": edge_index, "edge_type": edge_type, "edge_mask": edge_mask,
"q_ents": q_ents, "q_kind": q_kind,
"edit_op": edit_op, "edit_idx": edit_idx,
"edge_removed": edge_removed,
"answer": answer, "change": change, "evidence": evidence,
}