feat(spatial): scope 进模型输入,并把泄漏位与合规位分成可分别消融的两片

This commit is contained in:
liuhuajie committed 2026-12-03 23:20:42 +08:00
1 parent 762b4d347d
commit efe1ee6801
4 files changed
+796 -764

No files matched your search

+117 -112
View File
@@ -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}")