feat(spatial): 悬空关系与未知槽位,让"缺哪一段"落到位置而不是计数
此前"少了一条接触"只是全局计数,模型只能说"我在猜";它无法区分"目标根本没支撑" 和"目标的那条支撑被挡住了"。现在: - Observation.dangling:一端可见、另一端不可见的关系,锚在可见那一端,不带身份。 它说的是无知挂在哪儿,不是答案是什么。 - 模型多一个未知槽位(位置 1),悬空边的远端指向它;有悬空关系的锚定实体与它 相距一跳。一条链走到它上面,就是一条链走进了问题。 - 悬空边不参与连通计算、不进入实体的入射边求和、边特征里带 dangling 标志。 - 新增 area.free 家族:T 的唯一接触连到一个自身悬空的块,什么也没藏、什么也不悬空, 所以"没有支撑"是事实而非缺口,正确答案是 false,弃权才是错的。 它与 area.sup2h 构成最小对:同样是一条接触,一个通到未知、一个通到死路。
This commit is contained in:
1 parent
68380900ce
commit
40f6bb52fa
8 files changed
+251
-141
No files matched your search
@@ -5,9 +5,9 @@
|
||||
"rounds": 2, "n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": ["cond.p1", "cond.p3", "area.sup2", "area.sup3", "dof.c6", "dof.c6r", "cond.p1h"],
|
||||
"val_families": ["cond.p3h", "area.sup2h", "dof.c6h"],
|
||||
"test_families": ["cond.p3h", "area.sup2h", "dof.c6h"]
|
||||
"train_families": ["cond.p1", "cond.p3", "area.sup2", "area.sup3", "area.free", "dof.c6", "dof.c6r"],
|
||||
"val_families": ["cond.p1h", "area.sup2h", "dof.c6h"],
|
||||
"test_families": ["cond.p1h", "area.sup2h", "dof.c6h"]
|
||||
},
|
||||
"optim": { "lr": 0.003, "weight_decay": 0.01, "steps": 2400, "batch": 32, "log_every": 400 },
|
||||
"eval": { "n": 192 },
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 192, "n_layer": 4, "n_head": 6, "dropout": 0.1, "max_entities": 32,
|
||||
"rounds": 2, "n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": ["cond.p1", "cond.p3", "area.sup2", "area.sup3", "area.free", "dof.c6", "dof.c6r", "cond.p1h", "dof.c6h"],
|
||||
"val_families": ["area.sup2h"],
|
||||
"test_families": ["area.sup2h", "cond.p3h"]
|
||||
},
|
||||
"optim": { "lr": 0.003, "weight_decay": 0.01, "steps": 2400, "batch": 32, "log_every": 400 },
|
||||
"eval": { "n": 192 },
|
||||
"out_dir": "out_spatial/dangling"
|
||||
}
|
||||
+16
-2
@@ -94,7 +94,7 @@ def _contact_area(by_id: dict, ed, per_unit: int = 1) -> float:
|
||||
return min(1.0, ox * oy / (400.0 * max(1, per_unit) ** 2))
|
||||
|
||||
|
||||
def edge_features(sc: Scenario, ed, removed: bool) -> list:
|
||||
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")
|
||||
@@ -104,6 +104,7 @@ def edge_features(sc: Scenario, ed, removed: bool) -> list:
|
||||
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
|
||||
|
||||
|
||||
@@ -139,7 +140,7 @@ def scene_features(sc: Scenario) -> list:
|
||||
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))
|
||||
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")
|
||||
@@ -153,6 +154,7 @@ def collate(batch, max_entities: int = 32):
|
||||
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
|
||||
@@ -177,6 +179,17 @@ def collate(batch, max_entities: int = 32):
|
||||
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)
|
||||
@@ -202,5 +215,6 @@ def collate(batch, max_entities: int = 32):
|
||||
"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,
|
||||
}
|
||||
+34
-2
@@ -29,6 +29,7 @@ FAMILIES = {
|
||||
"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},
|
||||
"area.free": {"domain": "stability", "n_blocks": 2, "hidden": 0, "free": 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},
|
||||
@@ -47,6 +48,19 @@ def _observe(entities, edges, visible_edges, visible_ents, hidden_layers, camera
|
||||
"entity": dict(Counter(e.kind for e in entities if e.eid not in keep)),
|
||||
"edge": dict(Counter(e.kind for e in edges if e.eid not in visible_edges)),
|
||||
}
|
||||
# a hidden relation with one visible end becomes a dangling edge anchored on
|
||||
# that visible end. Both ends hidden leaves no mouth to report, so it stays
|
||||
# a bare count. The anchor is always something already in view: this says
|
||||
# where the ignorance attaches, never where it leads.
|
||||
dangling = []
|
||||
for e in edges:
|
||||
if e.eid in visible_edges:
|
||||
continue
|
||||
anchor = e.a if e.a in keep else (e.b if e.b in keep else None)
|
||||
if anchor is None:
|
||||
continue
|
||||
dangling.append(Edge(f"d{len(dangling)}", e.kind, anchor, "",
|
||||
layer=e.layer, source="inferred"))
|
||||
return Observation(
|
||||
entities=[e for e in entities if e.eid in keep],
|
||||
edges=vis_e,
|
||||
@@ -54,6 +68,7 @@ def _observe(entities, edges, visible_edges, visible_ents, hidden_layers, camera
|
||||
units=dict(units),
|
||||
hidden_layers=sorted(hidden_layers),
|
||||
hidden=hidden,
|
||||
dangling=dangling,
|
||||
)
|
||||
|
||||
|
||||
@@ -107,7 +122,23 @@ def _build_connection(rng, n_paths: int, hidden: int):
|
||||
# stability: stacked blocks, optional hidden pedestal
|
||||
|
||||
|
||||
def _build_stability(rng, n_blocks: int, hidden: int):
|
||||
def _build_stability(rng, n_blocks: int, hidden: int, free: int = 0):
|
||||
if free:
|
||||
# the minimal pair against area.sup2h: here T has exactly one contact and
|
||||
# that contact leads to a block which itself hangs in the air. Nothing
|
||||
# dangles and nothing is hidden, so "no support" is a fact rather than a
|
||||
# gap -- the answer is legitimately false and abstaining would be wrong.
|
||||
ents = [Entity("G", "ground", attrs={"plane": 0}),
|
||||
Entity("T", "block", attrs={"box": [42, 42, 20, 58, 58, 36]}),
|
||||
Entity("Q", "block", attrs={"box": [44, 44, 8, 56, 56, 20]}),
|
||||
Entity("D", "block", attrs={"box": [80, 40, 0, 100, 60, 16]})]
|
||||
edges = [Edge("kTQ", "contact", "Q", "T"), Edge("kDG", "contact", "D", "G")]
|
||||
query = Query(kind="stability", a="T")
|
||||
if rng.random() < 0.6:
|
||||
query.edit = {"op": "remove_entity", "entity": "Q"}
|
||||
return (ents, edges, query, {e.eid for e in edges}, {e.eid for e in ents},
|
||||
set(), ["front", "iso"], {"length": "mm", "per_unit": 1})
|
||||
|
||||
# D is a decoy: it rests on the ground next to the stack and carries
|
||||
# nothing. Without it "something was removed" and "the target lost support"
|
||||
# are the same event on every sample, and a one-bit rule fits the whole
|
||||
@@ -180,7 +211,8 @@ def _build_freedom(rng, n_cons: int, hidden: int):
|
||||
|
||||
_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"]),
|
||||
"stability": lambda rng, spec: _build_stability(rng, spec["n_blocks"], spec["hidden"],
|
||||
spec.get("free", 0)),
|
||||
"freedom": lambda rng, spec: _build_freedom(rng, spec["n_cons"], spec["hidden"]),
|
||||
}
|
||||
|
||||
|
||||
+77
-38
@@ -14,6 +14,10 @@ Differences from ``mm/model.py``, and why they are not negotiable here:
|
||||
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
|
||||
@@ -39,8 +43,8 @@ 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
|
||||
EDGE_FEAT_DIM = N_EDGE + N_AXIS + 3
|
||||
# type one-hot, axis one-hot, removed flag, layer, contact area, dangling flag
|
||||
EDGE_FEAT_DIM = N_EDGE + N_AXIS + 4
|
||||
QUERY_KINDS = ("connection", "stability", "freedom")
|
||||
|
||||
HOP_MAX = 4 # longer paths collapse into one bucket
|
||||
@@ -52,6 +56,9 @@ FAR = HOP_MAX + 1 # unreachable, or "involves the query token"
|
||||
# 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.
|
||||
@@ -132,6 +139,7 @@ class RelationBackbone(nn.Module):
|
||||
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))
|
||||
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)
|
||||
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
|
||||
@@ -143,6 +151,7 @@ class RelationBackbone(nn.Module):
|
||||
# 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))
|
||||
|
||||
@@ -166,33 +175,41 @@ class RelationBackbone(nn.Module):
|
||||
self.log_temp = nn.Parameter(torch.zeros(1))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
def _hop_matrix(self, dist_ent, top, edge_index, n_ent: int, K: int) -> torch.Tensor:
|
||||
"""(B, 1+N+K, 1+N+K) hop buckets, including the query token and the
|
||||
evidence slots so every pair of positions has an entry."""
|
||||
def _hop_matrix(self, dist_ent, anchor, top, pos, 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 = 1 + n_ent + K
|
||||
T = ENT0 + n_ent + K
|
||||
hop = torch.full((B, T, T), FAR, dtype=torch.long, device=device)
|
||||
hop[:, 1:1 + n_ent, 1:1 + n_ent] = dist_ent
|
||||
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(1 + n_ent, T, device=device)
|
||||
slots = torch.arange(ENT0 + n_ent, T, device=device)
|
||||
hop[:, slots, slots] = 0
|
||||
if top is not None:
|
||||
ar = torch.arange(B, device=device)
|
||||
pair = edge_index[ar.unsqueeze(1), top.clamp(min=0)]
|
||||
pair = pos[ar.unsqueeze(1), top.clamp(min=0)]
|
||||
a, b = pair[..., 0].clamp(min=0), pair[..., 1].clamp(min=0)
|
||||
pad = torch.full((B, K, n_ent), FAR, dtype=torch.long, device=device)
|
||||
d = torch.minimum(dist_ent.gather(2, a.unsqueeze(-1).expand(B, K, n_ent)),
|
||||
dist_ent.gather(2, b.unsqueeze(-1).expand(B, K, n_ent)))
|
||||
d = torch.where(d >= FAR, pad, d + 1)
|
||||
d = d.clamp(max=FAR)
|
||||
hop[:, slots, 1:1 + n_ent] = d
|
||||
hop[:, 1:1 + n_ent, slots] = d.transpose(1, 2)
|
||||
d = torch.where(d >= FAR, pad, 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, edge_index, edge_type, edge_mask, edge_removed, 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
|
||||
@@ -200,13 +217,13 @@ class RelationBackbone(nn.Module):
|
||||
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)
|
||||
src = edge_index[..., 0] + 1
|
||||
dst = edge_index[..., 1] + 1
|
||||
bidx = torch.arange(B, device=edge_index.device).unsqueeze(1).expand_as(src)
|
||||
|
||||
def add(mask, vec, flip=False):
|
||||
if not mask.any():
|
||||
@@ -225,26 +242,29 @@ class RelationBackbone(nn.Module):
|
||||
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, n_ent, edge_index, edge_type, edge_removed, edge_feat_emb, q_out):
|
||||
B = x.size(0)
|
||||
ent = x[:, 1:1 + n_ent]
|
||||
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 = ent[ar, edge_index[..., 0].clamp(min=0, max=n_ent - 1)]
|
||||
eb = ent[ar, edge_index[..., 1].clamp(min=0, max=n_ent - 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
|
||||
# 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):
|
||||
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
|
||||
@@ -253,14 +273,31 @@ class RelationBackbone(nn.Module):
|
||||
|
||||
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: index_put_ with
|
||||
# accumulate keeps the backward pass simple, but a matmul keeps it
|
||||
# obvious that an entity receiving three edges sums three vectors.
|
||||
# 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.
|
||||
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)
|
||||
@@ -268,7 +305,7 @@ class RelationBackbone(nn.Module):
|
||||
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)
|
||||
inc = inc * edge_mask.unsqueeze(1).to(inc.dtype)
|
||||
inc = inc * (edge_mask & ~has_unk).unsqueeze(1).to(inc.dtype)
|
||||
msg = torch.bmm(inc, ef)
|
||||
|
||||
# query token is read out of the two entities it names
|
||||
@@ -297,36 +334,38 @@ class RelationBackbone(nn.Module):
|
||||
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, h, zeros_ev], dim=1) # (B, 1+N+K, d)
|
||||
v_extra = torch.cat([torch.zeros(B, 1, self.d, device=device), msg, zeros_ev], dim=1)
|
||||
pad = torch.cat([torch.zeros(B, 1, dtype=torch.bool, device=device), pad_mask,
|
||||
torch.ones(B, K, dtype=torch.bool, device=device)], dim=1)
|
||||
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, edge_removed, n_ent)
|
||||
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, top, edge_index, n_ent, K)
|
||||
bias = self._bias(edge_index, edge_type, edge_mask, edge_removed, hop)
|
||||
hop = self._hop_matrix(dist, anchor, top, pos, 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, n_ent, edge_index, edge_type, edge_removed, ef, q_out)
|
||||
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[:, :1 + n_ent],
|
||||
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[:, :1 + n_ent], ~filled], dim=1)
|
||||
pad = torch.cat([pad[:, :ENT0 + n_ent], ~filled], dim=1)
|
||||
|
||||
return {
|
||||
"answer": self.answer_head(q_out) * temp,
|
||||
|
||||
+89
-89
@@ -1,89 +1,89 @@
|
||||
"""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 .train import load
|
||||
|
||||
ANSWERS = ("true", "false", "unknown")
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def family_row(model, family: str, seed: int, n: int, max_entities: int = 32) -> 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()}
|
||||
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"])
|
||||
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) -> None:
|
||||
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ckpt = os.path.join(root, "out_spatial", os.path.basename(config_path).replace(".json", ""),
|
||||
"ckpt.pt")
|
||||
model, _, step, cfg = load(ckpt, "cuda" if torch.cuda.is_available() else "cpu")
|
||||
model.eval()
|
||||
print(f"step {step} families: train={cfg['data']['train_families']} "
|
||||
f"val={cfg['data']['val_families']}")
|
||||
head = f"{'family':11s} {'n':>3s} {'dec':>4s} {'unk':>4s} {'acc':>5s} {'abst':>5s} " \
|
||||
f"{'cert':>5s} {'#true':>5s} {'conf':>5s}"
|
||||
print(head)
|
||||
print("-" * len(head))
|
||||
for fam in generator.FAMILIES:
|
||||
r = family_row(model, fam, cfg["seed"], n, cfg["model"]["max_entities"])
|
||||
print(f"{r['family']:11s} {r['n']:3d} {r['decidable']:4d} {r['unknown']:4d} "
|
||||
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 .train import load
|
||||
|
||||
ANSWERS = ("true", "false", "unknown")
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def family_row(model, family: str, seed: int, n: int, max_entities: int = 32) -> 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()}
|
||||
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) -> None:
|
||||
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ckpt = os.path.join(root, "out_spatial", os.path.basename(config_path).replace(".json", ""),
|
||||
"ckpt.pt")
|
||||
model, _, step, cfg = load(ckpt, "cuda" if torch.cuda.is_available() else "cpu")
|
||||
model.eval()
|
||||
print(f"step {step} families: train={cfg['data']['train_families']} "
|
||||
f"val={cfg['data']['val_families']}")
|
||||
head = f"{'family':11s} {'n':>3s} {'dec':>4s} {'unk':>4s} {'acc':>5s} {'abst':>5s} " \
|
||||
f"{'cert':>5s} {'#true':>5s} {'conf':>5s}"
|
||||
print(head)
|
||||
print("-" * len(head))
|
||||
for fam in generator.FAMILIES:
|
||||
r = family_row(model, fam, cfg["seed"], n, cfg["model"]["max_entities"])
|
||||
print(f"{r['family']:11s} {r['n']:3d} {r['decidable']:4d} {r['unknown']:4d} "
|
||||
f"{r['acc']:5.3f} {r['abst']:5.3f} {r['cert']:5.3f} {r['n_true']:5d} "
|
||||
f"{r['conf']:5.3f}")
|
||||
+16
-6
@@ -86,12 +86,20 @@ class Edge:
|
||||
class Observation:
|
||||
"""What the model sees. Only visible items are stored here.
|
||||
|
||||
``hidden`` is the one thing here that is not visible, and it is deliberate:
|
||||
it counts what the full state contains that this view does not. Without it
|
||||
"nothing is there" and "it is behind the part" are the same input, and the
|
||||
two have different answers -- no reasoning can recover a distinction that
|
||||
the input never carried. It records counts by kind, never identities, so it
|
||||
says *that* a support is missing, not *which* one.
|
||||
``hidden`` and ``dangling`` are the two things here that are not visible, and
|
||||
they are deliberate.
|
||||
|
||||
``hidden`` counts by kind what the full state contains and this view does
|
||||
not. Without it "nothing is there" and "it is behind the part" are the same
|
||||
input, and the two have different answers -- no reasoning can recover a
|
||||
distinction the input never carried.
|
||||
|
||||
``dangling`` is the sharper form of the same idea: a relation whose one end
|
||||
is visible and whose other end is not. It carries no identity -- the anchor
|
||||
is the entity you can already see, never the one you cannot -- so it says
|
||||
*where* the unknown attaches, not *what* the answer is. A support that
|
||||
dangles still does not decide anything, which is why a chain that ends in a
|
||||
dangling edge is evidence of ignorance rather than evidence of support.
|
||||
"""
|
||||
|
||||
entities: list = field(default_factory=list)
|
||||
@@ -101,6 +109,7 @@ class Observation:
|
||||
hidden_layers: list = field(default_factory=list)
|
||||
hidden_faces: list = field(default_factory=list)
|
||||
hidden: dict = field(default_factory=lambda: {"entity": {}, "edge": {}})
|
||||
dangling: list = field(default_factory=list)
|
||||
|
||||
def entity_ids(self) -> set:
|
||||
return {e.eid for e in self.entities}
|
||||
@@ -114,6 +123,7 @@ class Observation:
|
||||
"hidden_layers": sorted(self.hidden_layers),
|
||||
"hidden_faces": sorted(self.hidden_faces),
|
||||
"hidden": {k: dict(sorted(v.items())) for k, v in sorted(self.hidden.items())},
|
||||
"dangling": [e.to_dict() for e in sorted(self.dangling, key=lambda x: x.eid)],
|
||||
}
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ 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"),
|
||||
tensors.get("edge_feat"), tensors.get("scene"))
|
||||
tensors.get("edge_feat"), tensors.get("scene"), tensors.get("dangling"))
|
||||
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"]]
|
||||
|
||||
Reference in new issue
Block a user