leaf0932's picture
Public CausalMedBench benchmark release
e091e85
Raw History Blame Contribute Delete
12.4 kB
#!/usr/bin/env python3
"""Score CausalMedBench prediction JSONL files.
The script downloads only benchmark metadata when images are not accessed.
Predictions are joined by stable ``record_id`` values, so file order is ignored.
"""
from __future__ import annotations
import argparse
import json
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable
from datasets import load_dataset
REPO_ID = "leaf0932/CausalMedBench"
VIEWS = (
"forged_original",
"authentic_source",
"local_restored",
"local_forged_only",
"authentic_nuisance",
)
EXPECTED_REASONING = {
"forged_original": (
"fake",
{"mixed"},
{"mixed", "local_bbox"},
),
"authentic_source": ("real", {"none"}, {"none"}),
"local_restored": ("fake", {"global_forensic"}, {"global_or_outside"}),
"local_forged_only": (
"fake",
{"local_medical", "local_forensic", "local_medical_and_local_forensic"},
{"local_bbox"},
),
"authentic_nuisance": ("real", {"none"}, {"none"}),
}
def read_jsonl(path: Path) -> Iterable[dict[str, Any]]:
with path.open("r", encoding="utf-8") as stream:
for line_number, line in enumerate(stream, start=1):
if not line.strip():
continue
try:
value = json.loads(line)
except json.JSONDecodeError as error:
raise ValueError(f"Invalid JSON at {path}:{line_number}: {error}") from error
if not isinstance(value, dict):
raise ValueError(f"Expected an object at {path}:{line_number}")
yield value
def normalize_label(value: Any) -> str | None:
label = str(value or "").strip().lower()
if label.startswith("verdict:"):
label = label.split(":", 1)[1].strip()
return label if label in {"real", "fake"} else None
def prediction_index(path: Path) -> dict[str, dict[str, Any]]:
result: dict[str, dict[str, Any]] = {}
for row in read_jsonl(path):
record_id = str(row.get("record_id") or "").strip()
if not record_id:
raise ValueError(f"Missing record_id in {path}")
if record_id in result:
raise ValueError(f"Duplicate record_id in {path}: {record_id}")
label = normalize_label(row.get("verdict", row.get("label")))
result[record_id] = {**row, "label": label}
return result
def ground_truth_rows(dataset: Any) -> list[dict[str, Any]]:
columns = [name for name in dataset.column_names if name != "image"]
return [{name: row[name] for name in columns} for row in dataset]
def merge_predictions(
truth: list[dict[str, Any]],
predictions: dict[str, dict[str, Any]],
*,
strict: bool,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
truth_ids = {str(row["record_id"]) for row in truth}
unknown = sorted(set(predictions) - truth_ids)
if unknown:
raise ValueError(f"Predictions contain {len(unknown)} unknown record_id values; first: {unknown[0]}")
merged = []
missing = []
for row in truth:
record_id = str(row["record_id"])
prediction = predictions.get(record_id)
if prediction is None:
missing.append(record_id)
prediction = {"label": None}
merged.append({**row, "prediction": prediction})
if strict and missing:
raise ValueError(f"Missing {len(missing)} predictions; first: {missing[0]}")
return merged, {
"expected": len(truth),
"submitted": len(predictions),
"matched": len(truth) - len(missing),
"missing": len(missing),
"coverage": (len(truth) - len(missing)) / len(truth) if truth else 0.0,
}
def binary_metrics(rows: list[dict[str, Any]]) -> dict[str, Any]:
matrix: Counter[tuple[str, str]] = Counter()
parsed = 0
for row in rows:
target = str(row["target_label"]).lower()
predicted = row["prediction"].get("label")
if predicted in {"real", "fake"}:
parsed += 1
matrix[(target, predicted)] += 1
tp = matrix[("fake", "fake")]
tn = matrix[("real", "real")]
fp = matrix[("real", "fake")]
fn = matrix[("fake", "real")]
fake_precision = tp / (tp + fp) if tp + fp else 0.0
fake_recall = tp / (tp + fn) if tp + fn else 0.0
fake_f1 = (
2 * fake_precision * fake_recall / (fake_precision + fake_recall)
if fake_precision + fake_recall
else 0.0
)
real_precision = tn / (tn + fn) if tn + fn else 0.0
real_recall = tn / (tn + fp) if tn + fp else 0.0
real_f1 = (
2 * real_precision * real_recall / (real_precision + real_recall)
if real_precision + real_recall
else 0.0
)
n = len(rows)
return {
"n": n,
"parsed": parsed,
"coverage": parsed / n if n else 0.0,
"accuracy": (tp + tn) / n if n else 0.0,
"fake_precision": fake_precision,
"fake_recall": fake_recall,
"fake_f1": fake_f1,
"macro_f1": (fake_f1 + real_f1) / 2,
"confusion": {"tp_fake": tp, "tn_real": tn, "fp_fake": fp, "fn_fake": fn},
}
def grouped_metrics(rows: list[dict[str, Any]], field: str) -> dict[str, Any]:
groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
for row in rows:
groups[str(row.get(field) or "unknown")].append(row)
return {key: binary_metrics(values) for key, values in sorted(groups.items())}
def five_view_metrics(rows: list[dict[str, Any]]) -> dict[str, Any]:
by_view: dict[str, list[dict[str, Any]]] = defaultdict(list)
by_group: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict)
for row in rows:
by_view[str(row["view_id"])].append(row)
by_group[str(row["group_id"])][str(row["view_id"])] = row
complete = 0
all_correct = 0
contrast = Counter()
for views in by_group.values():
if not set(VIEWS).issubset(views):
continue
complete += 1
labels = {view: views[view]["prediction"].get("label") for view in VIEWS}
contrast["authentic_recovery"] += int(
labels["forged_original"] == "fake" and labels["authentic_source"] == "real"
)
contrast["global_evidence_sufficiency"] += int(
labels["forged_original"] == "fake" and labels["local_restored"] == "fake"
)
contrast["local_evidence_sufficiency"] += int(
labels["authentic_source"] == "real" and labels["local_forged_only"] == "fake"
)
contrast["benign_nuisance_invariance"] += int(
labels["authentic_source"] == "real" and labels["authentic_nuisance"] == "real"
)
targets = {view: ("real" if view in {"authentic_source", "authentic_nuisance"} else "fake") for view in VIEWS}
all_correct += int(all(labels[view] == targets[view] for view in VIEWS))
return {
"overall": binary_metrics(rows),
"by_view": {key: binary_metrics(values) for key, values in sorted(by_view.items())},
"complete_groups": complete,
"five_view_consistency": all_correct / complete if complete else 0.0,
"paired_contrasts": {
key: value / complete if complete else 0.0 for key, value in sorted(contrast.items())
},
"by_modality": grouped_metrics(rows, "modality"),
"by_forgery_type": grouped_metrics(rows, "forgery_type"),
"by_generator": grouped_metrics(rows, "generator"),
}
def reasoning_metrics(rows: list[dict[str, Any]]) -> dict[str, Any]:
totals = Counter()
by_view: dict[str, Counter[str]] = defaultdict(Counter)
group_checks: dict[str, list[bool]] = defaultdict(list)
failures = []
for row in rows:
view = str(row["view_id"])
expected_label, expected_types, expected_locations = EXPECTED_REASONING[view]
prediction = row["prediction"]
evidence_type = str(prediction.get("evidence_type") or "").strip().lower()
location = str(prediction.get("evidence_location") or "").strip().lower()
label_ok = prediction.get("label") == expected_label
type_ok = evidence_type in expected_types
location_ok = location in expected_locations
joint = label_ok and type_ok and location_ok
values = {
"n": 1,
"verdict_ok": int(label_ok),
"evidence_type_ok": int(type_ok),
"evidence_location_ok": int(location_ok),
"joint_alignment": int(joint),
}
totals.update(values)
by_view[view].update(values)
group_checks[str(row["group_id"])].append(joint)
if not joint and len(failures) < 20:
failures.append({
"record_id": row["record_id"],
"expected": {
"verdict": expected_label,
"evidence_type": sorted(expected_types),
"evidence_location": sorted(expected_locations),
},
"prediction": prediction,
})
def rates(values: Counter[str]) -> dict[str, float | int]:
n = values["n"]
return {key: (value if key == "n" else value / n if n else 0.0) for key, value in values.items()}
return {
"overall": rates(totals),
"by_view": {key: rates(values) for key, values in sorted(by_view.items())},
"five_view_strict_alignment": (
sum(len(values) == len(VIEWS) and all(values) for values in group_checks.values())
/ len(group_checks)
if group_checks
else 0.0
),
"failure_examples": failures,
}
def load_truth(repo_id: str, cache_dir: str | None) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
ordinary = load_dataset(repo_id, "ordinary", split="test", cache_dir=cache_dir)
five_view = load_dataset(repo_id, "five_view", split="test", cache_dir=cache_dir)
return ground_truth_rows(ordinary), ground_truth_rows(five_view)
def main() -> None:
parser = argparse.ArgumentParser(description="Score a CausalMedBench submission")
parser.add_argument("--ordinary-predictions", type=Path)
parser.add_argument("--five-view-predictions", type=Path)
parser.add_argument("--reasoning-predictions", type=Path)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--repo-id", default=REPO_ID)
parser.add_argument("--cache-dir")
parser.add_argument("--allow-partial", action="store_true")
args = parser.parse_args()
if not any((args.ordinary_predictions, args.five_view_predictions, args.reasoning_predictions)):
parser.error("provide at least one prediction file")
ordinary_truth, five_view_truth = load_truth(args.repo_id, args.cache_dir)
report: dict[str, Any] = {
"schema_version": "causalmedbench-score-v1.0",
"repo_id": args.repo_id,
}
strict = not args.allow_partial
if args.ordinary_predictions:
rows, coverage = merge_predictions(
ordinary_truth, prediction_index(args.ordinary_predictions), strict=strict
)
report["ordinary_submission"] = coverage
report["ordinary_task"] = {
"overall": binary_metrics(rows),
"by_modality": grouped_metrics(rows, "modality"),
"by_forgery_type": grouped_metrics(rows, "forgery_type"),
"by_generator": grouped_metrics(rows, "generator"),
}
if args.five_view_predictions:
rows, coverage = merge_predictions(
five_view_truth, prediction_index(args.five_view_predictions), strict=strict
)
report["five_view_submission"] = coverage
report["five_view"] = five_view_metrics(rows)
if args.reasoning_predictions:
reasoning_truth = [row for row in five_view_truth if row.get("is_reasoning_subset")]
rows, coverage = merge_predictions(
reasoning_truth, prediction_index(args.reasoning_predictions), strict=strict
)
report["reasoning_submission"] = coverage
report["explanation_alignment"] = reasoning_metrics(rows)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(json.dumps(report, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()