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

198 lines
7.5 KiB
Python

"""Unified entry point: smoke / train / resume / eval.
``smoke`` is the M0 gate. It does not care about accuracy; it cares that the
contract holds -- labels provably right, same seed rebuilds the same scene, the
insufficient-evidence pair really is indistinguishable, units and camera do not
move the answer, and a checkpoint survives an interruption.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from . import checker, generator
from .schema import FullState
def _load_config(path: str) -> dict:
with open(path, encoding="utf-8") as f:
cfg = json.load(f)
# configs live in spatial/configs, so the run root is the package's parent
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
cfg["out_dir"] = os.path.join(root, cfg.get("out_dir", "out_spatial/smoke"))
return cfg
def _fail(msg: str):
print(f"FAIL {msg}")
return False
def check_splits(cfg) -> bool:
d = cfg["data"]
tr, va, te = set(d["train_families"]), set(d["val_families"]), set(d["test_families"])
known = set(generator.FAMILIES)
if not (tr | va | te) <= known:
return _fail(f"unknown families: {(tr | va | te) - known}")
if tr & va or tr & te or va & te:
return _fail(f"split families overlap: {sorted(tr & va)} {sorted(tr & te)} {sorted(va & te)}")
if tr | va | te != known:
missing = known - (tr | va | te)
print(f"note families not used by any split: {sorted(missing)}")
print(f"ok splits disjoint over families: {len(tr)}/{len(va)}/{len(te)}")
return True
def check_determinism() -> bool:
ok = True
for fam in generator.FAMILIES:
a = generator.make(fam, seed=11, index=3)
b = generator.make(fam, seed=11, index=3)
if a.full_digest() != b.full_digest():
ok = _fail(f"{fam} not reproducible from the same seed")
if ok:
print("ok same seed rebuilds an identical scene (10 families)")
return ok
def check_labels() -> bool:
"""Every sufficient positive label must carry a certificate the checker
accepts, and every sufficient label must agree with a rerun on the full
state alone."""
bad = 0
n = 0
for fam in generator.FAMILIES:
for i in range(6):
sc = generator.make(fam, seed=23, index=i)
n += 1
if sc.label.sufficient:
ans = checker.evaluate(sc.full.entities, sc.full.edges, sc.query)
if (ans is True) != (sc.label.answer == "true"):
bad += 1
print(f" {fam}[{i}] label {sc.label.answer} vs checker {ans}")
if sc.label.answer == "true" and not checker.validate_evidence(
sc.full, sc.query, sc.label.evidence):
bad += 1
print(f" {fam}[{i}] certificate rejected: {sc.label.evidence}")
if bad:
return _fail(f"{bad} label/certificate mismatches over {n} samples")
print(f"ok {n} labels agree with the full-state checker, certificates validate")
return True
def check_insufficient() -> bool:
"""The point of the unknown label: identical observation, opposite truth."""
found = 0
for fam in ("cond.p1h", "area.sup2h", "dof.c6h"):
for i in range(8):
sc = generator.make(fam, seed=5, index=i)
if sc.label.answer != "unknown":
continue
restricted = FullState(entities=list(sc.obs.entities), edges=list(sc.obs.edges))
a_full = checker.evaluate(sc.full.entities, sc.full.edges, sc.query)
a_obs = checker.evaluate(restricted.entities, restricted.edges, sc.query)
if a_full != a_obs:
found += 1
else:
return _fail(f"{fam}[{i}] unknown but both worlds agree; label is not justified")
if found == 0:
return _fail("no insufficient-evidence sample was produced")
print(f"ok {found} unknown samples have same observation, different truth")
return True
def check_invariances() -> bool:
bad = 0
for fam in generator.FAMILIES:
sc = generator.make(fam, seed=31, index=1)
scaled = generator.rescale(sc, 10, "0.1mm")
if scaled.label.answer != sc.label.answer:
bad += 1
print(f" {fam} unit change moved the answer")
cam = generator.with_camera(sc, "iso")
if cam.label.answer != sc.label.answer:
bad += 1
print(f" {fam} camera change moved the answer")
if bad:
return _fail(f"{bad} invariance violations")
print("ok answer invariant to unit scaling and camera relabel")
return True
def cmd_smoke(args) -> int:
cfg = _load_config(args.config)
print(f"config {args.config} out {cfg['out_dir']}")
results = [check_splits(cfg), check_determinism(), check_labels(),
check_insufficient(), check_invariances()]
# one update, then interrupt and resume: the step counter must advance
from . import train as trainer
short = json.loads(json.dumps(cfg))
short["optim"]["steps"] = 2
short["optim"]["log_every"] = 1
short["eval"]["n"] = 12
m1 = trainer.run(short, verbose=False)
ckpt = os.path.join(short["out_dir"], "ckpt.pt")
if not os.path.exists(ckpt):
results.append(_fail("checkpoint not written"))
elif os.path.exists(ckpt + ".tmp"):
results.append(_fail("temporary checkpoint left behind"))
else:
print(f"ok checkpoint written atomically, val answer_acc {m1['answer_acc']:.2f}")
from . import train as trainer2
m2 = trainer2.run(short, resume=True, steps=1, verbose=False)
_, _, step, _ = trainer2.load(ckpt)
if step != 3:
results.append(_fail(f"resume advanced to step {step}, expected 3"))
else:
print(f"ok resume continued at step {step} (2 + 1)")
print("---")
if all(results):
print("smoke PASS")
return 0
print("smoke FAIL")
return 1
def cmd_train(args) -> int:
from . import train as trainer
cfg = _load_config(args.config)
trainer.run(cfg, resume=args.resume, steps=args.steps)
return 0
def cmd_eval(args) -> int:
from . import train as trainer
cfg = _load_config(args.config)
model, _, step, cfg = trainer.load(os.path.join(cfg["out_dir"], "ckpt.pt"))
for split in ("train", "val", "test"):
fams = cfg["data"][f"{split}_families"]
m = trainer.evaluate(model, fams, cfg["seed"], cfg["eval"]["n"])
print(f"{split:5s} " + json.dumps({k: (round(v, 3) if isinstance(v, float) else v)
for k, v in m.items() if k != "loss"}))
print(f"step {step}")
return 0
def main(argv=None) -> int:
p = argparse.ArgumentParser(prog="spatial")
sub = p.add_subparsers(dest="cmd", required=True)
for name, fn in (("smoke", cmd_smoke), ("train", cmd_train), ("eval", cmd_eval)):
sp = sub.add_parser(name)
sp.add_argument("--config", default=os.path.join(os.path.dirname(__file__), "configs", "smoke.json"))
if name != "eval":
sp.add_argument("--steps", type=int, default=None)
if name == "train":
sp.add_argument("--resume", action="store_true")
sp.set_defaults(fn=fn)
args = p.parse_args(argv)
return args.fn(args)
if __name__ == "__main__":
sys.exit(main())