"""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())