File size: 4,042 Bytes
1ef5ba8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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