Files
tiny-gpt/spatial/checker.py
T
x 813be2906b fix(spatial): 有隐藏内容时改用单调规则给标签
旧规则只比较"全状态"和"观测自己的世界"这两个世界。于是"底座在零件后面,而在这
个具体场景里它本来也帮不上忙"被判成可判 false——这不是 agent 能知道的事实:另一个
同样符合观测的世界把底座挪到形心底下,答案就翻了。

隐藏内容只会增加证据(导通的边只会连上、接触只会支撑、配合只会锁轴),不会推翻
观测里已有的证明。所以:可见结构已经证明 → 可判 true;没证明 → unknown,不管手上
那一个全状态怎么裁。这一条同时把上一轮 area.sup2h 那 36 条假"可判"消掉。
2026-12-03 20:46:25 +08:00

305 lines
11 KiB
Python

"""Reference checker.
The generator only builds structure; every label is produced here from the full
state, then downgraded to ``unknown`` whenever the observation admits a
different answer. That downgrade rule is what makes "evidence insufficient" a
real label instead of a random occlusion tag:
answers = {answer(full), answer(full restricted to the observation)}
if len(answers) != 1 -> unknown
Restricting the full state to what is visible is the cheapest way to build the
"same observation, opposite truth" pair that the plan asks for, and it needs no
special case per domain.
Nothing here imports the model, so a disagreement between the two is real.
"""
from __future__ import annotations
from collections import defaultdict, deque
from typing import Iterable, Optional
from .schema import (DOF_AXES, Edge, Entity, FullState, Label, Observation,
Query)
# --------------------------------------------------------------------------
# query edits
def _removed_edge(query: Query) -> Optional[str]:
if query.edit and query.edit.get("op") == "remove_edge":
return query.edit.get("edge")
return None
def _removed_entity(query: Query) -> Optional[str]:
if query.edit and query.edit.get("op") == "remove_entity":
return query.edit.get("entity")
return None
def _alive_edges(edges: Iterable[Edge], query: Query) -> list:
drop = _removed_edge(query)
return [e for e in edges if e.eid != drop]
def _alive_entities(entities: Iterable[Entity], query: Query) -> list:
drop = _removed_entity(query)
return [e for e in entities if e.eid != drop]
def _index(entities: Iterable[Entity]) -> dict:
return {e.eid: e for e in entities}
# --------------------------------------------------------------------------
# connection
def conduct_path(edges: Iterable[Edge], src: str, dst: str) -> Optional[list]:
adj = defaultdict(list)
for e in edges:
if e.kind != "conduct":
continue
adj[e.a].append((e.b, e.eid))
adj[e.b].append((e.a, e.eid))
if src == dst:
return []
prev = {src: (None, None)}
q = deque([src])
while q:
u = q.popleft()
for v, eid in adj[u]:
if v in prev:
continue
prev[v] = (u, eid)
if v == dst:
path = []
while v != src:
v, pe = prev[v]
path.append(pe)
return list(reversed(path))
q.append(v)
return None
def _connection_answer(entities, edges, query: Query) -> Optional[bool]:
idx = _index(_alive_entities(entities, query))
if query.a not in idx or query.b not in idx:
return None
return conduct_path(_alive_edges(edges, query), query.a, query.b) is not None
# --------------------------------------------------------------------------
# stability
def _box(e: Entity):
b = e.attrs.get("box")
return tuple(b) if b else None
def _overlap(a, b):
ox0, oy0 = max(a[0], b[0]), max(a[1], b[1])
ox1, oy1 = min(a[3], b[3]), min(a[4], b[4])
if ox0 >= ox1 or oy0 >= oy1:
return None
return (ox0, oy0, ox1, oy1)
def stable_blocks(entities) -> dict:
"""{block eid: supporter eid or "ground"} for blocks that stand."""
blocks = [e for e in entities if e.kind == "block" and _box(e)]
support, stable = {}, set()
changed = True
while changed:
changed = False
for b in blocks:
if b.eid in stable:
continue
x0, y0, z0, x1, y1, _ = _box(b)
if z0 == 0:
stable.add(b.eid)
support[b.eid] = "ground"
changed = True
continue
cx2, cy2 = x0 + x1, y0 + y1 # twice the centroid: stays integer
for s in blocks:
if s.eid == b.eid or s.eid not in stable:
continue
sx0, sy0, _, sx1, sy1, sz1 = _box(s)
if sz1 != z0:
continue
ov = _overlap(_box(b), _box(s))
if ov is None:
continue
if 2 * ov[0] <= cx2 <= 2 * ov[2] and 2 * ov[1] <= cy2 <= 2 * ov[3]:
stable.add(b.eid)
support[b.eid] = s.eid
changed = True
break
return support
def _stability_answer(entities, edges, query: Query) -> Optional[bool]:
alive = _alive_entities(entities, query)
part = _index(alive).get(query.a)
if part is None or part.kind != "block":
return None
return query.a in stable_blocks(alive)
# --------------------------------------------------------------------------
# freedom
def _freedom_answer(entities, edges, query: Query) -> Optional[bool]:
idx = _index(_alive_entities(entities, query))
part = idx.get(query.a)
if part is None or part.kind != "part":
return None
covered = {e.attrs.get("axis") for e in _alive_edges(edges, query) if e.kind == "constraint"}
return len(covered & set(DOF_AXES)) == len(DOF_AXES)
_ANSWER_FN = {
"connection": _connection_answer,
"stability": _stability_answer,
"freedom": _freedom_answer,
}
def evaluate(entities, edges, query: Query) -> Optional[bool]:
fn = _ANSWER_FN.get(query.kind)
if fn is None:
raise ValueError(f"unknown query kind {query.kind!r}")
return fn(list(entities), list(edges), query)
# --------------------------------------------------------------------------
# certificates
def evidence_for(full: FullState, query: Query) -> list:
"""One certificate, as edge ids. Several may be valid; the checker accepts
any that validates."""
edges = _alive_edges(full.edges, query)
ents = _alive_entities(full.entities, query)
if query.kind == "connection":
return conduct_path(edges, query.a, query.b) or []
if query.kind == "freedom":
picked, seen = [], set()
for e in edges:
if e.kind != "constraint":
continue
ax = e.attrs.get("axis")
if ax in DOF_AXES and ax not in seen:
seen.add(ax)
picked.append(e.eid)
return picked if len(seen) == len(DOF_AXES) else []
if query.kind == "stability":
support = stable_blocks(ents)
if query.a not in support:
return []
chain, cur = [], query.a
while support.get(cur) not in (None, "ground"):
nxt = support[cur]
edge = next((e for e in edges if e.kind == "contact"
and {e.a, e.b} == {cur, nxt}), None)
if edge is None:
break
chain.append(edge.eid)
cur = nxt
return chain
return []
def validate_evidence(full: FullState, query: Query, evidence) -> bool:
"""Independent re-check of a claimed certificate."""
evidence = list(evidence or [])
if not evidence or _removed_edge(query) in evidence:
return False
by_id = {e.eid: e for e in full.edges}
if any(eid not in by_id for eid in evidence):
return False
edges = [by_id[eid] for eid in evidence]
if query.kind == "connection":
return conduct_path(edges, query.a, query.b) is not None
if query.kind == "freedom":
covered = {e.attrs.get("axis") for e in edges if e.kind == "constraint"}
return len(covered & set(DOF_AXES)) == len(DOF_AXES)
if query.kind == "stability":
if any(e.kind != "contact" for e in edges):
return False
ents = _index(full.entities)
if query.a not in ents:
return False
reached = {query.a}
for _ in range(len(edges) + 1):
for e in edges:
if e.a in reached:
reached.add(e.b)
elif e.b in reached:
reached.add(e.a)
return any(eid in ents and ents[eid].kind == "ground" for eid in reached) or \
any(eid in ents and _box(ents[eid]) is not None and _box(ents[eid])[2] == 0
for eid in reached)
return False
# --------------------------------------------------------------------------
# label
def label(obs: Observation, full: FullState, query: Query,
alternatives: Iterable[FullState] = ()) -> Label:
"""Full state decides; the observation decides whether we may say so.
When something is withheld the rule is *monotone*: a hidden conduct edge can
only connect, a hidden contact can only support, a hidden mate can only lock
an axis. None of them can undo a proof the observation already contains. So
* the visible structure already proves the answer -> decidable "true";
* it does not -> the withheld item could be exactly the missing piece, and
the answer is unknown, however the one full state we happen to hold
resolves it.
The cheaper rule -- compare the full state against the observation's own
world -- marks "the pedestal is behind the part and in this particular scene
it would not have helped" as decidable false. That is not a fact the agent
can know: another equally consistent world puts the pedestal under the
centroid and the answer flips. Measured: area.sup2h came out 36 decidable /
92 not, and the model swung between answering all of them and abstaining
from all of them, because the split is not in the observation.
"""
ans_full = evaluate(full.entities, full.edges, query)
alt = list(alternatives)
ans_vis = evaluate(alt[0].entities, alt[0].edges, query) if alt else ans_full
withheld = bool(obs.dangling) or bool((obs.hidden or {}).get("entity")) \
or bool((obs.hidden or {}).get("edge"))
if withheld:
if ans_vis is True:
# the observation proves it on its own; nothing withheld can break it
return Label(answer="true", change=_change(full, query, True),
evidence=evidence_for(alt[0], query) if alt else [], sufficient=True)
return Label(answer="unknown", change="unknown", evidence=[], sufficient=False)
if ans_full is None or ans_vis is None or ans_full != ans_vis:
return Label(answer="unknown", change="unknown", evidence=[], sufficient=False)
return Label(answer="true" if ans_full else "false",
change=_change(full, query, ans_full),
evidence=evidence_for(full, query), sufficient=True)
def _change(full: FullState, query: Query, ans_after) -> str:
if query.edit is None:
return "same"
before = Query(kind=query.kind, a=query.a, b=query.b, edit=None)
ans_before = evaluate(full.entities, full.edges, before)
if ans_before is None:
return "unknown"
return "changed" if ans_before != ans_after else "same"