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:
1 parent
2517132a53
commit
f31288bf06
10 files changed
+1375
No files matched your search
@@ -0,0 +1,275 @@
|
||||
"""Reference checker.
|
||||
|
||||
The generator only builds structure; every label is produced here from the full
|
||||
state, then downgraded to ``unknown`` whenever the observation admits a
|
||||
different answer. That downgrade rule is what makes "evidence insufficient" a
|
||||
real label instead of a random occlusion tag:
|
||||
|
||||
answers = {answer(full), answer(full restricted to the observation)}
|
||||
if len(answers) != 1 -> unknown
|
||||
|
||||
Restricting the full state to what is visible is the cheapest way to build the
|
||||
"same observation, opposite truth" pair that the plan asks for, and it needs no
|
||||
special case per domain.
|
||||
|
||||
Nothing here imports the model, so a disagreement between the two is real.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict, deque
|
||||
from typing import Iterable, Optional
|
||||
|
||||
from .schema import (DOF_AXES, Edge, Entity, FullState, Label, Observation,
|
||||
Query)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# query edits
|
||||
|
||||
|
||||
def _removed_edge(query: Query) -> Optional[str]:
|
||||
if query.edit and query.edit.get("op") == "remove_edge":
|
||||
return query.edit.get("edge")
|
||||
return None
|
||||
|
||||
|
||||
def _removed_entity(query: Query) -> Optional[str]:
|
||||
if query.edit and query.edit.get("op") == "remove_entity":
|
||||
return query.edit.get("entity")
|
||||
return None
|
||||
|
||||
|
||||
def _alive_edges(edges: Iterable[Edge], query: Query) -> list:
|
||||
drop = _removed_edge(query)
|
||||
return [e for e in edges if e.eid != drop]
|
||||
|
||||
|
||||
def _alive_entities(entities: Iterable[Entity], query: Query) -> list:
|
||||
drop = _removed_entity(query)
|
||||
return [e for e in entities if e.eid != drop]
|
||||
|
||||
|
||||
def _index(entities: Iterable[Entity]) -> dict:
|
||||
return {e.eid: e for e in entities}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# connection
|
||||
|
||||
|
||||
def conduct_path(edges: Iterable[Edge], src: str, dst: str) -> Optional[list]:
|
||||
adj = defaultdict(list)
|
||||
for e in edges:
|
||||
if e.kind != "conduct":
|
||||
continue
|
||||
adj[e.a].append((e.b, e.eid))
|
||||
adj[e.b].append((e.a, e.eid))
|
||||
if src == dst:
|
||||
return []
|
||||
prev = {src: (None, None)}
|
||||
q = deque([src])
|
||||
while q:
|
||||
u = q.popleft()
|
||||
for v, eid in adj[u]:
|
||||
if v in prev:
|
||||
continue
|
||||
prev[v] = (u, eid)
|
||||
if v == dst:
|
||||
path = []
|
||||
while v != src:
|
||||
v, pe = prev[v]
|
||||
path.append(pe)
|
||||
return list(reversed(path))
|
||||
q.append(v)
|
||||
return None
|
||||
|
||||
|
||||
def _connection_answer(entities, edges, query: Query) -> Optional[bool]:
|
||||
idx = _index(_alive_entities(entities, query))
|
||||
if query.a not in idx or query.b not in idx:
|
||||
return None
|
||||
return conduct_path(_alive_edges(edges, query), query.a, query.b) is not None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# stability
|
||||
|
||||
|
||||
def _box(e: Entity):
|
||||
b = e.attrs.get("box")
|
||||
return tuple(b) if b else None
|
||||
|
||||
|
||||
def _overlap(a, b):
|
||||
ox0, oy0 = max(a[0], b[0]), max(a[1], b[1])
|
||||
ox1, oy1 = min(a[3], b[3]), min(a[4], b[4])
|
||||
if ox0 >= ox1 or oy0 >= oy1:
|
||||
return None
|
||||
return (ox0, oy0, ox1, oy1)
|
||||
|
||||
|
||||
def stable_blocks(entities) -> dict:
|
||||
"""{block eid: supporter eid or "ground"} for blocks that stand."""
|
||||
blocks = [e for e in entities if e.kind == "block" and _box(e)]
|
||||
support, stable = {}, set()
|
||||
changed = True
|
||||
while changed:
|
||||
changed = False
|
||||
for b in blocks:
|
||||
if b.eid in stable:
|
||||
continue
|
||||
x0, y0, z0, x1, y1, _ = _box(b)
|
||||
if z0 == 0:
|
||||
stable.add(b.eid)
|
||||
support[b.eid] = "ground"
|
||||
changed = True
|
||||
continue
|
||||
cx2, cy2 = x0 + x1, y0 + y1 # twice the centroid: stays integer
|
||||
for s in blocks:
|
||||
if s.eid == b.eid or s.eid not in stable:
|
||||
continue
|
||||
sx0, sy0, _, sx1, sy1, sz1 = _box(s)
|
||||
if sz1 != z0:
|
||||
continue
|
||||
ov = _overlap(_box(b), _box(s))
|
||||
if ov is None:
|
||||
continue
|
||||
if 2 * ov[0] <= cx2 <= 2 * ov[2] and 2 * ov[1] <= cy2 <= 2 * ov[3]:
|
||||
stable.add(b.eid)
|
||||
support[b.eid] = s.eid
|
||||
changed = True
|
||||
break
|
||||
return support
|
||||
|
||||
|
||||
def _stability_answer(entities, edges, query: Query) -> Optional[bool]:
|
||||
alive = _alive_entities(entities, query)
|
||||
part = _index(alive).get(query.a)
|
||||
if part is None or part.kind != "block":
|
||||
return None
|
||||
return query.a in stable_blocks(alive)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# freedom
|
||||
|
||||
|
||||
def _freedom_answer(entities, edges, query: Query) -> Optional[bool]:
|
||||
idx = _index(_alive_entities(entities, query))
|
||||
part = idx.get(query.a)
|
||||
if part is None or part.kind != "part":
|
||||
return None
|
||||
covered = {e.attrs.get("axis") for e in _alive_edges(edges, query) if e.kind == "constraint"}
|
||||
return len(covered & set(DOF_AXES)) == len(DOF_AXES)
|
||||
|
||||
|
||||
_ANSWER_FN = {
|
||||
"connection": _connection_answer,
|
||||
"stability": _stability_answer,
|
||||
"freedom": _freedom_answer,
|
||||
}
|
||||
|
||||
|
||||
def evaluate(entities, edges, query: Query) -> Optional[bool]:
|
||||
fn = _ANSWER_FN.get(query.kind)
|
||||
if fn is None:
|
||||
raise ValueError(f"unknown query kind {query.kind!r}")
|
||||
return fn(list(entities), list(edges), query)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# certificates
|
||||
|
||||
|
||||
def evidence_for(full: FullState, query: Query) -> list:
|
||||
"""One certificate, as edge ids. Several may be valid; the checker accepts
|
||||
any that validates."""
|
||||
edges = _alive_edges(full.edges, query)
|
||||
ents = _alive_entities(full.entities, query)
|
||||
if query.kind == "connection":
|
||||
return conduct_path(edges, query.a, query.b) or []
|
||||
if query.kind == "freedom":
|
||||
picked, seen = [], set()
|
||||
for e in edges:
|
||||
if e.kind != "constraint":
|
||||
continue
|
||||
ax = e.attrs.get("axis")
|
||||
if ax in DOF_AXES and ax not in seen:
|
||||
seen.add(ax)
|
||||
picked.append(e.eid)
|
||||
return picked if len(seen) == len(DOF_AXES) else []
|
||||
if query.kind == "stability":
|
||||
support = stable_blocks(ents)
|
||||
if query.a not in support:
|
||||
return []
|
||||
chain, cur = [], query.a
|
||||
while support.get(cur) not in (None, "ground"):
|
||||
nxt = support[cur]
|
||||
edge = next((e for e in edges if e.kind == "contact"
|
||||
and {e.a, e.b} == {cur, nxt}), None)
|
||||
if edge is None:
|
||||
break
|
||||
chain.append(edge.eid)
|
||||
cur = nxt
|
||||
return chain
|
||||
return []
|
||||
|
||||
|
||||
def validate_evidence(full: FullState, query: Query, evidence) -> bool:
|
||||
"""Independent re-check of a claimed certificate."""
|
||||
evidence = list(evidence or [])
|
||||
if not evidence or _removed_edge(query) in evidence:
|
||||
return False
|
||||
by_id = {e.eid: e for e in full.edges}
|
||||
if any(eid not in by_id for eid in evidence):
|
||||
return False
|
||||
edges = [by_id[eid] for eid in evidence]
|
||||
if query.kind == "connection":
|
||||
return conduct_path(edges, query.a, query.b) is not None
|
||||
if query.kind == "freedom":
|
||||
covered = {e.attrs.get("axis") for e in edges if e.kind == "constraint"}
|
||||
return len(covered & set(DOF_AXES)) == len(DOF_AXES)
|
||||
if query.kind == "stability":
|
||||
if any(e.kind != "contact" for e in edges):
|
||||
return False
|
||||
ents = _index(full.entities)
|
||||
if query.a not in ents:
|
||||
return False
|
||||
reached = {query.a}
|
||||
for _ in range(len(edges) + 1):
|
||||
for e in edges:
|
||||
if e.a in reached:
|
||||
reached.add(e.b)
|
||||
elif e.b in reached:
|
||||
reached.add(e.a)
|
||||
return any(eid in ents and ents[eid].kind == "ground" for eid in reached) or \
|
||||
any(eid in ents and _box(ents[eid]) is not None and _box(ents[eid])[2] == 0
|
||||
for eid in reached)
|
||||
return False
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# label
|
||||
|
||||
|
||||
def label(obs: Observation, full: FullState, query: Query,
|
||||
alternatives: Iterable[FullState] = ()) -> Label:
|
||||
"""Full state decides; the observation decides whether we may say so."""
|
||||
worlds = [full] + list(alternatives)
|
||||
answers = [evaluate(w.entities, w.edges, query) for w in worlds]
|
||||
if any(a is None for a in answers) or len(set(answers)) != 1:
|
||||
# the observation admits more than one truth: this is the real
|
||||
# "insufficient evidence" case, not an occlusion tag
|
||||
return Label(answer="unknown", change="unknown", evidence=[], sufficient=False)
|
||||
|
||||
ans_after = answers[0]
|
||||
before = Query(kind=query.kind, a=query.a, b=query.b, edit=None)
|
||||
ans_before = evaluate(full.entities, full.edges, before)
|
||||
if query.edit is None:
|
||||
change = "same"
|
||||
elif ans_before is None:
|
||||
change = "unknown"
|
||||
else:
|
||||
change = "changed" if ans_before != ans_after else "same"
|
||||
return Label(answer="true" if ans_after else "false", change=change,
|
||||
evidence=evidence_for(full, query), sufficient=True)
|
||||
Reference in new issue
Block a user