Datasets:
File size: 9,701 Bytes
a863f79 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | import argparse
import glob
import json
from pathlib import Path
def load(path):
return [json.loads(line) for line in Path(path).open(encoding="utf-8")]
def decide_witness(row, params):
if not row.get("detected"):
return "UNKNOWN"
claim = row["claim"]
sub = row["subject_box"]
obj = row["object_box"]
if claim == "left":
if abs(row["dx"]) >= params["margin_x"]:
return "SUPPORT" if row["dx"] < 0 else "REFUTE"
return "UNKNOWN"
if claim == "above":
gap = sub[3] - obj[1]
if gap <= -params["margin_y"]:
return "SUPPORT"
if gap >= params["margin_y"]:
return "UNKNOWN" if gap < 2 * params["margin_y"] else "REFUTE"
return "UNKNOWN"
if claim == "front":
if abs(row["dz"]) >= params["margin_depth"]:
return "SUPPORT" if row["dz"] > 0 else "REFUTE"
return "UNKNOWN"
edge_gap = sub[3] - obj[1]
if abs(edge_gap) <= params["contact_gap"] and row["overlap"] >= params["overlap_min"]:
return "SUPPORT"
if edge_gap <= -2 * params["contact_gap"] or row["overlap"] <= 0.5 * params["overlap_min"]:
return "REFUTE"
return "UNKNOWN"
def index_predictions(rows):
table = {}
for row in rows:
table[(row["scene_id"], row["state"], row["condition"])] = row
return table
def score(scenes, answer_of, name, extra_calls):
total = len(scenes)
correct = sum(1 for s in scenes if answer_of(s) == s["truth"])
answered = sum(1 for s in scenes if answer_of(s) is not None)
harm = sum(1 for s in scenes if s["baseline_correct"] and answer_of(s) is not None and answer_of(s) != s["truth"])
repair = sum(1 for s in scenes if not s["baseline_correct"] and answer_of(s) == s["truth"])
induced = sum(1 for s in scenes if s["baseline_correct"] and answer_of(s) is not None and answer_of(s) != s["truth"])
return {
"method": name,
"n": total,
"accuracy": correct / total if total else 0.0,
"answered": answered,
"accuracy_answered": correct / answered if answered else None,
"coverage": answered / total if total else 0.0,
"induced_error": induced / total if total else 0.0,
"harm_rate": harm / max(1, sum(1 for s in scenes if s["baseline_correct"])),
"repair_rate": repair / max(1, sum(1 for s in scenes if not s["baseline_correct"])),
"extra_calls": extra_calls,
}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--truth", required=True)
parser.add_argument("--witness", required=True)
parser.add_argument("--params", required=True)
parser.add_argument("--pred", required=True)
parser.add_argument("--check-pred", default=None)
parser.add_argument("--out", required=True)
args = parser.parse_args()
params = json.loads(Path(args.params).read_text(encoding="utf-8"))["best"]
truth = {(r["scene_id"], r["state"]): r for r in load(args.truth)}
witness = {(r["scene_id"], r["state"]): r for r in load(args.witness)}
pred_rows = []
for pattern in args.pred.split(","):
for path in sorted(glob.glob(pattern)):
pred_rows.extend(load(path))
if not pred_rows:
raise RuntimeError(f"no predictions matched {args.pred}")
pred = index_predictions(pred_rows)
check = None
if args.check_pred:
check_rows = []
for pattern in args.check_pred.split(","):
for path in sorted(glob.glob(pattern)):
check_rows.extend(load(path))
check = index_predictions(check_rows)
scenes = []
for key, row in sorted(witness.items()):
t = truth[key]
truth_answer = t["computed"]
if truth_answer not in ("yes", "no"):
raise RuntimeError(f"bad computed truth {truth_answer!r} for {key}")
base = pred.get((key[0], key[1], "T0"))
if base is None:
raise RuntimeError(f"missing T0 prediction for {key}")
claim_pred = pred.get((key[0], key[1], "Tpos"))
scenes.append({
"scene_id": key[0],
"state": key[1],
"family": row["family"],
"truth": truth_answer,
"verdict": decide_witness(row, params),
"witness_score": min(row.get("subject_score") or 0.0, row.get("object_score") or 0.0),
"baseline_answer": base["answer"],
"baseline_correct": base["answer"] == truth_answer,
"claim_answer": claim_pred["answer"] if claim_pred else None,
"check_answer": (check.get((key[0], key[1], "Tpos")) or {}).get("answer") if check else None,
})
def direct(s):
return s["baseline_answer"]
def trust_all(s):
return "yes"
def vcg(s):
if s["verdict"] == "SUPPORT":
return "yes"
if s["verdict"] == "REFUTE":
return "no"
return s["baseline_answer"]
def independent(s):
return s["check_answer"]
def support_only(s):
if s["verdict"] == "SUPPORT":
return "yes"
return s["baseline_answer"]
def confident(s):
if s["verdict"] in ("SUPPORT", "REFUTE") and s["witness_score"] >= 0.35:
return "yes" if s["verdict"] == "SUPPORT" else "no"
return s["baseline_answer"]
def witness_only(s):
if s["verdict"] == "SUPPORT":
return "yes"
if s["verdict"] == "REFUTE":
return "no"
return None
def risk_coverage(scenes):
thresholds = [round(0.05 * i, 2) for i in range(0, 19)]
curves = {"vcg": [], "vcg_support_only": [], "direct_on_same_subset": [],
"direct_on_support_subset": []}
for t in thresholds:
for name in ("vcg", "vcg_support_only"):
committed = []
for s in scenes:
if s["verdict"] == "UNKNOWN" or s["witness_score"] < t:
continue
if name == "vcg_support_only" and s["verdict"] != "SUPPORT":
continue
answer = "yes" if s["verdict"] == "SUPPORT" else "no"
committed.append(1 if answer == s["truth"] else 0)
total = sum(committed)
curves[name].append({
"threshold": t,
"n_committed": len(committed),
"coverage": len(committed) / len(scenes) if scenes else None,
"risk": (1 - total / len(committed)) if committed else None,
})
if name == "vcg":
direct_hits = []
for s in scenes:
if s["verdict"] == "UNKNOWN" or s["witness_score"] < t:
continue
direct_hits.append(1 if s["baseline_correct"] else 0)
base = sum(direct_hits)
curves["direct_on_same_subset"].append({
"threshold": t,
"n_committed": len(direct_hits),
"coverage": len(direct_hits) / len(scenes) if scenes else None,
"risk": (1 - base / len(direct_hits)) if direct_hits else None,
})
if name == "vcg_support_only":
support_hits = []
for s in scenes:
if s["verdict"] != "SUPPORT" or s["witness_score"] < t:
continue
support_hits.append(1 if s["baseline_correct"] else 0)
base = sum(support_hits)
curves["direct_on_support_subset"].append({
"threshold": t,
"n_committed": len(support_hits),
"coverage": len(support_hits) / len(scenes) if scenes else None,
"risk": (1 - base / len(support_hits)) if support_hits else None,
})
return curves
results = {
"params": params,
"methods": [
score(scenes, direct, "direct_only", 0),
score(scenes, trust_all, "trust_all", 0),
score(scenes, vcg, "vcg", 2),
score(scenes, support_only, "vcg_support_only", 2),
score(scenes, confident, "vcg_confident", 2),
score(scenes, witness_only, "witness_only", 2),
],
}
if check:
results["methods"].append(score(scenes, independent, "independent_vlm_check", 1))
by_family = {}
for family in sorted({s["family"] for s in scenes}):
subset = [s for s in scenes if s["family"] == family]
by_family[family] = {
"direct_only": score(subset, direct, "direct_only", 0)["accuracy"],
"vcg": score(subset, vcg, "vcg", 2)["accuracy"],
"vcg_support_only": score(subset, support_only, "vcg_support_only", 2)["accuracy"],
"trust_all": score(subset, trust_all, "trust_all", 0)["accuracy"],
"support_rate": sum(1 for s in subset if s["verdict"] == "SUPPORT") / len(subset),
"refute_rate": sum(1 for s in subset if s["verdict"] == "REFUTE") / len(subset),
"coverage": score(subset, vcg, "vcg", 2)["coverage"],
}
results["by_family"] = by_family
results["risk_coverage"] = risk_coverage(scenes)
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps({m["method"]: round(m["accuracy"], 4) for m in results["methods"]}, ensure_ascii=False))
if __name__ == "__main__":
main()
|