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:
liuhuajie committed 2026-12-03 16:13:38 +08:00
1 parent 2517132a53
commit f31288bf06
10 files changed
+1375

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
"""Spatial-structure foundation.
A slice of the plan in ``mm/SPATIAL_FOUNDATION.md``: one observation contract,
one procedural generator, one reference checker, one bidirectional backbone,
and a CLI that can smoke / train / resume / eval.
M0 is CPU-only on purpose -- the point is that the labels are provably right
before any GPU time is spent learning them.
"""
__all__ = ["schema", "generator", "checker", "model", "train", "cli"]
+275
View File
@@ -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)
+197
View File
@@ -0,0 +1,197 @@
"""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())
+12
View File
@@ -0,0 +1,12 @@
{
"seed": 0,
"model": { "d": 192, "n_layer": 4, "n_head": 6, "dropout": 0.0, "max_entities": 32 },
"data": {
"train_families": ["cond.p3"],
"val_families": ["cond.p3"],
"test_families": ["cond.p3"]
},
"optim": { "lr": 0.003, "weight_decay": 0.01, "steps": 400, "batch": 32, "log_every": 100 },
"eval": { "n": 96 },
"out_dir": "out_spatial/floor"
}
+12
View File
@@ -0,0 +1,12 @@
{
"seed": 0,
"model": { "d": 64, "n_layer": 2, "n_head": 4, "dropout": 0.0, "max_entities": 32 },
"data": {
"train_families": ["cond.p1", "area.sup2", "dof.c6"],
"val_families": ["cond.p3", "area.sup3", "dof.c6r"],
"test_families": ["cond.p1h", "cond.p3h", "area.sup2h", "dof.c6h"]
},
"optim": { "lr": 0.003, "weight_decay": 0.01, "steps": 2, "batch": 16, "log_every": 1 },
"eval": { "n": 12 },
"out_dir": "out_spatial/smoke"
}
+137
View File
@@ -0,0 +1,137 @@
"""Tensorisation.
Padding lives here and only here. A scenario with more entities than
``max_entities`` is rejected explicitly -- the plan forbids silently truncating
a scene, because cutting a node can turn "still connected" into "disconnected"
and quietly corrupt the label.
"""
from __future__ import annotations
import torch
from collections import deque
from .schema import ANSWERS, CHANGES, EDGE_KINDS, ENTITY_KINDS, Scenario
from .model import FEAT_DIM, QUERY_KINDS
def _reach(edges, src: str, alive) -> set:
adj = {}
for e in edges:
if not alive(e):
continue
adj.setdefault(e.a, []).append(e.b)
adj.setdefault(e.b, []).append(e.a)
seen, q = {src}, deque([src])
while q:
u = q.popleft()
for v in adj.get(u, ()):
if v not in seen:
seen.add(v)
q.append(v)
return seen
def evidence_target(sc: Scenario) -> set:
"""Every edge that can appear in *some* valid certificate counts as positive.
For a connection the checker returns one shortest path, but any a-b path is
a correct answer; training against a single one marks its equally valid
siblings as negatives and the head learns nothing usable. An edge lies on
some a-b path exactly when it can be traversed from a towards b.
"""
if sc.query.kind == "connection" and sc.label.answer == "true":
removed = (sc.query.edit or {}).get("edge")
alive = lambda e: e.eid != removed
ra = _reach(sc.obs.edges, sc.query.a, alive)
rb = _reach(sc.obs.edges, sc.query.b, alive)
return {e.eid for e in sc.obs.edges
if e.eid != removed
and ((e.a in ra and e.b in rb) or (e.b in ra and e.a in rb))}
return set(sc.label.evidence or [])
def _unit_onehot(per_unit: int):
return {1: 0, 10: 1, 100: 2}.get(per_unit, 0)
def entity_features(sc: Scenario, e) -> list:
f = [0.0] * FEAT_DIM
f[ENTITY_KINDS.index(e.kind)] = 1.0
f[len(ENTITY_KINDS) + (0 if e.source == "given" else 1)] = 1.0
f[len(ENTITY_KINDS) + 2 + _unit_onehot(sc.obs.units.get("per_unit", 1))] = 1.0
base = len(ENTITY_KINDS) + 2 + 3
scale = 200.0 * max(1, sc.obs.units.get("per_unit", 1))
box = e.attrs.get("box")
if box:
cx, cy, cz = (box[0] + box[3]) / 2, (box[1] + box[4]) / 2, (box[2] + box[5]) / 2
d = [cx / scale, cy / scale, cz / scale, e.attrs.get("layer", 0) / 6.0,
(box[3] - box[0]) / scale, (box[4] - box[1]) / scale, (box[5] - box[2]) / scale]
else:
d = [e.attrs.get("x", 0) / scale, e.attrs.get("y", 0) / scale,
e.attrs.get("z", 0) / scale, e.attrs.get("layer", 0) / 6.0, 0.0, 0.0, 0.0]
f[base:base + 7] = d
return f
def collate(batch, max_entities: int = 32):
B = len(batch)
N = max(1, max(len(sc.obs.entities) for sc in batch))
E = max(1, max(len(sc.obs.edges) for sc in batch))
if N > max_entities:
raise ValueError(f"scene needs {N} entity slots > max_entities {max_entities}; "
"bucket it instead of truncating")
feat = torch.zeros(B, N, FEAT_DIM)
pad_mask = torch.ones(B, N, dtype=torch.bool)
edge_index = torch.zeros(B, E, 2, dtype=torch.long)
edge_type = torch.zeros(B, E, dtype=torch.long)
edge_mask = torch.zeros(B, E, dtype=torch.bool)
evidence = torch.zeros(B, E)
edge_removed = torch.zeros(B, E)
q_ents = torch.full((B, 2), -1, dtype=torch.long)
q_kind = torch.zeros(B, dtype=torch.long)
edit_op = torch.zeros(B, dtype=torch.long) # 0 none, 1 remove_edge, 2 remove_entity
edit_idx = torch.full((B,), -1, dtype=torch.long)
answer = torch.zeros(B, dtype=torch.long)
change = torch.zeros(B, dtype=torch.long)
for i, sc in enumerate(batch):
ids = {e.eid: j for j, e in enumerate(sc.obs.entities)}
for j, e in enumerate(sc.obs.entities):
feat[i, j] = torch.tensor(entity_features(sc, e))
pad_mask[i, j] = False
ev = evidence_target(sc)
for k, ed in enumerate(sc.obs.edges):
edge_index[i, k, 0] = ids.get(ed.a, 0)
edge_index[i, k, 1] = ids.get(ed.b, 0)
edge_type[i, k] = EDGE_KINDS.index(ed.kind)
edge_mask[i, k] = True
evidence[i, k] = 1.0 if ed.eid in ev else 0.0
if (sc.query.edit or {}).get("edge") == ed.eid:
edge_removed[i, k] = 1.0
q_ents[i, 0] = ids.get(sc.query.a, -1)
q_ents[i, 1] = ids.get(sc.query.b, -1)
q_kind[i] = QUERY_KINDS.index(sc.query.kind)
# the intervention is part of the input, not something to infer from a
# missing edge: without it "removed the trunk" and "removed a branch"
# are the same tensor and the answer is unlearnable
edit = sc.query.edit or {}
if edit.get("op") == "remove_edge":
eid2idx = {e.eid: k for k, e in enumerate(sc.obs.edges)}
edit_op[i] = 1
edit_idx[i] = eid2idx.get(edit.get("edge"), -1)
elif edit.get("op") == "remove_entity":
edit_op[i] = 2
edit_idx[i] = ids.get(edit.get("entity"), -1)
answer[i] = ANSWERS.index(sc.label.answer)
change[i] = CHANGES.index(sc.label.change)
return {
"feat": feat, "pad_mask": pad_mask,
"edge_index": edge_index, "edge_type": edge_type, "edge_mask": edge_mask,
"q_ents": q_ents, "q_kind": q_kind,
"edit_op": edit_op, "edit_idx": edit_idx,
"edge_removed": edge_removed,
"answer": answer, "change": change, "evidence": evidence,
}
+212
View File
@@ -0,0 +1,212 @@
"""Procedural scenes.
Three domains, each built so that a *structure family* -- not a single sample --
is the unit of split. Families differ in topology depth and in what the
observation withholds, never in rendering noise, so a test family is genuinely
unseen structure.
Builders only construct geometry and visible subsets. They never write a label:
``checker.label`` does that, using the full state plus the world obtained by
restricting the full state to what the observation shows.
"""
from __future__ import annotations
import random
from dataclasses import replace
from . import checker
from .schema import (DOF_AXES, Edge, Entity, FullState, Observation, Query,
Scenario)
# family -> builder parameters. Splits are assigned in configs/*.json and must
# be disjoint over families.
FAMILIES = {
"cond.p1": {"domain": "connection", "n_paths": 1, "hidden": 0},
"cond.p3": {"domain": "connection", "n_paths": 3, "hidden": 0},
"cond.p1h": {"domain": "connection", "n_paths": 2, "hidden": 1},
"cond.p3h": {"domain": "connection", "n_paths": 4, "hidden": 1},
"area.sup2": {"domain": "stability", "n_blocks": 2, "hidden": 0},
"area.sup3": {"domain": "stability", "n_blocks": 3, "hidden": 0},
"area.sup2h": {"domain": "stability", "n_blocks": 2, "hidden": 1},
"dof.c6": {"domain": "freedom", "n_cons": 6, "hidden": 0},
"dof.c6r": {"domain": "freedom", "n_cons": 7, "hidden": 0},
"dof.c6h": {"domain": "freedom", "n_cons": 6, "hidden": 1},
}
DOMAIN_OF = {f: spec["domain"] for f, spec in FAMILIES.items()}
def _observe(entities, edges, visible_edges, visible_ents, hidden_layers, cameras, units):
vis_e = [e for e in edges if e.eid in visible_edges]
keep = set(visible_ents) | {e.a for e in vis_e} | {e.b for e in vis_e}
return Observation(
entities=[e for e in entities if e.eid in keep],
edges=vis_e,
cameras=list(cameras),
units=dict(units),
hidden_layers=sorted(hidden_layers),
)
# --------------------------------------------------------------------------
# connection: parallel branches into one trunk, optional inner-layer branch
#
# A --branch i--> M --trunk--> B
#
# removing one branch is harmless while another exists; removing the trunk is
# never harmless. With one visible branch and one hidden branch the observation
# cannot tell those apart.
def _build_connection(rng, n_paths: int, hidden: int):
ents = [Entity("A", "pad", attrs={"x": 0, "y": 0, "z": 0, "layer": 0}),
Entity("B", "pad", attrs={"x": 100, "y": 0, "z": 0, "layer": 0}),
Entity("M", "via", attrs={"x": 50, "y": 0, "z": 0, "layer": 0})]
edges, visible, layers = [], set(), set()
branch_edges = []
for i in range(n_paths):
is_hidden = i >= (n_paths - hidden)
layer = (1 + i % 2) if is_hidden else 0
vid = f"V{i}"
ents.append(Entity(vid, "via", attrs={"x": 50, "y": 10 * (i + 1), "z": layer, "layer": layer}))
e1 = Edge(f"c{i}a", "conduct", "A", vid, layer=layer)
e2 = Edge(f"c{i}b", "conduct", vid, "M", layer=layer)
edges += [e1, e2]
if layer == 0:
visible.update({e1.eid, e2.eid})
branch_edges += [e1.eid, e2.eid]
else:
layers.add(layer)
trunk = Edge("trunk", "conduct", "M", "B", layer=0)
edges.append(trunk)
visible.add(trunk.eid)
query = Query(kind="connection", a="A", b="B")
r = rng.random()
if r < 0.4 and branch_edges:
query.edit = {"op": "remove_edge", "edge": branch_edges[0]}
elif r < 0.7:
query.edit = {"op": "remove_edge", "edge": "trunk"}
# a hidden branch must not appear as an isolated node either: the mere
# presence of a via on layer 1 is already a leak of the hidden detour
vis_ents = {"A", "B", "M"} | {f"V{i}" for i in range(n_paths - hidden)}
return ents, edges, query, visible, vis_ents, layers, ["top"], {"length": "mm", "per_unit": 1}
# --------------------------------------------------------------------------
# stability: stacked blocks, optional hidden pedestal
def _build_stability(rng, n_blocks: int, hidden: int):
ents = [Entity("G", "ground", attrs={"plane": 0}),
Entity("P", "block", attrs={"box": [40, 40, 0, 60, 60, 20]}),
Entity("T", "block", attrs={"box": [42, 42, 20, 58, 58, 36]})]
edges = [Edge("kPG", "contact", "P", "G"), Edge("kPT", "contact", "T", "P")]
if n_blocks >= 3:
ents.append(Entity("U", "block", attrs={"box": [44, 44, 36, 56, 56, 48]}))
edges.append(Edge("kTU", "contact", "U", "T"))
vis_edges = {e.eid for e in edges}
vis_ents = {e.eid for e in ents}
layers = set()
if hidden:
# the pedestal sits behind the front face: its contacts are unseen, and
# the pedestal itself is not in view
for e in list(edges):
if "P" in (e.a, e.b):
vis_edges.discard(e.eid)
vis_ents.discard("P")
target = "U" if n_blocks >= 3 else "T"
query = Query(kind="stability", a=target)
# an edit can only name something the observation shows; with the pedestal
# hidden the only legal edit is "nothing changes"
if not hidden and rng.random() < 0.5:
query.edit = {"op": "remove_entity", "entity": "P"}
return ents, edges, query, vis_edges, vis_ents, layers, ["front", "iso"], {"length": "mm", "per_unit": 1}
# --------------------------------------------------------------------------
# freedom: constraint sets, optionally redundant on one axis
def _build_freedom(rng, n_cons: int, hidden: int):
axes = list(DOF_AXES) + ["tz"] # a 7th constraint repeats tz: redundant
ents = [Entity("P", "part", attrs={"x": 0, "y": 0, "z": 0})]
edges, visible = [], set()
for i in range(n_cons):
fid = f"F{i}"
ents.append(Entity(fid, "ground", attrs={"x": 0, "y": 0, "z": 0}))
e = Edge(f"k{i}", "constraint", "P", fid, attrs={"axis": axes[i]})
edges.append(e)
visible.add(e.eid)
vis_ents = {e.eid for e in ents}
layers = set()
if hidden:
visible.discard("k5") # one mate lives in the part definition
vis_ents.discard("F5")
query = Query(kind="freedom", a="P")
if n_cons == 7:
# removing the duplicate must not change the verdict; that is the point
query.edit = {"op": "remove_edge", "edge": "k6"}
elif rng.random() < 0.6:
query.edit = {"op": "remove_edge", "edge": "k0"}
return ents, edges, query, visible, vis_ents, layers, ["iso"], {"length": "mm", "per_unit": 1}
_BUILDERS = {
"connection": lambda rng, spec: _build_connection(rng, spec["n_paths"], spec["hidden"]),
"stability": lambda rng, spec: _build_stability(rng, spec["n_blocks"], spec["hidden"]),
"freedom": lambda rng, spec: _build_freedom(rng, spec["n_cons"], spec["hidden"]),
}
def make(family: str, seed: int, index: int = 0) -> Scenario:
spec = FAMILIES[family]
rng = random.Random(f"{family}:{seed}:{index}")
ents, edges, query, vis_edges, vis_ents, layers, cameras, units = \
_BUILDERS[spec["domain"]](rng, spec)
full = FullState(entities=ents, edges=edges)
obs = _observe(ents, edges, vis_edges, vis_ents, layers, cameras, units)
# the world the observation alone describes: anything not visible is gone
restricted = FullState(entities=list(obs.entities), edges=list(obs.edges))
sc = Scenario(key=f"{family}-{seed}-{index:04d}", domain=spec["domain"],
family=family, seed=seed, obs=obs, query=query, full=full,
tags={"n_hidden": spec["hidden"], "edit": query.edit is not None})
sc.label = checker.label(obs, full, query, alternatives=[restricted])
return sc
# --------------------------------------------------------------------------
# invariances: camera and units must not change the answer
def with_camera(sc: Scenario, camera: str) -> Scenario:
out = replace(sc, obs=replace(sc.obs, cameras=[camera]))
out.tags = dict(sc.tags, camera=camera)
return out
def rescale(sc: Scenario, factor: int, unit: str) -> Scenario:
"""Multiply integer geometry by ``factor`` and relabel the unit. The answer
must be invariant; the fixture checks that it actually is."""
def scale_ent(e: Entity) -> Entity:
attrs = dict(e.attrs)
for k in ("x", "y", "z"):
if k in attrs:
attrs[k] = attrs[k] * factor
if "box" in attrs:
attrs["box"] = [v * factor for v in attrs["box"]]
return replace(e, attrs=attrs, unit=unit)
full = FullState(entities=[scale_ent(e) for e in sc.full.entities], edges=list(sc.full.edges))
obs = replace(sc.obs, entities=[scale_ent(e) for e in sc.obs.entities],
edges=list(sc.obs.edges),
units={"length": unit, "per_unit": factor})
out = replace(sc, obs=obs, full=full, tags=dict(sc.tags, unit=unit, scale=factor))
return out
+158
View File
@@ -0,0 +1,158 @@
"""Bidirectional relation backbone (deliberately small).
Differences from ``mm/model.py``, and why they are not negotiable here:
* **no causal mask** -- a query may sit on any entity and relations are
symmetric; an autoregressive mask would make the answer depend on an
arbitrary serialisation order.
* **edge types are attention biases** -- adjacency alone cannot express
"contact" vs "constraint" vs "conduct", and those three mean different things
for the same pair of nodes.
* **one query token, not a token per entity** -- the output is about a query,
not about the next token.
The size is a smoke-test size (2 layers, 64 wide). The plan's 6/384 is a
config change; nothing in this file assumes 64.
"""
from __future__ import annotations
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .schema import EDGE_KINDS, ENTITY_KINDS
N_KIND = len(ENTITY_KINDS)
N_EDGE = len(EDGE_KINDS)
FEAT_DIM = N_KIND + 2 + 3 + 7 # kind, source, unit, (x,y,z,layer,w,h,d)
QUERY_KINDS = ("connection", "stability", "freedom")
class Block(nn.Module):
def __init__(self, d: int, n_head: int, dropout: float = 0.0):
super().__init__()
self.n_head = n_head
self.ln1 = nn.LayerNorm(d)
self.qkv = nn.Linear(d, 3 * d, bias=False)
self.proj = nn.Linear(d, d, bias=False)
self.ln2 = nn.LayerNorm(d)
self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
self.drop = nn.Dropout(dropout)
def forward(self, x, bias, pad_mask):
B, N, d = x.shape
h = self.ln1(x)
q, k, v = self.qkv(h).view(B, N, 3, self.n_head, d // self.n_head).permute(2, 0, 3, 1, 4)
att = (q @ k.transpose(-2, -1)) / math.sqrt(d // self.n_head)
att = att + bias
att = att.masked_fill(pad_mask[:, None, None, :], float("-inf"))
att = self.drop(att.softmax(dim=-1))
y = (att @ v).transpose(1, 2).reshape(B, N, d)
x = x + self.drop(self.proj(y))
x = x + self.drop(self.mlp(self.ln2(x)))
return x
class RelationBackbone(nn.Module):
def __init__(self, d: int = 64, n_layer: int = 2, n_head: int = 4,
dropout: float = 0.0, max_entities: int = 32):
super().__init__()
self.d = d
self.max_entities = max_entities
self.ent_proj = nn.Sequential(nn.Linear(FEAT_DIM, d), nn.GELU(), nn.Linear(d, d))
self.query_emb = nn.Embedding(len(QUERY_KINDS), d)
self.edit_op_emb = nn.Embedding(3, d) # none / remove_edge / remove_entity
# direction matters: a constraint points from the part to the fixture, a
# conduct edge from source to sink. Two tables, not one symmetric table.
self.edge_bias = nn.Parameter(torch.zeros(N_EDGE, n_head))
self.edge_bias_inv = nn.Parameter(torch.zeros(N_EDGE, n_head))
self.none_bias = nn.Parameter(torch.zeros(n_head))
# the intervention as an edge flag: a global token tells the model that
# something was removed, not which edge, and the evidence head needs the
# latter to exclude the removed edge from its certificate
self.removed_bias = nn.Parameter(torch.zeros(n_head))
self.blocks = nn.ModuleList([Block(d, n_head, dropout) for _ in range(n_layer)])
self.ln_f = nn.LayerNorm(d)
self.answer_head = nn.Linear(d, 3)
self.change_head = nn.Linear(d, 3)
self.evidence_head = nn.Sequential(nn.Linear(2 * d, d), nn.GELU(), nn.Linear(d, 1))
# the evidence head used to see only the two endpoint embeddings, so it
# could not tell a removed edge from a live one. Edge identity has to be
# part of the score, not just part of the attention bias.
self.edge_emb = nn.Embedding(N_EDGE, d)
self.removed_emb = nn.Embedding(2, d)
def forward(self, feat, pad_mask, edge_index, edge_type, edge_mask, q_ents, q_kind,
edit_op=None, edit_idx=None, edge_removed=None):
B, N, _ = feat.shape
device = feat.device
h = self.ent_proj(feat)
# query token is read out of the two entities it names
q = self.query_emb(q_kind).unsqueeze(1).expand(B, 1, self.d).clone()
valid_a = (q_ents[:, 0] >= 0).unsqueeze(-1)
valid_b = (q_ents[:, 1] >= 0).unsqueeze(-1)
ent_pad = torch.cat([torch.ones(B, 1, dtype=torch.bool, device=device), pad_mask], dim=1)
a_idx = q_ents[:, 0].clamp(min=0)
b_idx = q_ents[:, 1].clamp(min=0)
q = q + torch.where(valid_a.unsqueeze(-1), h[torch.arange(B), a_idx].unsqueeze(1),
torch.zeros_like(q))
q = q + torch.where(valid_b.unsqueeze(-1), h[torch.arange(B), b_idx].unsqueeze(1),
torch.zeros_like(q))
# the intervention itself: which edge or entity the question removes
if edit_op is not None and edit_idx is not None:
ar = torch.arange(B, device=device)
# separate clamps: an entity index can exceed the padded edge count
tgt_ent = h[ar, edit_idx.clamp(min=0, max=N - 1)]
pair = edge_index[ar, edit_idx.clamp(min=0, max=edge_index.size(1) - 1)]
tgt_edge = h[ar, pair[:, 0].clamp(min=0)] + h[ar, pair[:, 1].clamp(min=0)]
tgt = torch.where((edit_op == 1).unsqueeze(-1), tgt_edge, tgt_ent)
has = (edit_op > 0).unsqueeze(-1).to(q.dtype)
q = q + self.edit_op_emb(edit_op).unsqueeze(1) + (tgt * has).unsqueeze(1)
x = torch.cat([q, h], dim=1) # (B, 1+N, d)
pad = ent_pad # (B, 1+N)
# edge-type bias: only where an edge exists, and asymmetric per direction
n_head = self.blocks[0].n_head
bias = self.none_bias.view(1, n_head, 1, 1).expand(B, n_head, N + 1, N + 1).clone()
src = edge_index[..., 0] + 1
dst = edge_index[..., 1] + 1
bidx = torch.arange(B, device=device).unsqueeze(1).expand_as(src)
for t in range(N_EDGE):
m = (edge_type == t) & edge_mask
if not m.any():
continue
b_idx, s_idx, d_idx = bidx[m], src[m], dst[m]
bias[b_idx, :, s_idx, d_idx] = bias[b_idx, :, s_idx, d_idx] + self.edge_bias[t].unsqueeze(0)
bias[b_idx, :, d_idx, s_idx] = bias[b_idx, :, d_idx, s_idx] + self.edge_bias_inv[t].unsqueeze(0)
if edge_removed is not None:
rm = (edge_removed > 0) & edge_mask
if rm.any():
b_idx, s_idx, d_idx = bidx[rm], src[rm], dst[rm]
bias[b_idx, :, s_idx, d_idx] = bias[b_idx, :, s_idx, d_idx] + self.removed_bias.unsqueeze(0)
bias[b_idx, :, d_idx, s_idx] = bias[b_idx, :, d_idx, s_idx] + self.removed_bias.unsqueeze(0)
for blk in self.blocks:
x = blk(x, bias, pad)
x = self.ln_f(x)
q_out, ent_out = x[:, 0], x[:, 1:]
# evidence: score every edge by its endpoints and the query
ea = ent_out[torch.arange(B).unsqueeze(1), edge_index[..., 0].clamp(min=0)]
eb = ent_out[torch.arange(B).unsqueeze(1), edge_index[..., 1].clamp(min=0)]
e_feat = self.edge_emb(edge_type)
if edge_removed is not None:
e_feat = e_feat + self.removed_emb((edge_removed > 0).long())
pair = torch.cat([ea + eb + e_feat, q_out.unsqueeze(1).expand_as(ea)], dim=-1)
ev_logits = self.evidence_head(pair).squeeze(-1)
return {
"answer": self.answer_head(q_out),
"change": self.change_head(q_out),
"evidence": ev_logits,
}
+188
View File
@@ -0,0 +1,188 @@
"""Data contract for the spatial-structure task.
Two records per sample, and the split between them is the whole point:
``Observation``
Everything the model may read. Visible entities and edges only. A hidden
inner-layer trace, a contact on the back face, or a constraint that lives in
a mate definition is simply absent here -- not masked, absent.
``FullState``
Everything the checker and the generator know. Never reaches the model.
If a generator bug leaks a hidden edge into the observation the fixture
``hidden_pair`` catches it, because that fixture builds two samples with
identical observation digests and opposite full-state answers.
Everything is integer geometry on a 0.25 mm grid, so a digest is reproducible
across machines and a "same seed rebuilds the same digest" check means
something.
"""
from __future__ import annotations
import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional
EDGE_KINDS = ("contain", "adjacent", "contact", "constraint", "conduct")
ENTITY_KINDS = ("pad", "via", "trace", "block", "part", "ground")
ANSWERS = ("true", "false", "unknown")
CHANGES = ("changed", "same", "unknown")
DOF_AXES = ("tx", "ty", "tz", "rx", "ry", "rz")
def canonical(obj) -> str:
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
def digest(obj) -> str:
return hashlib.sha256(canonical(obj).encode("utf-8")).hexdigest()
@dataclass
class Entity:
eid: str
kind: str
frame: str = "world"
unit: str = "mm"
source: str = "given"
attrs: dict = field(default_factory=dict)
def to_dict(self) -> dict:
return {
"eid": self.eid,
"kind": self.kind,
"frame": self.frame,
"unit": self.unit,
"source": self.source,
"attrs": dict(sorted(self.attrs.items())),
}
@dataclass
class Edge:
eid: str
kind: str
a: str
b: str
layer: int = 0
source: str = "given"
attrs: dict = field(default_factory=dict)
def to_dict(self) -> dict:
return {
"eid": self.eid,
"kind": self.kind,
"a": self.a,
"b": self.b,
"layer": self.layer,
"source": self.source,
"attrs": dict(sorted(self.attrs.items())),
}
@dataclass
class Observation:
"""What the model sees. Only visible items are stored here."""
entities: list = field(default_factory=list)
edges: list = field(default_factory=list)
cameras: list = field(default_factory=list)
units: dict = field(default_factory=lambda: {"length": "mm", "per_unit": 1})
hidden_layers: list = field(default_factory=list)
hidden_faces: list = field(default_factory=list)
def entity_ids(self) -> set:
return {e.eid for e in self.entities}
def to_dict(self) -> dict:
return {
"entities": [e.to_dict() for e in sorted(self.entities, key=lambda x: x.eid)],
"edges": [e.to_dict() for e in sorted(self.edges, key=lambda x: x.eid)],
"cameras": list(self.cameras),
"units": dict(self.units),
"hidden_layers": sorted(self.hidden_layers),
"hidden_faces": sorted(self.hidden_faces),
}
@dataclass
class FullState:
"""Everything, including what the observation omits."""
entities: list = field(default_factory=list)
edges: list = field(default_factory=list)
def to_dict(self) -> dict:
return {
"entities": [e.to_dict() for e in sorted(self.entities, key=lambda x: x.eid)],
"edges": [e.to_dict() for e in sorted(self.edges, key=lambda x: x.eid)],
}
@dataclass
class Query:
kind: str # "connection" | "stability" | "freedom"
a: str = ""
b: str = ""
edit: Optional[dict] = None # {"op": "remove_edge", "edge": "<eid>"}
def to_dict(self) -> dict:
return {"kind": self.kind, "a": self.a, "b": self.b, "edit": self.edit}
@dataclass
class Label:
answer: str = "unknown" # one of ANSWERS
change: str = "unknown" # one of CHANGES
evidence: list = field(default_factory=list) # edge ids
sufficient: bool = False # observation alone decides the answer
def to_dict(self) -> dict:
return {
"answer": self.answer,
"change": self.change,
"evidence": sorted(self.evidence),
"sufficient": self.sufficient,
}
@dataclass
class Scenario:
key: str
domain: str
family: str
seed: int
obs: Observation
query: Query
full: FullState
label: Label = field(default_factory=Label)
tags: dict = field(default_factory=dict)
# ---- digests -------------------------------------------------------
def input_dict(self) -> dict:
"""Exactly what the model may read. Two samples with the same digest
must be indistinguishable to the model, whatever their labels are."""
return {"obs": self.obs.to_dict(), "query": self.query.to_dict()}
def input_digest(self) -> str:
return digest(self.input_dict())
def full_digest(self) -> str:
return digest({"full": self.full.to_dict(), "query": self.query.to_dict(),
"obs": self.obs.to_dict()})
def to_dict(self) -> dict:
return {
"key": self.key,
"domain": self.domain,
"family": self.family,
"seed": self.seed,
"obs": self.obs.to_dict(),
"query": self.query.to_dict(),
"label": self.label.to_dict(),
"full": self.full.to_dict(),
"tags": dict(sorted(self.tags.items())),
"input_digest": self.input_digest(),
}
+173
View File
@@ -0,0 +1,173 @@
"""Train / resume / eval on the relational task.
Two contract points from the plan that the old ``mm/train.py`` could not meet:
* checkpoints are replaced atomically and carry optimizer, step and RNG state,
so an interrupted run continues into the same next batch;
* evaluation reports over-confidence on insufficient-evidence samples and
certificate validity, not just accuracy -- a model that answers "true"
everywhere would look fine on accuracy alone.
"""
from __future__ import annotations
import json
import os
import random
import time
import torch
import torch.nn.functional as F
from . import checker, generator
from .data import collate
from .model import RelationBackbone, QUERY_KINDS
def make_batch(families, seed: int, step: int, batch_size: int):
rng = random.Random(f"batch:{seed}:{step}")
out = []
for _ in range(batch_size):
fam = rng.choice(families)
out.append(generator.make(fam, seed=seed, index=rng.randrange(10 ** 6)))
return out
def batch_loss(model, tensors):
out = model(tensors["feat"], tensors["pad_mask"], tensors["edge_index"],
tensors["edge_type"], tensors["edge_mask"], tensors["q_ents"], tensors["q_kind"],
tensors.get("edit_op"), tensors.get("edit_idx"), tensors.get("edge_removed"))
l_ans = F.cross_entropy(out["answer"], tensors["answer"])
l_chg = F.cross_entropy(out["change"], tensors["change"])
ev_logits = out["evidence"][tensors["edge_mask"]]
ev_target = tensors["evidence"][tensors["edge_mask"]]
l_ev = F.binary_cross_entropy_with_logits(ev_logits, ev_target) if ev_logits.numel() else l_ans * 0
total = l_ans + 0.5 * l_chg + 0.5 * l_ev
return total, {"answer": float(l_ans.detach()), "change": float(l_chg.detach()),
"evidence": float(l_ev.detach())}, out
@torch.no_grad()
def evaluate(model, families, seed: int, n: int, max_entities: int = 32) -> dict:
model.eval()
batch = make_batch(families, seed + 1, 0, n)[:n]
device = next(model.parameters()).device
tensors = collate(batch, max_entities)
tensors = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in tensors.items()}
_, losses, out = batch_loss(model, tensors)
pred = out["answer"].argmax(-1).tolist()
pred_chg = out["change"].argmax(-1).tolist()
answerable = [i for i, sc in enumerate(batch) if sc.label.answer != "unknown"]
unknown = [i for i, sc in enumerate(batch) if sc.label.answer == "unknown"]
correct = sum(1 for i in answerable if pred[i] == ["true", "false", "unknown"].index(batch[i].label.answer))
overconfident = sum(1 for i in unknown if pred[i] != 2)
chg_rows = [i for i, sc in enumerate(batch) if sc.label.change != "unknown"]
chg_correct = sum(1 for i in chg_rows
if pred_chg[i] == ["changed", "same", "unknown"].index(batch[i].label.change))
# certificate check on rows the model calls "true"
probs = torch.sigmoid(out["evidence"])
valid = total = 0
for i, sc in enumerate(batch):
if pred[i] != 0:
continue
ids = [e.eid for e in sc.obs.edges]
picked = [ids[k] for k in range(len(ids)) if probs[i, k] > 0.5]
total += 1
valid += int(bool(picked) and checker.validate_evidence(sc.full, sc.query, picked))
model.train()
return {
"answer_acc": correct / max(1, len(answerable)),
"answerable": len(answerable),
"overconf": overconfident / max(1, len(unknown)),
"n_unknown": len(unknown),
"change_acc": chg_correct / max(1, len(chg_rows)),
"evidence_valid": valid / max(1, total),
"n_true_pred": total,
"loss": losses,
}
def save(path: str, model, opt, step: int, config: dict):
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
torch.save({
"model": model.state_dict(),
"opt": opt.state_dict() if opt is not None else None,
"step": step,
"config": config,
"torch_rng": torch.get_rng_state(),
"py_rng": random.getstate(),
}, tmp)
os.replace(tmp, path) # atomic: a crash leaves the old file intact
def load(path: str, device="cpu"):
# always restore on CPU: map_location=device would drag the RNG state (a
# ByteTensor) onto the GPU, and set_rng_state only accepts a CPU one
ck = torch.load(path, map_location="cpu", weights_only=False)
cfg = ck["config"]["model"]
model = RelationBackbone(d=cfg["d"], n_layer=cfg["n_layer"], n_head=cfg["n_head"],
dropout=cfg["dropout"], max_entities=cfg["max_entities"])
model.load_state_dict(ck["model"])
opt = torch.optim.AdamW(model.parameters(), lr=ck["config"]["optim"]["lr"],
weight_decay=ck["config"]["optim"]["weight_decay"])
if ck.get("opt"):
opt.load_state_dict(ck["opt"])
torch.set_rng_state(ck["torch_rng"].to(torch.uint8))
random.setstate(ck["py_rng"])
if ck.get("opt"):
# the checkpoint is restored on CPU, so the moment and variance buffers
# have to follow the parameters onto the device
for state in opt.state.values():
for key, val in state.items():
if torch.is_tensor(val):
state[key] = val.to(device)
model.to(device)
return model, opt, ck["step"], ck["config"]
def run(config: dict, resume: bool = False, steps: int = None, verbose: bool = True) -> dict:
device = "cuda" if torch.cuda.is_available() else "cpu"
torch.manual_seed(config["seed"])
out_dir = config["out_dir"]
ckpt = os.path.join(out_dir, "ckpt.pt")
if resume and os.path.exists(ckpt):
model, opt, start, config = load(ckpt, device)
if verbose:
print(f"resume from step {start}")
else:
m = config["model"]
model = RelationBackbone(d=m["d"], n_layer=m["n_layer"], n_head=m["n_head"],
dropout=m["dropout"], max_entities=m["max_entities"])
opt = torch.optim.AdamW(model.parameters(), lr=config["optim"]["lr"],
weight_decay=config["optim"]["weight_decay"])
start = 0
model.to(device).train()
total_steps = start + (steps if steps is not None else config["optim"]["steps"])
t0 = time.time()
for step in range(start, total_steps):
batch = make_batch(config["data"]["train_families"], config["seed"], step,
config["optim"]["batch"])
tensors = collate(batch, config["model"]["max_entities"])
tensors = {k: v.to(device) if torch.is_tensor(v) else v for k, v in tensors.items()}
loss, parts, _ = batch_loss(model, tensors)
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
if verbose and (step % max(1, config["optim"]["log_every"]) == 0):
print(f"step {step:4d} loss {float(loss.detach()):.4f} "
f"(ans {parts['answer']:.3f} chg {parts['change']:.3f} ev {parts['evidence']:.3f})")
save(ckpt, model, opt, total_steps, config)
metrics = evaluate(model, config["data"]["val_families"], config["seed"], config["eval"]["n"])
if verbose:
print(f"val {json.dumps({k: (round(v, 3) if isinstance(v, float) else v) for k, v in metrics.items() if k != 'loss'})}")
print(f"done in {time.time() - t0:.1f}s device={device}")
metrics["secs"] = round(time.time() - t0, 2)
return metrics