"""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: the observation does not settle it. Under the monotone rule an unknown label no longer implies that *the one full state we hold* answers differently from the observation's own world -- it implies that the withheld content could be the missing piece. So the check is that something is withheld and the visible structure does not already prove the answer, which is exactly the condition the label promises. """ found = 0 for fam in generator.FAMILIES: 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_vis = checker.evaluate(restricted.entities, restricted.edges, sc.query) withheld = checker.withheld_flag(sc.obs) if withheld and a_vis is not True: found += 1 else: return _fail(f"{fam}[{i}] unknown without withheld content or with a " f"visible proof; label is not justified") if found == 0: return _fail("no insufficient-evidence sample was produced") print(f"ok {found} unknown samples are undecided by the observation") 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 check_extract_contacts(n: int = 8) -> bool: """The geometry provider must not invent a contact across a clearance. ``area.gap1/2/4`` place the same block 1, 2 and 4 units above its pedestal. Contact is decided by coincident faces, not by distance, so at a numerical epsilon the extractor has to report no T-P edge there -- and still report the two contacts that are real. This is the regression gate for the parameter that used to decide the answer by itself. """ from . import extract bad = set() for fam in ("area.gap1", "area.gap2", "area.gap4"): for i in range(n): sc = generator.make(fam, seed=0, index=i) if any({e.a, e.b} == {"T", "P"} for e in extract.extract_edges(sc.obs.entities, eps=1e-9)): bad.add(fam) break if bad: return _fail(f"extractor welded T to P across a clearance: {sorted(bad)}") got = len(extract.extract_edges( generator.make("area.sup2", seed=0, index=0).obs.entities, eps=1e-9)) if got != 3: return _fail(f"area.sup2: extractor found {got} contacts, expected 3") print("ok extractor: nothing welded across a clearance, 3/3 real contacts kept") return True def check_scope_agrees(n: int = 24) -> bool: """The declared inventory must say "something withheld" exactly when the diagnostic one does. ``hidden``/``dangling`` are computed from the full state, so they are not something a provider can produce. ``scope`` is. This check pins the migration: wherever the two disagree, the label path would have to fall back on full-state data -- and that is the leak M2 exists to remove. """ bad = [] rows = 0 for fam in generator.FAMILIES: for i in range(n): sc = generator.make(fam, seed=11, index=i) old = bool(sc.obs.dangling) or bool((sc.obs.hidden or {}).get("entity")) or bool((sc.obs.hidden or {}).get("edge")) new = checker.withheld_flag(sc.obs) rows += 1 if old != new: bad.append((fam, i, old, new)) if bad: fams = sorted({f for f, _, _, _ in bad}) print(f" {len(bad)}/{rows} samples disagree, families {fams}") for f, i, o, nn in bad[:4]: print(f" {f}[{i}] diagnostic={o} scope={nn}") return _fail("scope cannot express what was withheld; the label path still " "needs full-state data") print(f"ok {rows} samples: declared inventory agrees with the diagnostic one") 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(), check_extract_contacts(), check_scope_agrees()] # 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) if args.seed is not None: cfg["seed"] = args.seed cfg["out_dir"] = f"{cfg['out_dir']}_s{args.seed}" 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) if args.seed is not None: cfg["seed"] = args.seed cfg["out_dir"] = f"{cfg['out_dir']}_s{args.seed}" 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, ablate=args.ablate, seed=args.seed) 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")) sp.add_argument("--seed", type=int, default=None, help="override config seed (data and init both follow it)") 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.add_argument("--ablate", default=None, choices=[None, "dangling", "scene", "edge_feat", "dangling,scene"]) sp.set_defaults(fn=fn) args = p.parse_args(argv) return args.fn(args) if __name__ == "__main__": sys.exit(main())