此前"少了一条接触"只是全局计数,模型只能说"我在猜";它无法区分"目标根本没支撑" 和"目标的那条支撑被挡住了"。现在: - Observation.dangling:一端可见、另一端不可见的关系,锚在可见那一端,不带身份。 它说的是无知挂在哪儿,不是答案是什么。 - 模型多一个未知槽位(位置 1),悬空边的远端指向它;有悬空关系的锚定实体与它 相距一跳。一条链走到它上面,就是一条链走进了问题。 - 悬空边不参与连通计算、不进入实体的入射边求和、边特征里带 dangling 标志。 - 新增 area.free 家族:T 的唯一接触连到一个自身悬空的块,什么也没藏、什么也不悬空, 所以"没有支撑"是事实而非缺口,正确答案是 false,弃权才是错的。 它与 area.sup2h 构成最小对:同样是一条接触,一个通到未知、一个通到死路。
221 lines
9.2 KiB
Python
221 lines
9.2 KiB
Python
"""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_area(by_id: dict, ed, per_unit: int = 1) -> float:
|
|
"""Overlap area of two boxes, normalised so a unit change cannot move it.
|
|
|
|
Stability depends on how much material two blocks share, not on the fact
|
|
that they touch; without this the model has to recompute geometry from two
|
|
coordinate vectors that the value stream never even carried.
|
|
"""
|
|
a, b = by_id.get(ed.a), by_id.get(ed.b)
|
|
if a is None or b is None:
|
|
return 0.0
|
|
ba, bb = a.attrs.get("box"), b.attrs.get("box")
|
|
if not ba or not bb:
|
|
return 0.0
|
|
ox = min(ba[3], bb[3]) - max(ba[0], bb[0])
|
|
oy = min(ba[4], bb[4]) - max(ba[1], bb[1])
|
|
if ox <= 0 or oy <= 0:
|
|
return 0.0
|
|
return min(1.0, ox * oy / (400.0 * max(1, per_unit) ** 2))
|
|
|
|
|
|
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}
|
|
f[N_EDGE + N_AXIS + 2] = _contact_area(by_id, ed, sc.obs.units.get("per_unit", 1))
|
|
f[N_EDGE + N_AXIS + 3] = 1.0 if dangling else 0.0
|
|
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)
|
|
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,
|
|
}
|