File size: 12,494 Bytes
1eecc00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
"""Family #12 Step 1B-3: Head-to-head 5-Suite Public OOD Benchmark evaluating Tamarillo tiers
against ALL 6 top Hugging Face AI-image forensics incumbents on identical frozen images:
  - umm-maybe/AI-image-detector                          (65.2K dl/mo, 86M Swin-Base, NO ONNX)
  - buildborderless/CommunityForensics-DeepfakeDet-ViT   (23.6K dl/mo, 21.8M ViT-Small 384px, timm)
  - Ateeqq/ai-vs-human-image-detector                    (12.1K dl/mo, 92.9M SigLIP, NO ONNX)
  - Organika/sdxl-detector                               (8.6K dl/mo, 86.8M Swin-Base, CC-BY-NC-3.0)
  - haywoodsloan/ai-image-detector-deploy                (5.0K dl/mo, 195.2M SwinV2, NO ONNX)
  - abacusai/Smaug-AI-Image-Detector                     (5.7K dl/mo, 438.8M, NO ONNX)
  - Plus Tamarillo FP32 & full-suite INT8 ONNX verification!

Reports per-suite EER, ROC-AUC, Balanced Acc @0.50, Fake Recall @0.50, Real-Photo FPR @0.50,
TPR@5%FPR, 4-Suite Strict Zero-Touch OOD Mean, 5-Suite Public Mean, and per-generator OpenFake breakdown.
"""

from __future__ import annotations

import argparse
import gc
import json
import os
import time
from collections import defaultdict
from pathlib import Path
from typing import Any

import numpy as np
import onnxruntime as ort
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from sklearn.metrics import roc_auc_score, roc_curve
from transformers import AutoImageProcessor, AutoModelForImageClassification

Image.MAX_IMAGE_PIXELS = None

SUITES_4Z = ["ood_openfake_core", "ood_openfake_reddit", "ood_synthbuster", "ood_social_recompressed"]
SUITES_ALL5 = SUITES_4Z + ["eval_commfor_comp"]


def compute_metrics(y_art: np.ndarray, p_art: np.ndarray, rows: list[dict[str, Any]]) -> dict[str, Any]:
    fpr, tpr, _ = roc_curve(y_art, p_art)
    fnr = 1.0 - tpr
    idx = int(np.nanargmin(np.abs(fnr - fpr)))
    eer = float(0.5 * (fpr[idx] + fnr[idx]))
    auc = float(roc_auc_score(y_art, p_art))
    t5 = float(tpr[np.where(fpr <= 0.05)[0][-1]]) if np.any(fpr <= 0.05) else 0.0
    t1 = float(tpr[np.where(fpr <= 0.01)[0][-1]]) if np.any(fpr <= 0.01) else 0.0

    pred_art = (p_art >= 0.50).astype(np.int32)
    fake_mask = y_art == 1
    real_mask = y_art == 0
    fake_rec = float(pred_art[fake_mask].mean()) if fake_mask.any() else 0.0
    real_fpr = float(pred_art[real_mask].mean()) if real_mask.any() else 0.0
    bal_acc = 0.5 * (fake_rec + (1.0 - real_fpr))

    out: dict[str, Any] = {
        "n": int(len(y_art)),
        "eer": round(eer, 5),
        "roc_auc": round(auc, 5),
        "tpr_at_5fpr": round(t5, 5),
        "tpr_at_1fpr": round(t1, 5),
        "bal_acc_050": round(bal_acc, 5),
        "fake_rec_050": round(fake_rec, 5),
        "real_fpr_050": round(real_fpr, 5),
    }

    # Per-generator fake recall / mean P(artificial) breakdown when model metadata exists
    by_mod: dict[str, list[float]] = defaultdict(list)
    for r, p, ya in zip(rows, p_art, y_art):
        if ya == 1:
            by_mod[str(r.get("model", "unknown"))].append(float(p))
    if len(by_mod) >= 2:
        real_scores = p_art[real_mask]
        gen_stats = {}
        for gm, scores in sorted(by_mod.items(), key=lambda x: -len(x[1]))[:15]:
            if len(scores) < 10:
                continue
            arr = np.asarray(scores, dtype=np.float32)
            # Compute per-generator AUC against all real photos in this suite
            y_comb = np.concatenate([np.zeros(len(real_scores)), np.ones(len(arr))])
            s_comb = np.concatenate([real_scores, arr])
            gen_stats[gm] = {
                "n": len(scores),
                "auc": round(float(roc_auc_score(y_comb, s_comb)), 4),
                "rec_050": round(float((arr >= 0.50).mean()), 4),
                "mean_p": round(float(arr.mean()), 4),
            }
        out["by_generator"] = gen_stats
    return out


def _detect_artificial_index(id2label: dict[Any, str]) -> int:
    for k, v in id2label.items():
        vl = str(v).strip().lower()
        if any(tok in vl for tok in ("artificial", "fake", "ai", "synthetic", "generated", "deepfake", "spoof")):
            return int(k)
    return 0


def score_hf_classifier(model_id_or_dir: str, paths: list[str], device: torch.device, bs: int = 32) -> tuple[np.ndarray, float]:
    proc = AutoImageProcessor.from_pretrained(model_id_or_dir)
    model = AutoModelForImageClassification.from_pretrained(model_id_or_dir).to(device).eval()
    params_m = sum(p.numel() for p in model.parameters()) / 1e6
    art_idx = _detect_artificial_index(model.config.id2label)
    print(f"    [hf] {model_id_or_dir}: {params_m:.2f}M | id2label={model.config.id2label} -> art_idx={art_idx}", flush=True)

    scores = []
    with torch.no_grad(), torch.amp.autocast("cuda", dtype=torch.bfloat16):
        for i in range(0, len(paths), bs):
            ims = [Image.open(p).convert("RGB") for p in paths[i : i + bs]]
            enc = proc(images=ims, return_tensors="pt").to(device)
            logits = model(**enc).logits.float()
            if logits.shape[-1] == 1:
                p = torch.sigmoid(logits[:, 0]).cpu().numpy()
            else:
                p = torch.softmax(logits, dim=-1)[:, art_idx].cpu().numpy()
            scores.append(p)
    del model
    gc.collect()
    torch.cuda.empty_cache()
    return np.concatenate(scores, axis=0), params_m


def score_commfor_vit(paths: list[str], bs: int = 32) -> tuple[np.ndarray, float]:
    """Score buildborderless/CommunityForensics-DeepfakeDet-ViT via its official ONNX artifact & official CLIP processor."""
    repo = "buildborderless/CommunityForensics-DeepfakeDet-ViT"
    proc = AutoImageProcessor.from_pretrained(repo)
    onnx_path = hf_hub_download(repo_id=repo, filename="onnx/model.onnx")
    opts = ort.SessionOptions()
    opts.intra_op_num_threads = 8
    sess = ort.InferenceSession(onnx_path, sess_options=opts, providers=["CPUExecutionProvider"])
    in_name = sess.get_inputs()[0].name
    print(f"    [commfor-onnx] {repo}: input={in_name} {sess.get_inputs()[0].shape} proc={type(proc).__name__}", flush=True)

    scores = []
    for i in range(0, len(paths), bs):
        ims = [Image.open(p).convert("RGB") for p in paths[i : i + bs]]
        x = proc(images=ims, return_tensors="np")["pixel_values"].astype(np.float32)
        out = sess.run(None, {in_name: x})[0]
        if out.ndim == 2 and out.shape[-1] == 1:
            p = 1.0 / (1.0 + np.exp(-out[:, 0]))
        elif out.ndim == 1:
            p = 1.0 / (1.0 + np.exp(-out))
        else:
            ex = np.exp(out - out.max(axis=-1, keepdims=True))
            # CommunityForensics convention: label 1 = Fake, 0 = Real
            p = (ex / ex.sum(axis=-1, keepdims=True))[:, 1]
        scores.append(p.astype(np.float32))
    return np.concatenate(scores, axis=0), 21.81


def score_tamarillo_onnx(model_dir: Path, onnx_file: str, paths: list[str], bs: int = 32) -> np.ndarray:
    """Full-suite ONNX evaluation (proves INT8 preserves actual OOD ROC-AUC/EER!)."""
    proc = AutoImageProcessor.from_pretrained(str(model_dir))
    opts = ort.SessionOptions()
    opts.intra_op_num_threads = 8
    sess = ort.InferenceSession(str(model_dir / "onnx" / onnx_file), sess_options=opts, providers=["CPUExecutionProvider"])
    in_name = sess.get_inputs()[0].name
    sz = 224
    if hasattr(proc, "size") and isinstance(proc.size, dict):
        sz = int(proc.size.get("height", proc.size.get("shortest_edge", 224)))

    scores = []
    for i in range(0, len(paths), bs):
        ims = [Image.open(p).convert("RGB") for p in paths[i : i + bs]]
        x = proc(images=ims, return_tensors="np")["pixel_values"].astype(np.float32)
        logits = sess.run(None, {in_name: x})[0]
        ex = np.exp(logits - logits.max(axis=-1, keepdims=True))
        p_art = (ex / ex.sum(axis=-1, keepdims=True))[:, 0]
        scores.append(p_art.astype(np.float32))
    return np.concatenate(scores, axis=0)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--ood-dir", type=str, required=True)
    ap.add_argument("--models", type=str, nargs="+", required=True, help="key=path_or_hf_id pairs")
    ap.add_argument("--int8-check-dirs", type=str, nargs="*", default=[], help="key=model_dir pairs for full-suite INT8 OOD eval")
    ap.add_argument("--out-json", type=str, required=True)
    args = ap.parse_args()

    os.environ["HF_HOME"] = "/tmp/hf"
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    ood_dir = Path(args.ood_dir)

    suites: dict[str, tuple[list[str], np.ndarray, list[dict[str, Any]]]] = {}
    for sn in SUITES_ALL5:
        jp = ood_dir / f"{sn}.jsonl"
        if not jp.exists():
            continue
        rows = [json.loads(l) for l in jp.read_text(encoding="utf-8").splitlines() if l.strip()]
        paths = [r["path"] for r in rows]
        y_art = np.array([1 if int(r["label"]) == 0 else 0 for r in rows], dtype=np.int32)
        suites[sn] = (paths, y_art, rows)
        print(f"[eval] Loaded {sn}: n={len(rows)} (art={int(y_art.sum())}, hum={int((1-y_art).sum())})", flush=True)

    results: dict[str, Any] = {"suites_4z": SUITES_4Z, "suites_all5": SUITES_ALL5, "models": {}}

    for spec in args.models:
        key, mpath = spec.split("=", 1)
        print(f"\n=== Evaluating {key} ({mpath}) ===", flush=True)
        t0 = time.time()
        try:
            suite_res = {}
            params_m = 0.0
            for sn, (paths, y_art, rows) in suites.items():
                if "CommunityForensics-DeepfakeDet-ViT" in mpath:
                    p_art, params_m = score_commfor_vit(paths, bs=32)
                else:
                    p_art, params_m = score_hf_classifier(mpath, paths, device, bs=32)
                # Sanity check polarity ONLY for CommunityForensics if needed? No — never flip dynamically;
                # log exact raw score!
                suite_res[sn] = compute_metrics(y_art, p_art, rows)
                print(
                    f"  {sn:24s} | EER={suite_res[sn]['eer']*100:5.2f}% | AUC={suite_res[sn]['roc_auc']:.4f} | "
                    f"Rec@0.5={suite_res[sn]['fake_rec_050']*100:5.1f}% | RealFPR@0.5={suite_res[sn]['real_fpr_050']*100:4.1f}%",
                    flush=True,
                )
            z4_eer = float(np.mean([suite_res[s]["eer"] for s in SUITES_4Z if s in suite_res]))
            z4_auc = float(np.mean([suite_res[s]["roc_auc"] for s in SUITES_4Z if s in suite_res]))
            m5_eer = float(np.mean([suite_res[s]["eer"] for s in SUITES_ALL5 if s in suite_res]))
            m5_auc = float(np.mean([suite_res[s]["roc_auc"] for s in SUITES_ALL5 if s in suite_res]))
            results["models"][key] = {
                "repo_or_path": mpath,
                "params_m": round(params_m, 2),
                "z4_mean_eer": round(z4_eer, 5),
                "z4_mean_auc": round(z4_auc, 5),
                "all5_mean_eer": round(m5_eer, 5),
                "all5_mean_auc": round(m5_auc, 5),
                "suites": suite_res,
                "elapsed_s": round(time.time() - t0, 1),
            }
            print(f"  ==> {key}: 4Z Mean EER={z4_eer*100:.2f}% AUC={z4_auc:.4f} | 5-Suite EER={m5_eer*100:.2f}% AUC={m5_auc:.4f}", flush=True)
        except Exception as e:
            print(f"  [ERROR] {key} failed: {e}", flush=True)
            results["models"][key] = {"repo_or_path": mpath, "error": str(e)}

    # Full-suite INT8 OOD evaluation on ood_openfake_core & ood_social_recompressed
    int8_eval = {}
    for spec in args.int8_check_dirs:
        key, mdir_s = spec.split("=", 1)
        mdir = Path(mdir_s)
        q8_p = mdir / "onnx" / "model_quantized.onnx"
        if not q8_p.exists():
            continue
        print(f"\n=== Full-Suite INT8 ONNX Eval: {key} ===", flush=True)
        sub = {}
        for sn in ("ood_openfake_core", "ood_social_recompressed"):
            if sn not in suites:
                continue
            paths, y_art, rows = suites[sn]
            p_art = score_tamarillo_onnx(mdir, "model_quantized.onnx", paths, bs=32)
            sub[sn] = compute_metrics(y_art, p_art, rows)
            print(f"  INT8 {sn:24s} | EER={sub[sn]['eer']*100:5.2f}% | AUC={sub[sn]['roc_auc']:.4f}", flush=True)
        int8_eval[key] = sub
    results["int8_full_ood_eval"] = int8_eval

    Path(args.out_json).write_text(json.dumps(results, indent=2), encoding="utf-8")
    print(f"\n[DONE] Saved full benchmark -> {args.out_json}", flush=True)


if __name__ == "__main__":
    main()