diff --git a/spatial/cli.py b/spatial/cli.py index ad6282a..5934f00 100644 --- a/spatial/cli.py +++ b/spatial/cli.py @@ -309,7 +309,9 @@ def main(argv=None) -> int: 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"]) + help="comma list of dangling | scene | hidden | edge_feat; " + "hidden zeroes only the full-state-derived slice of " + "the scene features, leaving the scope block intact") sp.set_defaults(fn=fn) args = p.parse_args(argv) return args.fn(args) diff --git a/spatial/data.py b/spatial/data.py index 2488066..dda8334 100644 --- a/spatial/data.py +++ b/spatial/data.py @@ -1,245 +1,265 @@ -"""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, DOF_AXES, EDGE_KINDS, ENTITY_KINDS, Scenario -from .model import EDGE_FEAT_DIM, FEAT_DIM, N_AXIS, N_EDGE, QUERY_KINDS, SCENE_DIM - - -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 _contact_geom(by_id: dict, ed, per_unit: int = 1): - """(area, faces_meet, centroid_inside, area_ratio) for a contact edge. - - The checker's stability rule is local: two boxes support each other when - their faces actually meet and the upper centroid falls inside the overlap - rectangle. Leaving that predicate to be recomputed from two coordinate - vectors is leaving arithmetic to a classifier; measuring it per edge is what - a caliper would do and it says nothing about the answer. - """ - a, b = by_id.get(ed.a), by_id.get(ed.b) - if a is None or b is None: - return 0.0, 0.0, 0.0, 0.0 - ba, bb = a.attrs.get("box"), b.attrs.get("box") - if not ba or not bb: - return 0.0, 0.0, 0.0, 0.0 - scale = 400.0 * max(1, per_unit) ** 2 - ox0, oy0 = max(ba[0], bb[0]), max(ba[1], bb[1]) - ox1, oy1 = min(ba[3], bb[3]), min(ba[4], bb[4]) - if ox0 >= ox1 or oy0 >= oy1: - return 0.0, 0.0, 0.0, 0.0 - area = min(1.0, (ox1 - ox0) * (oy1 - oy0) / scale) - meet = 1.0 if (ba[5] == bb[2] or bb[5] == ba[2]) else 0.0 - # the support is the lower one; its centroid has to sit on the overlap - up = ba if ba[2] >= bb[2] else bb - cx2, cy2 = up[0] + up[3], up[1] + up[4] # twice the centroid, stays integer - inside = 1.0 if (2 * ox0 <= cx2 <= 2 * ox1 and 2 * oy0 <= cy2 <= 2 * oy1) else 0.0 - foot = max(1, (up[3] - up[0]) * (up[4] - up[1])) - return area, meet, inside, min(1.0, (ox1 - ox0) * (oy1 - oy0) / foot) - - -def _contact_area(by_id: dict, ed, per_unit: int = 1) -> float: - return _contact_geom(by_id, ed, per_unit)[0] - - -def edge_features(sc: Scenario, ed, removed: bool, dangling: bool = False) -> list: - f = [0.0] * EDGE_FEAT_DIM - f[EDGE_KINDS.index(ed.kind)] = 1.0 - ax = ed.attrs.get("axis") - if ax in DOF_AXES: - f[N_EDGE + DOF_AXES.index(ax)] = 1.0 - f[N_EDGE + N_AXIS] = 1.0 if removed else 0.0 - f[N_EDGE + N_AXIS + 1] = ed.layer / 6.0 - by_id = {e.eid: e for e in sc.obs.entities} - geom = _contact_geom(by_id, ed, sc.obs.units.get("per_unit", 1)) - f[N_EDGE + N_AXIS + 2] = geom[0] - f[N_EDGE + N_AXIS + 3] = 1.0 if dangling else 0.0 - f[N_EDGE + N_AXIS + 4:N_EDGE + N_AXIS + 7] = list(geom[1:]) - return f - - -def scene_features(sc: Scenario) -> list: - """The observation's own admission of what it is missing. - - ``hidden_layers`` and ``hidden_faces`` are in the digest but were never in - the tensor, so "no hidden branch" and "a hidden branch off-view" arrived at - the model as the same input with opposite labels. That is not an - under-fitting problem; it is information the contract promised and the - tensorisation dropped. - - Counts by kind, not identities: "one contact is missing" is a fact the - agent can act on, "kPT is missing" would be a leak of the answer. - """ - f = [0.0] * SCENE_DIM - for layer in sc.obs.hidden_layers: - if 1 <= layer <= 3: - f[layer - 1] = 1.0 - f[3] = min(1.0, len(sc.obs.hidden_faces) / 6.0) - hidden = sc.obs.hidden or {} - for kind, cnt in (hidden.get("entity") or {}).items(): - if kind in ENTITY_KINDS: - f[4 + ENTITY_KINDS.index(kind)] = min(1.0, cnt / 2.0) - for kind, cnt in (hidden.get("edge") or {}).items(): - if kind in EDGE_KINDS: - f[4 + len(ENTITY_KINDS) + EDGE_KINDS.index(kind)] = min(1.0, cnt / 3.0) - f[-2] = 1.0 if (hidden.get("entity") or hidden.get("edge")) else 0.0 - f[-1] = len(sc.obs.entities) / 32.0 - 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) + len(sc.obs.dangling) 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) - scene = torch.zeros(B, SCENE_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_feat = torch.zeros(B, E, EDGE_FEAT_DIM) - edge_mask = torch.zeros(B, E, dtype=torch.bool) - evidence = torch.zeros(B, E) - edge_removed = torch.zeros(B, E) - dangling = 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)} - scene[i] = torch.tensor(scene_features(sc)) - 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) - removed_eid = (sc.query.edit or {}).get("edge") - 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 - rm = ed.eid == removed_eid - edge_removed[i, k] = 1.0 if rm else 0.0 - edge_feat[i, k] = torch.tensor(edge_features(sc, ed, rm)) - # dangling relations go after the real ones and point at the unknown - # slot via the sentinel endpoint ``N``; their far end is never an entity, - # so they can never be mistaken for a traversable edge - for j, dl in enumerate(sc.obs.dangling): - k = len(sc.obs.edges) + j - edge_index[i, k, 0] = ids.get(dl.a, 0) - edge_index[i, k, 1] = N - edge_type[i, k] = EDGE_KINDS.index(dl.kind) - edge_mask[i, k] = True - dangling[i, k] = 1.0 - edge_feat[i, k] = torch.tensor(edge_features(sc, dl, False, dangling=True)) - 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) - # an entity that is gone takes its relations with it. Without this - # the post-intervention graph still has T resting on the pedestal it - # just lost, the hop distance still reports support, and the only - # evidence against support is the edit token itself -- which makes - # "an edit happened, answer false" the cheapest consistent rule. - gone = edit.get("entity") - for k, ed in enumerate(sc.obs.edges): - if gone in (ed.a, ed.b): - edge_removed[i, k] = 1.0 - 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, - "edge_feat": edge_feat, - "scene": scene, - "q_ents": q_ents, "q_kind": q_kind, - "edit_op": edit_op, "edit_idx": edit_idx, - "edge_removed": edge_removed, - "dangling": dangling, - "answer": answer, "change": change, "evidence": evidence, - } +"""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, DOF_AXES, EDGE_KINDS, ENTITY_KINDS, Scenario +from .model import EDGE_FEAT_DIM, FEAT_DIM, N_AXIS, N_EDGE, QUERY_KINDS, SCENE_DIM + + +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 _contact_geom(by_id: dict, ed, per_unit: int = 1): + """(area, faces_meet, centroid_inside, area_ratio) for a contact edge. + + The checker's stability rule is local: two boxes support each other when + their faces actually meet and the upper centroid falls inside the overlap + rectangle. Leaving that predicate to be recomputed from two coordinate + vectors is leaving arithmetic to a classifier; measuring it per edge is what + a caliper would do and it says nothing about the answer. + """ + a, b = by_id.get(ed.a), by_id.get(ed.b) + if a is None or b is None: + return 0.0, 0.0, 0.0, 0.0 + ba, bb = a.attrs.get("box"), b.attrs.get("box") + if not ba or not bb: + return 0.0, 0.0, 0.0, 0.0 + scale = 400.0 * max(1, per_unit) ** 2 + ox0, oy0 = max(ba[0], bb[0]), max(ba[1], bb[1]) + ox1, oy1 = min(ba[3], bb[3]), min(ba[4], bb[4]) + if ox0 >= ox1 or oy0 >= oy1: + return 0.0, 0.0, 0.0, 0.0 + area = min(1.0, (ox1 - ox0) * (oy1 - oy0) / scale) + meet = 1.0 if (ba[5] == bb[2] or bb[5] == ba[2]) else 0.0 + # the support is the lower one; its centroid has to sit on the overlap + up = ba if ba[2] >= bb[2] else bb + cx2, cy2 = up[0] + up[3], up[1] + up[4] # twice the centroid, stays integer + inside = 1.0 if (2 * ox0 <= cx2 <= 2 * ox1 and 2 * oy0 <= cy2 <= 2 * oy1) else 0.0 + foot = max(1, (up[3] - up[0]) * (up[4] - up[1])) + return area, meet, inside, min(1.0, (ox1 - ox0) * (oy1 - oy0) / foot) + + +def _contact_area(by_id: dict, ed, per_unit: int = 1) -> float: + return _contact_geom(by_id, ed, per_unit)[0] + + +def edge_features(sc: Scenario, ed, removed: bool, dangling: bool = False) -> list: + f = [0.0] * EDGE_FEAT_DIM + f[EDGE_KINDS.index(ed.kind)] = 1.0 + ax = ed.attrs.get("axis") + if ax in DOF_AXES: + f[N_EDGE + DOF_AXES.index(ax)] = 1.0 + f[N_EDGE + N_AXIS] = 1.0 if removed else 0.0 + f[N_EDGE + N_AXIS + 1] = ed.layer / 6.0 + by_id = {e.eid: e for e in sc.obs.entities} + geom = _contact_geom(by_id, ed, sc.obs.units.get("per_unit", 1)) + f[N_EDGE + N_AXIS + 2] = geom[0] + f[N_EDGE + N_AXIS + 3] = 1.0 if dangling else 0.0 + f[N_EDGE + N_AXIS + 4:N_EDGE + N_AXIS + 7] = list(geom[1:]) + return f + + +def scene_features(sc: Scenario) -> list: + """The observation's own admission of what it is missing. + + ``hidden_layers`` and ``hidden_faces`` are in the digest but were never in + the tensor, so "no hidden branch" and "a hidden branch off-view" arrived at + the model as the same input with opposite labels. That is not an + under-fitting problem; it is information the contract promised and the + tensorisation dropped. + + Counts by kind, not identities: "one contact is missing" is a fact the + agent can act on, "kPT is missing" would be a leak of the answer. + """ + f = [0.0] * SCENE_DIM + for layer in sc.obs.hidden_layers: + if 1 <= layer <= 3: + f[layer - 1] = 1.0 + f[3] = min(1.0, len(sc.obs.hidden_faces) / 6.0) + hidden = sc.obs.hidden or {} + for kind, cnt in (hidden.get("entity") or {}).items(): + if kind in ENTITY_KINDS: + f[4 + ENTITY_KINDS.index(kind)] = min(1.0, cnt / 2.0) + for kind, cnt in (hidden.get("edge") or {}).items(): + if kind in EDGE_KINDS: + f[4 + len(ENTITY_KINDS) + EDGE_KINDS.index(kind)] = min(1.0, cnt / 3.0) + base = 4 + len(ENTITY_KINDS) + len(EDGE_KINDS) + f[base] = 1.0 if (hidden.get("entity") or hidden.get("edge")) else 0.0 + f[base + 1] = len(sc.obs.entities) / 32.0 + # the declared inventory: what the source says it has versus what it handed + # over. No endpoints, so it can suspend an answer but never decide one. This + # is the only availability channel the contract allows; the block above is + # computed as "full minus visible" and therefore is not something a provider + # can produce. + scope = sc.obs.scope or {} + parts = scope.get("parts") or {} + rendered = scope.get("rendered") or {} + rel = scope.get("relations") or {} + rel_r = scope.get("rendered_relations") or {} + tot_parts = sum(parts.values()) or 0 + tot_rel = sum(rel.values()) or 0 + f[base + 2] = (tot_parts - sum(rendered.values())) / tot_parts if tot_parts else 0.0 + f[base + 3] = (tot_rel - sum(rel_r.values())) / tot_rel if tot_rel else 0.0 + missing_layers = set(scope.get("layers") or []) - set(scope.get("rendered_layers") or []) + f[base + 4] = min(1.0, len(missing_layers) / 4.0) + f[base + 5] = 1.0 if (scope.get("layers") or []) and ( + tot_parts > sum(rendered.values()) or tot_rel > sum(rel_r.values()) + or missing_layers) else 0.0 + 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) + len(sc.obs.dangling) 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) + scene = torch.zeros(B, SCENE_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_feat = torch.zeros(B, E, EDGE_FEAT_DIM) + edge_mask = torch.zeros(B, E, dtype=torch.bool) + evidence = torch.zeros(B, E) + edge_removed = torch.zeros(B, E) + dangling = 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)} + scene[i] = torch.tensor(scene_features(sc)) + 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) + removed_eid = (sc.query.edit or {}).get("edge") + 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 + rm = ed.eid == removed_eid + edge_removed[i, k] = 1.0 if rm else 0.0 + edge_feat[i, k] = torch.tensor(edge_features(sc, ed, rm)) + # dangling relations go after the real ones and point at the unknown + # slot via the sentinel endpoint ``N``; their far end is never an entity, + # so they can never be mistaken for a traversable edge + for j, dl in enumerate(sc.obs.dangling): + k = len(sc.obs.edges) + j + edge_index[i, k, 0] = ids.get(dl.a, 0) + edge_index[i, k, 1] = N + edge_type[i, k] = EDGE_KINDS.index(dl.kind) + edge_mask[i, k] = True + dangling[i, k] = 1.0 + edge_feat[i, k] = torch.tensor(edge_features(sc, dl, False, dangling=True)) + 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) + # an entity that is gone takes its relations with it. Without this + # the post-intervention graph still has T resting on the pedestal it + # just lost, the hop distance still reports support, and the only + # evidence against support is the edit token itself -- which makes + # "an edit happened, answer false" the cheapest consistent rule. + gone = edit.get("entity") + for k, ed in enumerate(sc.obs.edges): + if gone in (ed.a, ed.b): + edge_removed[i, k] = 1.0 + 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, + "edge_feat": edge_feat, + "scene": scene, + "q_ents": q_ents, "q_kind": q_kind, + "edit_op": edit_op, "edit_idx": edit_idx, + "edge_removed": edge_removed, + "dangling": dangling, + "answer": answer, "change": change, "evidence": evidence, + } diff --git a/spatial/model.py b/spatial/model.py index a7e4091..ee8604b 100644 --- a/spatial/model.py +++ b/spatial/model.py @@ -1,406 +1,411 @@ -"""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. -* **no positional encoding** -- entity order in a scene carries no meaning, so - the only ordering signal is structural: a learned bias indexed by graph - hop distance. Renumbering the scene must not move the output. -* **edge types are attention biases *and* values** -- a bias alone says "look - this way" but never tells the token *what* the relation is (layer, contact - area, which axis a mate locks). Edge content is folded into the value stream - so an entity actually receives its incident relations. -* **one query token, not a token per entity** -- the output is about a query, - not about the next token. -* **one unknown slot** -- a dangling relation (one end visible, one end not) - points at a single dedicated token instead of at an entity. A chain that ends - there is a chain that ends in a question, which is what "I cannot decide this" - has to look like in the input. -* **two rounds of read-out** -- round 1 selects a few edges as a candidate - certificate, round 2 lets every entity attend to those edges. This is the - cheap version of "grab evidence, then decide"; without it the evidence head - and the answer head never see the same object. -* **a learned temperature** -- the answer/change/evidence logits are divided by - ``exp(log_temp)``, so "unknown" is a decision made on a calibrated scale - rather than the argmax of an over-confident 3-way classifier. - -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 DOF_AXES, EDGE_KINDS, ENTITY_KINDS - -N_KIND = len(ENTITY_KINDS) -N_EDGE = len(EDGE_KINDS) -N_AXIS = len(DOF_AXES) -FEAT_DIM = N_KIND + 2 + 3 + 7 # kind, source, unit, (x,y,z,layer,w,h,d) -# type one-hot, axis one-hot, removed flag, layer, contact area, dangling flag, -# then the three local predicates a contact needs before it can carry load: -# do the faces meet in z, is the upper block's centroid inside the overlap, and -# how much of the upper footprint is covered. They are measurements, not -# answers -- the same numbers a caliper and a straight edge would give. -EDGE_FEAT_DIM = N_EDGE + N_AXIS + 4 + 3 -QUERY_KINDS = ("connection", "stability", "freedom") - -HOP_MAX = 4 # longer paths collapse into one bucket -FAR = HOP_MAX + 1 # unreachable, or "involves the query token" -# what the observation admits it is missing: hidden layer markers, unseen faces, -# one count per entity kind and per edge kind, an "anything withheld" bit, and -# the scene size. Without this the two worlds "no hidden branch exists" and "a -# hidden branch exists off-view" are literally the same tensor, and no amount of -# reasoning can separate them. -SCENE_DIM = 4 + N_KIND + N_EDGE + 2 - -UNK = 1 # position of the unknown slot -ENT0 = 2 # first entity position - - -def hop_distance(edge_index, edge_mask, edge_removed, n_ent: int) -> torch.Tensor: - """Truncated all-pairs shortest path over the *post-intervention* graph. - - A removed edge is not traversed: the question "still connected after cutting - the trunk" is about the graph after the cut, and a hop count that still - walks through the cut edge is a lie the model would have to unlearn. - """ - device = edge_index.device - B = edge_index.size(0) - ar = torch.arange(B, device=device) - adj = torch.zeros(B, n_ent, n_ent, dtype=torch.bool, device=device) - live = edge_mask if edge_removed is None else (edge_mask & (edge_removed < 0.5)) - for k in range(edge_index.size(1)): - m = live[:, k] - if not m.any(): - continue - b = ar[m] - s = edge_index[m, k, 0].clamp(min=0, max=n_ent - 1) - t = edge_index[m, k, 1].clamp(min=0, max=n_ent - 1) - adj[b, s, t] = True - adj[b, t, s] = True - - dist = torch.full((B, n_ent, n_ent), FAR, dtype=torch.long, device=device) - idx = torch.arange(n_ent, device=device) - dist[:, idx, idx] = 0 - dist = torch.where(adj, torch.ones_like(dist), dist) - reach = adj.clone() - front = adj.clone() - for d in range(2, HOP_MAX + 1): - front = (torch.bmm(front.float(), adj.float()) > 0) & ~reach - reach = reach | front - dist = torch.where(front, torch.full_like(dist, d), dist) - return dist - - -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, v_extra=None): - B, T, d = x.shape - h = self.ln1(x) - q, k, v = self.qkv(h).view(B, T, 3, self.n_head, d // self.n_head).permute(2, 0, 3, 1, 4) - if v_extra is not None: - # the relations an entity touches, injected straight into its value: - # edge type as attention bias only says "look there", not "it is a - # 0.8 mm2 contact on layer 2" - v = v + v_extra.view(B, T, self.n_head, d // self.n_head).permute(0, 2, 1, 3) - 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, T, 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, - rounds: int = 2, n_evidence: int = 4): - super().__init__() - self.d = d - self.n_head = n_head - self.max_entities = max_entities - self.rounds = max(1, rounds) - self.n_evidence = max(0, n_evidence) - - self.ent_proj = nn.Sequential(nn.Linear(FEAT_DIM, d), nn.GELU(), nn.Linear(d, d)) - self.edge_proj = nn.Sequential(nn.Linear(EDGE_FEAT_DIM, d), nn.GELU(), nn.Linear(d, d)) - # a linear path for edge content, alongside the nonlinear one. "Are all - # six axes locked" is a statement about the cardinality of a set, and the - # sum of a *nonlinear* projection of one-hots is no longer a count -- - # GELU mixes the axes and the bag loses which of them it saw. The linear - # skip keeps the sum an exact count vector, so a threshold can read it. - self.edge_lin = nn.Linear(EDGE_FEAT_DIM, d, bias=False) - self.scene_proj = nn.Sequential(nn.Linear(SCENE_DIM, d), nn.GELU(), nn.Linear(d, d)) - self.unk_tok = nn.Parameter(torch.zeros(d)) - self.query_emb = nn.Embedding(len(QUERY_KINDS), d) - # the relations attached to the entity the question names, delivered to - # the question directly. Letting the query pick them up through attention - # means averaging them with a dozen unrelated positions, and "are all six - # axes locked" is a conjunction of six per-axis thresholds -- measured: at - # chance (0.49) even on a single family, with the training loss stuck at - # ln 2. The bag of incident relations is the evidence the question asks - # for; it should not have to survive a softmax to arrive. - self.q_inc = nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Linear(d, 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.dangling_bias = nn.Parameter(torch.zeros(n_head)) - # structural order, not positional order: one bias per hop bucket - self.hop_bias = nn.Parameter(torch.zeros(HOP_MAX + 2, 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.answer_round = nn.Embedding(self.rounds, d) - 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) - self.ev_proj = nn.Linear(EDGE_FEAT_DIM, d) - self.round_emb = nn.Embedding(max(1, self.rounds - 1), d) - - # calibration: logits / exp(log_temp). Learned, not tuned on a split, so - # the temperature is supervised by the same labels as the heads. - self.log_temp = nn.Parameter(torch.zeros(1)) - - # ------------------------------------------------------------------ - def _hop_matrix(self, dist_ent, anchor, top, edge_index, n_ent: int, K: int) -> torch.Tensor: - """(B, T, T) hop buckets over *positions*, not entity indices. - - The unknown slot sits one hop from every entity that has a dangling - relation anchored on it, and is far from everything else. That is the - whole point of the slot: "the chain continues, but not visibly". - """ - B = dist_ent.size(0) - device = dist_ent.device - T = ENT0 + n_ent + K - hop = torch.full((B, T, T), FAR, dtype=torch.long, device=device) - hop[:, ENT0:ENT0 + n_ent, ENT0:ENT0 + n_ent] = dist_ent - hop[:, 0, 0] = 0 - hop[:, UNK, UNK] = 0 - one = torch.ones(B, n_ent, dtype=torch.long, device=device) - d_unk = torch.where(anchor, one, torch.full_like(one, FAR)) - hop[:, UNK, ENT0:ENT0 + n_ent] = d_unk - hop[:, ENT0:ENT0 + n_ent, UNK] = d_unk - if K == 0: - return hop - slots = torch.arange(ENT0 + n_ent, T, device=device) - hop[:, slots, slots] = 0 - if top is not None: - ar = torch.arange(B, device=device) - sel = edge_index[ar.unsqueeze(1), top.clamp(min=0)] # (B, K, 2), entity space - ok = sel < n_ent # false for the unknown end - safe = sel.clamp(min=0, max=n_ent - 1) - far = torch.full((B, K, n_ent), FAR, dtype=torch.long, device=device) - da = dist_ent.gather(2, safe[..., 0].unsqueeze(-1).expand(B, K, n_ent)) - db = dist_ent.gather(2, safe[..., 1].unsqueeze(-1).expand(B, K, n_ent)) - d = torch.minimum(torch.where(ok[..., 0:1], da, far), torch.where(ok[..., 1:2], db, far)) - d = torch.where(d >= FAR, far, d + 1).clamp(max=FAR) - hop[:, slots, ENT0:ENT0 + n_ent] = d - hop[:, ENT0:ENT0 + n_ent, slots] = d.transpose(1, 2) - return hop - - def _bias(self, pos, edge_type, edge_mask, edge_removed, dangling, hop): - """(B, n_head, T, T) additive attention bias, built in (B,T,T,H) so the - advanced indexing below is unambiguous.""" - B, T, _ = hop.shape - H = self.n_head - bias = self.none_bias.view(1, 1, 1, H).expand(B, T, T, H).clone() - bias = bias + self.hop_bias[hop] - - src, dst = pos[..., 0], pos[..., 1] - bidx = torch.arange(B, device=pos.device).unsqueeze(1).expand_as(src) - - # accumulate through a flat linear index: parallel edges between the same - # pair of nodes hit the same cell, and fancy-index assignment would keep - # only the last of them - flat = bias.view(-1, H) - - def add(mask, vec, flip=False): - if not mask.any(): - return - b_, s_, d_ = bidx[mask], src[mask], dst[mask] - if flip: - s_, d_ = d_, s_ - lin = b_ * (T * T) + s_ * T + d_ - flat.index_put_((lin,), vec.expand(lin.size(0), H), accumulate=True) - - for t in range(N_EDGE): - m = (edge_type == t) & edge_mask - add(m, self.edge_bias[t]) - add(m, self.edge_bias_inv[t], flip=True) - if edge_removed is not None: - rm = (edge_removed > 0) & edge_mask - add(rm, self.removed_bias) - add(rm, self.removed_bias, flip=True) - if dangling is not None: - add((dangling > 0) & edge_mask, self.dangling_bias) - return bias.permute(0, 3, 1, 2) - - def _evidence(self, x, pos, edge_type, edge_removed, edge_feat_emb, q_out): - B, T, _ = x.shape - ar = torch.arange(B, device=x.device).unsqueeze(1) - ea = x[ar, pos[..., 0].clamp(min=0, max=T - 1)] - eb = x[ar, pos[..., 1].clamp(min=0, max=T - 1)] - e_feat = self.edge_emb(edge_type) - if edge_removed is not None: - e_feat = e_feat + self.removed_emb((edge_removed > 0).long()) - # endpoints + query + the edge's own content: without the last term the - # head cannot exclude a removed edge from its own certificate, and - # without the dangling flag it cannot tell a support from a question - pair = torch.cat([ea + eb + e_feat + edge_feat_emb, - q_out.unsqueeze(1).expand(-1, ea.size(1), -1)], dim=-1) - return self.evidence_head(pair).squeeze(-1) - - # ------------------------------------------------------------------ - 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, edge_feat=None, scene=None, - dangling=None): - B, n_ent, _ = feat.shape - E = edge_index.size(1) - device = feat.device - K = min(self.n_evidence, E) if self.rounds > 1 else 0 - ar = torch.arange(B, device=device) - - if edge_feat is None: - edge_feat = torch.zeros(B, E, EDGE_FEAT_DIM, device=device) - if dangling is None: - dangling = torch.zeros(B, E, device=device) - - # an edge endpoint is either an entity (entity index < n_ent) or the - # unknown slot; mapping to positions once keeps every downstream use -- - # bias, hop, evidence -- reading the same coordinates - pos = torch.where(edge_index < n_ent, edge_index + ENT0, - torch.full_like(edge_index, UNK)) - has_unk = (dangling > 0) & edge_mask - anchor = torch.zeros(B, n_ent, dtype=torch.bool, device=device) - if has_unk.any(): - b_ = ar.unsqueeze(1).expand(B, E)[has_unk] - e_ = edge_index[..., 0][has_unk].clamp(min=0, max=n_ent - 1) - anchor.index_put_((b_, e_), torch.ones(b_.size(0), dtype=torch.bool, device=device)) - unk_absent = ~anchor.any(dim=1) # no mouth: the slot is not shown - - h = self.ent_proj(feat) - ef = self.edge_proj(edge_feat) # edge content, (B, E, d) - - # fold incident edge content into each entity's value. Incidence is built - # as a dense (B,N,E) matrix and applied as one matmul: it keeps the - # backward pass simple and it makes "an entity receiving three edges sums - # three vectors" obvious. Dangling edges are excluded: their far end is - # not an entity, and pretending otherwise would credit an arbitrary node - # with a relation it does not have. Removed edges are excluded too, for - # the same reason the hop distance excludes them: the question is about - # the graph after the cut, and an entity whose value still sums a cut - # constraint has to un-learn it before it can answer. - inc = torch.zeros(B, n_ent, E, device=device) - cols = torch.arange(E, device=device).view(1, E).expand(B, E) - ones = torch.ones_like(cols, dtype=inc.dtype) - inc.index_put_((ar.unsqueeze(1).expand(B, E), - edge_index[..., 0].clamp(min=0, max=n_ent - 1), cols), ones) - inc.index_put_((ar.unsqueeze(1).expand(B, E), - edge_index[..., 1].clamp(min=0, max=n_ent - 1), cols), ones) - live = edge_mask & ~has_unk - if edge_removed is not None: - live = live & ~(edge_removed > 0) - inc = inc * live.unsqueeze(1).to(inc.dtype) - msg = torch.bmm(inc, ef) + torch.bmm(inc, self.edge_lin(edge_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) - 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[ar, a_idx].unsqueeze(1), torch.zeros_like(q)) - q = q + torch.where(valid_b.unsqueeze(-1), h[ar, b_idx].unsqueeze(1), torch.zeros_like(q)) - # and the relations hanging off those entities, without the detour - q = q + torch.where(valid_a.unsqueeze(-1), - self.q_inc(msg[ar, a_idx]).unsqueeze(1), torch.zeros_like(q)) - q = q + torch.where(valid_b.unsqueeze(-1), - self.q_inc(msg[ar, 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: - # separate clamps: an entity index can exceed the padded edge count - tgt_ent = h[ar, edit_idx.clamp(min=0, max=n_ent - 1)] - pair = edge_index[ar, edit_idx.clamp(min=0, max=E - 1)] - tgt_edge = h[ar, pair[:, 0].clamp(min=0, max=n_ent - 1)] + \ - h[ar, pair[:, 1].clamp(min=0, max=n_ent - 1)] - 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) - - # what the observation says it cannot see is part of the question, not a - # property of any entity, so it rides on the query token where every - # entity can attend to it - if scene is not None: - q = q + self.scene_proj(scene).unsqueeze(1) - - unk = self.unk_tok.view(1, 1, self.d).expand(B, 1, self.d) - zeros_ev = torch.zeros(B, K, self.d, device=device) - x_tok = torch.cat([q, unk, h, zeros_ev], dim=1) # (B, 2+N+K, d) - v_extra = torch.cat([torch.zeros(B, 2, self.d, device=device), msg, zeros_ev], dim=1) - pad = torch.cat([torch.zeros(B, 2, dtype=torch.bool, device=device), - pad_mask, torch.ones(B, K, dtype=torch.bool, device=device)], dim=1) - pad[:, UNK] = unk_absent # no dangling relation: no unknown slot - - dist = hop_distance(edge_index, edge_mask & ~has_unk, edge_removed, n_ent) - top = None - ev_logits = None - q_out = None - temp = torch.exp(-self.log_temp) - - for r in range(self.rounds): - hop = self._hop_matrix(dist, anchor, top, edge_index, n_ent, K) - bias = self._bias(pos, edge_type, edge_mask, edge_removed, dangling, hop) - x = x_tok - for blk in self.blocks: - x = blk(x, bias, pad, v_extra) - x = self.ln_f(x) - q_out = x[:, 0] + self.answer_round.weight[r] - ev_logits = self._evidence(x, pos, edge_type, edge_removed, ef, q_out) - if r + 1 < self.rounds and K > 0: - # round 1 hands back the strongest candidate edges as tokens, so - # every entity can attend to the certificate it is part of - top = ev_logits.detach().masked_fill(~edge_mask, float("-inf")).topk(K, -1).indices - filled = torch.cat([edge_mask.gather(1, top[:, kk:kk + 1]) for kk in range(K)], 1) - x_tok = torch.cat([x_tok[:, :ENT0 + n_ent], - self.ev_proj(edge_feat[ar.unsqueeze(1), top.clamp(min=0)]) - + self.round_emb.weight[r]], dim=1) - pad = torch.cat([pad[:, :ENT0 + n_ent], ~filled], dim=1) - - return { - "answer": self.answer_head(q_out) * temp, - "change": self.change_head(q_out) * temp, - "evidence": ev_logits * temp, - "temp": temp.detach(), - } +"""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. +* **no positional encoding** -- entity order in a scene carries no meaning, so + the only ordering signal is structural: a learned bias indexed by graph + hop distance. Renumbering the scene must not move the output. +* **edge types are attention biases *and* values** -- a bias alone says "look + this way" but never tells the token *what* the relation is (layer, contact + area, which axis a mate locks). Edge content is folded into the value stream + so an entity actually receives its incident relations. +* **one query token, not a token per entity** -- the output is about a query, + not about the next token. +* **one unknown slot** -- a dangling relation (one end visible, one end not) + points at a single dedicated token instead of at an entity. A chain that ends + there is a chain that ends in a question, which is what "I cannot decide this" + has to look like in the input. +* **two rounds of read-out** -- round 1 selects a few edges as a candidate + certificate, round 2 lets every entity attend to those edges. This is the + cheap version of "grab evidence, then decide"; without it the evidence head + and the answer head never see the same object. +* **a learned temperature** -- the answer/change/evidence logits are divided by + ``exp(log_temp)``, so "unknown" is a decision made on a calibrated scale + rather than the argmax of an over-confident 3-way classifier. + +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 DOF_AXES, EDGE_KINDS, ENTITY_KINDS + +N_KIND = len(ENTITY_KINDS) +N_EDGE = len(EDGE_KINDS) +N_AXIS = len(DOF_AXES) +FEAT_DIM = N_KIND + 2 + 3 + 7 # kind, source, unit, (x,y,z,layer,w,h,d) +# type one-hot, axis one-hot, removed flag, layer, contact area, dangling flag, +# then the three local predicates a contact needs before it can carry load: +# do the faces meet in z, is the upper block's centroid inside the overlap, and +# how much of the upper footprint is covered. They are measurements, not +# answers -- the same numbers a caliper and a straight edge would give. +EDGE_FEAT_DIM = N_EDGE + N_AXIS + 4 + 3 +QUERY_KINDS = ("connection", "stability", "freedom") + +HOP_MAX = 4 # longer paths collapse into one bucket +FAR = HOP_MAX + 1 # unreachable, or "involves the query token" +# what the observation admits it is missing: hidden layer markers, unseen faces, +# one count per entity kind and per edge kind, an "anything withheld" bit, and +# the scene size. Without this the two worlds "no hidden branch exists" and "a +# hidden branch exists off-view" are literally the same tensor, and no amount of +# reasoning can separate them. +SCENE_DIM = 4 + N_KIND + N_EDGE + 2 + 4 +# the first block is derived from the full state (what is hidden by kind); +# the last four are derived from the declared inventory (scope), which a real +# provider can state without endpoints. They live in separate slices so an +# ablation can remove one without touching the other. +SCENE_HIDDEN = slice(0, 4 + N_KIND + N_EDGE + 2) + +UNK = 1 # position of the unknown slot +ENT0 = 2 # first entity position + + +def hop_distance(edge_index, edge_mask, edge_removed, n_ent: int) -> torch.Tensor: + """Truncated all-pairs shortest path over the *post-intervention* graph. + + A removed edge is not traversed: the question "still connected after cutting + the trunk" is about the graph after the cut, and a hop count that still + walks through the cut edge is a lie the model would have to unlearn. + """ + device = edge_index.device + B = edge_index.size(0) + ar = torch.arange(B, device=device) + adj = torch.zeros(B, n_ent, n_ent, dtype=torch.bool, device=device) + live = edge_mask if edge_removed is None else (edge_mask & (edge_removed < 0.5)) + for k in range(edge_index.size(1)): + m = live[:, k] + if not m.any(): + continue + b = ar[m] + s = edge_index[m, k, 0].clamp(min=0, max=n_ent - 1) + t = edge_index[m, k, 1].clamp(min=0, max=n_ent - 1) + adj[b, s, t] = True + adj[b, t, s] = True + + dist = torch.full((B, n_ent, n_ent), FAR, dtype=torch.long, device=device) + idx = torch.arange(n_ent, device=device) + dist[:, idx, idx] = 0 + dist = torch.where(adj, torch.ones_like(dist), dist) + reach = adj.clone() + front = adj.clone() + for d in range(2, HOP_MAX + 1): + front = (torch.bmm(front.float(), adj.float()) > 0) & ~reach + reach = reach | front + dist = torch.where(front, torch.full_like(dist, d), dist) + return dist + + +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, v_extra=None): + B, T, d = x.shape + h = self.ln1(x) + q, k, v = self.qkv(h).view(B, T, 3, self.n_head, d // self.n_head).permute(2, 0, 3, 1, 4) + if v_extra is not None: + # the relations an entity touches, injected straight into its value: + # edge type as attention bias only says "look there", not "it is a + # 0.8 mm2 contact on layer 2" + v = v + v_extra.view(B, T, self.n_head, d // self.n_head).permute(0, 2, 1, 3) + 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, T, 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, + rounds: int = 2, n_evidence: int = 4): + super().__init__() + self.d = d + self.n_head = n_head + self.max_entities = max_entities + self.rounds = max(1, rounds) + self.n_evidence = max(0, n_evidence) + + self.ent_proj = nn.Sequential(nn.Linear(FEAT_DIM, d), nn.GELU(), nn.Linear(d, d)) + self.edge_proj = nn.Sequential(nn.Linear(EDGE_FEAT_DIM, d), nn.GELU(), nn.Linear(d, d)) + # a linear path for edge content, alongside the nonlinear one. "Are all + # six axes locked" is a statement about the cardinality of a set, and the + # sum of a *nonlinear* projection of one-hots is no longer a count -- + # GELU mixes the axes and the bag loses which of them it saw. The linear + # skip keeps the sum an exact count vector, so a threshold can read it. + self.edge_lin = nn.Linear(EDGE_FEAT_DIM, d, bias=False) + self.scene_proj = nn.Sequential(nn.Linear(SCENE_DIM, d), nn.GELU(), nn.Linear(d, d)) + self.unk_tok = nn.Parameter(torch.zeros(d)) + self.query_emb = nn.Embedding(len(QUERY_KINDS), d) + # the relations attached to the entity the question names, delivered to + # the question directly. Letting the query pick them up through attention + # means averaging them with a dozen unrelated positions, and "are all six + # axes locked" is a conjunction of six per-axis thresholds -- measured: at + # chance (0.49) even on a single family, with the training loss stuck at + # ln 2. The bag of incident relations is the evidence the question asks + # for; it should not have to survive a softmax to arrive. + self.q_inc = nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Linear(d, 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.dangling_bias = nn.Parameter(torch.zeros(n_head)) + # structural order, not positional order: one bias per hop bucket + self.hop_bias = nn.Parameter(torch.zeros(HOP_MAX + 2, 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.answer_round = nn.Embedding(self.rounds, d) + 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) + self.ev_proj = nn.Linear(EDGE_FEAT_DIM, d) + self.round_emb = nn.Embedding(max(1, self.rounds - 1), d) + + # calibration: logits / exp(log_temp). Learned, not tuned on a split, so + # the temperature is supervised by the same labels as the heads. + self.log_temp = nn.Parameter(torch.zeros(1)) + + # ------------------------------------------------------------------ + def _hop_matrix(self, dist_ent, anchor, top, edge_index, n_ent: int, K: int) -> torch.Tensor: + """(B, T, T) hop buckets over *positions*, not entity indices. + + The unknown slot sits one hop from every entity that has a dangling + relation anchored on it, and is far from everything else. That is the + whole point of the slot: "the chain continues, but not visibly". + """ + B = dist_ent.size(0) + device = dist_ent.device + T = ENT0 + n_ent + K + hop = torch.full((B, T, T), FAR, dtype=torch.long, device=device) + hop[:, ENT0:ENT0 + n_ent, ENT0:ENT0 + n_ent] = dist_ent + hop[:, 0, 0] = 0 + hop[:, UNK, UNK] = 0 + one = torch.ones(B, n_ent, dtype=torch.long, device=device) + d_unk = torch.where(anchor, one, torch.full_like(one, FAR)) + hop[:, UNK, ENT0:ENT0 + n_ent] = d_unk + hop[:, ENT0:ENT0 + n_ent, UNK] = d_unk + if K == 0: + return hop + slots = torch.arange(ENT0 + n_ent, T, device=device) + hop[:, slots, slots] = 0 + if top is not None: + ar = torch.arange(B, device=device) + sel = edge_index[ar.unsqueeze(1), top.clamp(min=0)] # (B, K, 2), entity space + ok = sel < n_ent # false for the unknown end + safe = sel.clamp(min=0, max=n_ent - 1) + far = torch.full((B, K, n_ent), FAR, dtype=torch.long, device=device) + da = dist_ent.gather(2, safe[..., 0].unsqueeze(-1).expand(B, K, n_ent)) + db = dist_ent.gather(2, safe[..., 1].unsqueeze(-1).expand(B, K, n_ent)) + d = torch.minimum(torch.where(ok[..., 0:1], da, far), torch.where(ok[..., 1:2], db, far)) + d = torch.where(d >= FAR, far, d + 1).clamp(max=FAR) + hop[:, slots, ENT0:ENT0 + n_ent] = d + hop[:, ENT0:ENT0 + n_ent, slots] = d.transpose(1, 2) + return hop + + def _bias(self, pos, edge_type, edge_mask, edge_removed, dangling, hop): + """(B, n_head, T, T) additive attention bias, built in (B,T,T,H) so the + advanced indexing below is unambiguous.""" + B, T, _ = hop.shape + H = self.n_head + bias = self.none_bias.view(1, 1, 1, H).expand(B, T, T, H).clone() + bias = bias + self.hop_bias[hop] + + src, dst = pos[..., 0], pos[..., 1] + bidx = torch.arange(B, device=pos.device).unsqueeze(1).expand_as(src) + + # accumulate through a flat linear index: parallel edges between the same + # pair of nodes hit the same cell, and fancy-index assignment would keep + # only the last of them + flat = bias.view(-1, H) + + def add(mask, vec, flip=False): + if not mask.any(): + return + b_, s_, d_ = bidx[mask], src[mask], dst[mask] + if flip: + s_, d_ = d_, s_ + lin = b_ * (T * T) + s_ * T + d_ + flat.index_put_((lin,), vec.expand(lin.size(0), H), accumulate=True) + + for t in range(N_EDGE): + m = (edge_type == t) & edge_mask + add(m, self.edge_bias[t]) + add(m, self.edge_bias_inv[t], flip=True) + if edge_removed is not None: + rm = (edge_removed > 0) & edge_mask + add(rm, self.removed_bias) + add(rm, self.removed_bias, flip=True) + if dangling is not None: + add((dangling > 0) & edge_mask, self.dangling_bias) + return bias.permute(0, 3, 1, 2) + + def _evidence(self, x, pos, edge_type, edge_removed, edge_feat_emb, q_out): + B, T, _ = x.shape + ar = torch.arange(B, device=x.device).unsqueeze(1) + ea = x[ar, pos[..., 0].clamp(min=0, max=T - 1)] + eb = x[ar, pos[..., 1].clamp(min=0, max=T - 1)] + e_feat = self.edge_emb(edge_type) + if edge_removed is not None: + e_feat = e_feat + self.removed_emb((edge_removed > 0).long()) + # endpoints + query + the edge's own content: without the last term the + # head cannot exclude a removed edge from its own certificate, and + # without the dangling flag it cannot tell a support from a question + pair = torch.cat([ea + eb + e_feat + edge_feat_emb, + q_out.unsqueeze(1).expand(-1, ea.size(1), -1)], dim=-1) + return self.evidence_head(pair).squeeze(-1) + + # ------------------------------------------------------------------ + 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, edge_feat=None, scene=None, + dangling=None): + B, n_ent, _ = feat.shape + E = edge_index.size(1) + device = feat.device + K = min(self.n_evidence, E) if self.rounds > 1 else 0 + ar = torch.arange(B, device=device) + + if edge_feat is None: + edge_feat = torch.zeros(B, E, EDGE_FEAT_DIM, device=device) + if dangling is None: + dangling = torch.zeros(B, E, device=device) + + # an edge endpoint is either an entity (entity index < n_ent) or the + # unknown slot; mapping to positions once keeps every downstream use -- + # bias, hop, evidence -- reading the same coordinates + pos = torch.where(edge_index < n_ent, edge_index + ENT0, + torch.full_like(edge_index, UNK)) + has_unk = (dangling > 0) & edge_mask + anchor = torch.zeros(B, n_ent, dtype=torch.bool, device=device) + if has_unk.any(): + b_ = ar.unsqueeze(1).expand(B, E)[has_unk] + e_ = edge_index[..., 0][has_unk].clamp(min=0, max=n_ent - 1) + anchor.index_put_((b_, e_), torch.ones(b_.size(0), dtype=torch.bool, device=device)) + unk_absent = ~anchor.any(dim=1) # no mouth: the slot is not shown + + h = self.ent_proj(feat) + ef = self.edge_proj(edge_feat) # edge content, (B, E, d) + + # fold incident edge content into each entity's value. Incidence is built + # as a dense (B,N,E) matrix and applied as one matmul: it keeps the + # backward pass simple and it makes "an entity receiving three edges sums + # three vectors" obvious. Dangling edges are excluded: their far end is + # not an entity, and pretending otherwise would credit an arbitrary node + # with a relation it does not have. Removed edges are excluded too, for + # the same reason the hop distance excludes them: the question is about + # the graph after the cut, and an entity whose value still sums a cut + # constraint has to un-learn it before it can answer. + inc = torch.zeros(B, n_ent, E, device=device) + cols = torch.arange(E, device=device).view(1, E).expand(B, E) + ones = torch.ones_like(cols, dtype=inc.dtype) + inc.index_put_((ar.unsqueeze(1).expand(B, E), + edge_index[..., 0].clamp(min=0, max=n_ent - 1), cols), ones) + inc.index_put_((ar.unsqueeze(1).expand(B, E), + edge_index[..., 1].clamp(min=0, max=n_ent - 1), cols), ones) + live = edge_mask & ~has_unk + if edge_removed is not None: + live = live & ~(edge_removed > 0) + inc = inc * live.unsqueeze(1).to(inc.dtype) + msg = torch.bmm(inc, ef) + torch.bmm(inc, self.edge_lin(edge_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) + 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[ar, a_idx].unsqueeze(1), torch.zeros_like(q)) + q = q + torch.where(valid_b.unsqueeze(-1), h[ar, b_idx].unsqueeze(1), torch.zeros_like(q)) + # and the relations hanging off those entities, without the detour + q = q + torch.where(valid_a.unsqueeze(-1), + self.q_inc(msg[ar, a_idx]).unsqueeze(1), torch.zeros_like(q)) + q = q + torch.where(valid_b.unsqueeze(-1), + self.q_inc(msg[ar, 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: + # separate clamps: an entity index can exceed the padded edge count + tgt_ent = h[ar, edit_idx.clamp(min=0, max=n_ent - 1)] + pair = edge_index[ar, edit_idx.clamp(min=0, max=E - 1)] + tgt_edge = h[ar, pair[:, 0].clamp(min=0, max=n_ent - 1)] + \ + h[ar, pair[:, 1].clamp(min=0, max=n_ent - 1)] + 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) + + # what the observation says it cannot see is part of the question, not a + # property of any entity, so it rides on the query token where every + # entity can attend to it + if scene is not None: + q = q + self.scene_proj(scene).unsqueeze(1) + + unk = self.unk_tok.view(1, 1, self.d).expand(B, 1, self.d) + zeros_ev = torch.zeros(B, K, self.d, device=device) + x_tok = torch.cat([q, unk, h, zeros_ev], dim=1) # (B, 2+N+K, d) + v_extra = torch.cat([torch.zeros(B, 2, self.d, device=device), msg, zeros_ev], dim=1) + pad = torch.cat([torch.zeros(B, 2, dtype=torch.bool, device=device), + pad_mask, torch.ones(B, K, dtype=torch.bool, device=device)], dim=1) + pad[:, UNK] = unk_absent # no dangling relation: no unknown slot + + dist = hop_distance(edge_index, edge_mask & ~has_unk, edge_removed, n_ent) + top = None + ev_logits = None + q_out = None + temp = torch.exp(-self.log_temp) + + for r in range(self.rounds): + hop = self._hop_matrix(dist, anchor, top, edge_index, n_ent, K) + bias = self._bias(pos, edge_type, edge_mask, edge_removed, dangling, hop) + x = x_tok + for blk in self.blocks: + x = blk(x, bias, pad, v_extra) + x = self.ln_f(x) + q_out = x[:, 0] + self.answer_round.weight[r] + ev_logits = self._evidence(x, pos, edge_type, edge_removed, ef, q_out) + if r + 1 < self.rounds and K > 0: + # round 1 hands back the strongest candidate edges as tokens, so + # every entity can attend to the certificate it is part of + top = ev_logits.detach().masked_fill(~edge_mask, float("-inf")).topk(K, -1).indices + filled = torch.cat([edge_mask.gather(1, top[:, kk:kk + 1]) for kk in range(K)], 1) + x_tok = torch.cat([x_tok[:, :ENT0 + n_ent], + self.ev_proj(edge_feat[ar.unsqueeze(1), top.clamp(min=0)]) + + self.round_emb.weight[r]], dim=1) + pad = torch.cat([pad[:, :ENT0 + n_ent], ~filled], dim=1) + + return { + "answer": self.answer_head(q_out) * temp, + "change": self.change_head(q_out) * temp, + "evidence": ev_logits * temp, + "temp": temp.detach(), + } diff --git a/spatial/report.py b/spatial/report.py index 93a99d6..eea549b 100644 --- a/spatial/report.py +++ b/spatial/report.py @@ -1,112 +1,117 @@ -"""Per-family report. - -The aggregate metrics in ``train.evaluate`` hide the only comparison that -matters: a model can score 1.000 answer accuracy on a held-out family while -never once abstaining and while its certificates are wrong four times out of -five. Answer accuracy alone cannot tell "learned the rule" from "learned the -label distribution of this family". - -So each row here reports the four things separately: - -* ``acc`` -- accuracy on rows the observation can decide -* ``abst`` -- fraction of undecidable rows the model actually refuses -* ``cert`` -- certificate validity among the rows it calls "true" -* ``conf`` -- mean top-1 confidence, which is what ``cert`` and ``abst`` are - fighting against -""" -from __future__ import annotations - -import json -import os - -import torch - -from . import checker, generator -from .data import collate -from .model import N_AXIS, N_EDGE -from .train import load - -DANGLING_BIT = N_EDGE + N_AXIS + 3 - -ANSWERS = ("true", "false", "unknown") - - -@torch.no_grad() -def family_row(model, family: str, seed: int, n: int, max_entities: int = 32, - ablate: str = None) -> dict: - batch = [generator.make(family, seed=seed, index=i) for i in range(n)] - device = next(model.parameters()).device - t = collate(batch, max_entities) - t = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in t.items()} - if ablate: - # a mechanism that survives its own removal was never used. The dangling - # signal lives in two places -- the structural unknown slot and a flag on - # the edge itself -- so zeroing only one of them tests the other, not the - # mechanism. - for key in ablate.split(","): - if key == "dangling": - t["dangling"] = torch.zeros_like(t["dangling"]) - t["edge_feat"][..., DANGLING_BIT] = 0.0 - else: - t[key] = torch.zeros_like(t[key]) - out = model(t["feat"], t["pad_mask"], t["edge_index"], t["edge_type"], t["edge_mask"], - t["q_ents"], t["q_kind"], t["edit_op"], t["edit_idx"], t["edge_removed"], - t["edge_feat"], t["scene"], t["dangling"]) - pred = out["answer"].argmax(-1).tolist() - conf = torch.softmax(out["answer"], -1).max(-1).values.tolist() - probs = torch.sigmoid(out["evidence"]) - - ans_rows = [i for i, sc in enumerate(batch) if sc.label.answer != "unknown"] - unk_rows = [i for i, sc in enumerate(batch) if sc.label.answer == "unknown"] - hit = sum(1 for i in ans_rows if pred[i] == ANSWERS.index(batch[i].label.answer)) - abst = sum(1 for i in unk_rows if pred[i] == 2) - - # a certificate is only asked of rows the model is willing to assert - - 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)) - - return { - "family": family, - "n": len(batch), - "decidable": len(ans_rows), - "unknown": len(unk_rows), - "acc": round(hit / max(1, len(ans_rows)), 3), - "abst": round(abst / max(1, len(unk_rows)), 3), - "cert": round(valid / max(1, total), 3), - "n_true": total, - "conf": round(sum(conf) / len(conf), 3), - } - - -def report(config_path: str, n: int = 128, ablate: str = None, seed: int = None) -> None: - root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - tag = os.path.basename(config_path).replace(".json", "") - if seed is not None: - tag = f"{tag}_s{seed}" - ckpt = os.path.join(root, "out_spatial", tag, "ckpt.pt") - model, _, step, cfg = load(ckpt, "cuda" if torch.cuda.is_available() else "cpu") - model.eval() - if seed is not None: - cfg["seed"] = seed - print(f"step {step} families: train={cfg['data']['train_families']} " - f"val={cfg['data']['val_families']}") - if ablate: - print(f"ABLATION: {ablate} zeroed at eval time") - head = f"{'family':11s} {'n':>3s} {'dec':>4s} {'unk':>4s} {'dang':>4s} {'acc':>5s} " \ - f"{'abst':>5s} {'cert':>5s} {'#true':>5s} {'conf':>5s}" - print(head) - print("-" * len(head)) - for fam in generator.FAMILIES: - ndang = sum(len(generator.make(fam, cfg["seed"], i).obs.dangling) for i in range(8)) / 8 - r = family_row(model, fam, cfg["seed"], n, cfg["model"]["max_entities"], ablate) - print(f"{r['family']:11s} {r['n']:3d} {r['decidable']:4d} {r['unknown']:4d} " - f"{ndang:4.1f} " - f"{r['acc']:5.3f} {r['abst']:5.3f} {r['cert']:5.3f} {r['n_true']:5d} " - f"{r['conf']:5.3f}") +"""Per-family report. + +The aggregate metrics in ``train.evaluate`` hide the only comparison that +matters: a model can score 1.000 answer accuracy on a held-out family while +never once abstaining and while its certificates are wrong four times out of +five. Answer accuracy alone cannot tell "learned the rule" from "learned the +label distribution of this family". + +So each row here reports the four things separately: + +* ``acc`` -- accuracy on rows the observation can decide +* ``abst`` -- fraction of undecidable rows the model actually refuses +* ``cert`` -- certificate validity among the rows it calls "true" +* ``conf`` -- mean top-1 confidence, which is what ``cert`` and ``abst`` are + fighting against +""" +from __future__ import annotations + +import json +import os + +import torch + +from . import checker, generator +from .data import collate +from .model import N_AXIS, N_EDGE, SCENE_HIDDEN +from .train import load + +DANGLING_BIT = N_EDGE + N_AXIS + 3 + +ANSWERS = ("true", "false", "unknown") + + +@torch.no_grad() +def family_row(model, family: str, seed: int, n: int, max_entities: int = 32, + ablate: str = None) -> dict: + batch = [generator.make(family, seed=seed, index=i) for i in range(n)] + device = next(model.parameters()).device + t = collate(batch, max_entities) + t = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in t.items()} + if ablate: + # a mechanism that survives its own removal was never used. The dangling + # signal lives in two places -- the structural unknown slot and a flag on + # the edge itself -- so zeroing only one of them tests the other, not the + # mechanism. + for key in ablate.split(","): + if key == "dangling": + t["dangling"] = torch.zeros_like(t["dangling"]) + t["edge_feat"][..., DANGLING_BIT] = 0.0 + elif key == "hidden": + # the full-state-derived block only: what is withheld *by kind*. + # The scope block at the end stays, so this measures exactly the + # leak's contribution rather than "any availability signal". + t["scene"][:, SCENE_HIDDEN] = 0.0 + else: + t[key] = torch.zeros_like(t[key]) + out = model(t["feat"], t["pad_mask"], t["edge_index"], t["edge_type"], t["edge_mask"], + t["q_ents"], t["q_kind"], t["edit_op"], t["edit_idx"], t["edge_removed"], + t["edge_feat"], t["scene"], t["dangling"]) + pred = out["answer"].argmax(-1).tolist() + conf = torch.softmax(out["answer"], -1).max(-1).values.tolist() + probs = torch.sigmoid(out["evidence"]) + + ans_rows = [i for i, sc in enumerate(batch) if sc.label.answer != "unknown"] + unk_rows = [i for i, sc in enumerate(batch) if sc.label.answer == "unknown"] + hit = sum(1 for i in ans_rows if pred[i] == ANSWERS.index(batch[i].label.answer)) + abst = sum(1 for i in unk_rows if pred[i] == 2) + + # a certificate is only asked of rows the model is willing to assert + + 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)) + + return { + "family": family, + "n": len(batch), + "decidable": len(ans_rows), + "unknown": len(unk_rows), + "acc": round(hit / max(1, len(ans_rows)), 3), + "abst": round(abst / max(1, len(unk_rows)), 3), + "cert": round(valid / max(1, total), 3), + "n_true": total, + "conf": round(sum(conf) / len(conf), 3), + } + + +def report(config_path: str, n: int = 128, ablate: str = None, seed: int = None) -> None: + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + tag = os.path.basename(config_path).replace(".json", "") + if seed is not None: + tag = f"{tag}_s{seed}" + ckpt = os.path.join(root, "out_spatial", tag, "ckpt.pt") + model, _, step, cfg = load(ckpt, "cuda" if torch.cuda.is_available() else "cpu") + model.eval() + if seed is not None: + cfg["seed"] = seed + print(f"step {step} families: train={cfg['data']['train_families']} " + f"val={cfg['data']['val_families']}") + if ablate: + print(f"ABLATION: {ablate} zeroed at eval time") + head = f"{'family':11s} {'n':>3s} {'dec':>4s} {'unk':>4s} {'dang':>4s} {'acc':>5s} " \ + f"{'abst':>5s} {'cert':>5s} {'#true':>5s} {'conf':>5s}" + print(head) + print("-" * len(head)) + for fam in generator.FAMILIES: + ndang = sum(len(generator.make(fam, cfg["seed"], i).obs.dangling) for i in range(8)) / 8 + r = family_row(model, fam, cfg["seed"], n, cfg["model"]["max_entities"], ablate) + print(f"{r['family']:11s} {r['n']:3d} {r['decidable']:4d} {r['unknown']:4d} " + f"{ndang:4.1f} " + f"{r['acc']:5.3f} {r['abst']:5.3f} {r['cert']:5.3f} {r['n_true']:5d} " + f"{r['conf']:5.3f}")