Files
tiny-gpt/spatial/cli.py
T
liuhuajie 1e0dcd6fb4 test(spatial): 跨家族 digest 一致性检查——同一观测不许有两个标签
"没有隐藏支路"和"有隐藏支路但看不见"产生完全相同的观测,于是前者标可判、
后者标 unknown,是模型永远无法复现的标签:证据缺失不等于不存在。原来的
hidden_pair 只在一个家族内部查,查不到这件事。
2026-12-03 18:29:29 +08:00

243 lines
9.4 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 check_cross_family_digest() -> bool:
"""Two samples with the same ``input_digest`` must carry the same label.
This is the whole contract, and it has to hold *across* families, not only
inside one: "no hidden branch exists" and "a hidden branch exists but is not
visible" produce the same observation, so a label that says "decidable" in
the first case and "unknown" in the second is a label the model can never
reproduce -- absence of evidence is not evidence of absence. Samples whose
scores differ are still a bug, just a quieter one.
"""
seen = {}
bad = []
n = 0
for fam in generator.FAMILIES:
for i in range(40):
sc = generator.make(fam, seed=71, index=i)
n += 1
d = sc.input_digest()
prev = seen.get(d)
if prev is None:
seen[d] = (fam, sc.label.answer, sc.label.change)
elif (prev[1], prev[2]) != (sc.label.answer, sc.label.change):
bad.append((prev, (fam, sc.label.answer, sc.label.change)))
if bad:
# collapse to the distinct family pairs, the list itself is long
pairs = sorted({(a[0], b[0]) for a, b in bad})
print(f" {len(bad)} samples share an input digest with a different label")
for a, b in pairs[:6]:
print(f" {a:11s} vs {b:11s}")
return _fail("same input, different label -- the observation does not "
"determine the answer, so both cannot be decidable")
print(f"ok {n} samples: no two families assign different labels to "
f"the same observation ({len(seen)} distinct inputs)")
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(), check_cross_family_digest()]
# 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 cmd_report(args) -> int:
from . import report
report.report(args.config, n=args.n)
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),
("report", cmd_report)):
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")
if name == "report":
sp.add_argument("--n", type=int, default=128)
sp.set_defaults(fn=fn)
args = p.parse_args(argv)
return args.fn(args)
if __name__ == "__main__":
sys.exit(main())