"""Protocol runners. Each returns a dict of metrics; driver script prints them.""" from __future__ import annotations import json from pathlib import Path from typing import Dict, List import numpy as np import torch from torch.utils.data import DataLoader from tqdm import tqdm from .metrics import compute_detection_metrics, compute_fairness_metrics @torch.no_grad() def _collect_scores(model, loader, device) -> Dict[str, list]: model.eval().to(device) scores, labels, metas = [], [], [] for batch in tqdm(loader, desc="scoring"): if batch is None: continue for k in ("video", "audio", "label"): if k in batch and torch.is_tensor(batch[k]): batch[k] = batch[k].to(device, non_blocking=True) s = model.score(batch).cpu().numpy() scores.extend(s.tolist()) labels.extend(batch["label"].cpu().numpy().tolist()) if "meta" in batch: metas.extend(batch["meta"]) return {"scores": scores, "labels": labels, "metas": metas} def run_protocol_1(model, dm, device, out_dir: Path) -> Dict: """Protocol 1: zero-shot robustness on the balanced test set.""" out_dir.mkdir(parents=True, exist_ok=True) dm.setup("test") res = _collect_scores(model, dm.test_dataloader(), device) m = compute_detection_metrics(res["labels"], res["scores"]) (out_dir / "protocol1.json").write_text(json.dumps(m, indent=2)) return m def run_protocol_2(model, dm, device, out_dir: Path) -> Dict: """Protocol 2: fairness across demographic groups on the balanced test set.""" out_dir.mkdir(parents=True, exist_ok=True) dm.setup("test") res = _collect_scores(model, dm.test_dataloader(), device) labels = res["labels"]; scores = res["scores"]; metas = res["metas"] # run separately on gender, race4, age_group out = {"overall": compute_detection_metrics(labels, scores)} for key in ("gender", "race4", "age_group"): groups = [m.get(key, "") for m in metas] out[key] = compute_fairness_metrics(labels, scores, groups) (out_dir / "protocol2.json").write_text(json.dumps(out, indent=2)) return out def run_protocol_3(model, dm, device, out_dir: Path, mode: str = "LOGO") -> Dict: """Protocol 3: cross-generator generalization. LOGO: hold one generator out at *training* time, evaluate on it. (Requires retraining; here we only *evaluate* a pretrained model on per-generator subsets so you can decide whether to retrain.) LOGI: train on one generator only. Also retraining-required. This runner reports per-generator detection AUC on the test set. """ out_dir.mkdir(parents=True, exist_ok=True) dm.setup("test") res = _collect_scores(model, dm.test_dataloader(), device) labels = np.asarray(res["labels"]); scores = np.asarray(res["scores"]) metas = res["metas"] gens = np.asarray([m.get("generator", "") for m in metas]) out = {} for g in sorted(set(gens.tolist())): if g == "": continue mask = (gens == g) | (labels == 0) # real vs this-generator-fake out[g] = compute_detection_metrics(labels[mask], scores[mask]) (out_dir / f"protocol3_{mode}.json").write_text(json.dumps(out, indent=2)) return out def run_protocol_4(model, dm, device, out_dir: Path) -> Dict: """Protocol 4: identity-paired analysis on HDTF subsets A/B/C.""" out_dir.mkdir(parents=True, exist_ok=True) summary = {} for subset in ("A", "B", "C"): try: loader = dm.hdtf_loader(subset, mode="pair") except Exception as e: summary[subset] = {"error": str(e)} continue if len(loader.dataset) == 0: summary[subset] = {"error": "empty subset csv"} continue res = _collect_scores(model, loader, device) summary[subset] = compute_detection_metrics(res["labels"], res["scores"]) (out_dir / "protocol4.json").write_text(json.dumps(summary, indent=2)) return summary