Spaces:
Sleeping
Sleeping
Update SynthScope Space from the GitHub repository
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- LEADERBOARD.md+1-1
- LICENSES.md+7
- benchmark/bench_eval.py+1-2
- benchmark/bench_eval_video.py+261-41
- benchmark/evaluate.py+2
- benchmark/seed_reference_results.py+2-2
- benchmark/submissions/co_spy_official.json+24-24
- conf/dataset/image/cure_train.yamlAdded+18
- conf/model/image/aide.yaml+11-7
- conf/model/image/cure.yaml+8
- conf/model/image/probe.yamlAdded+20
- conf/model/image/probe_resnet.yamlAdded+18
- conf/model/video/waverep.yamlAdded+18
- conf/trainer/image/aide.yaml+22-4
- conf/trainer/image/cure.yamlAdded+30
- dataset.py+131
- docs/ADD_DETECTOR.md+6-2
- docs/CAPABILITIES.md+8-4
- experiments/image/aide.sh+43-11
- experiments/image/cure.shAdded+97
- interface/README.md+6-3
- interface/backend/build_repro_full.py+54-14
- interface/backend/engine.py+78-5
- interface/backend/hf_compat.pyAdded+67
- interface/backend/media.py+42-4
- interface/backend/registry.py+105-3
- interface/backend/repro_full.json+318-40
- interface/scripts/collect_checkpoints.py+25-4
- interface/scripts/verify_model.py+3-2
- interface/static/index.html+1-1
- models/image/aide/README.md+28-4
- models/image/aide/official_arch.py+7-2
- models/image/co_spy/README.md+2
- models/image/cure/README.md+188-15
- models/image/cure/cure.py+89-7
- models/image/cure/preprocess.py+10-3
- models/image/cure/subspace.pyAdded+100
- models/image/cure/train_augment.pyAdded+96
- models/image/cure/train_stages.pyAdded+369
- models/image/effort/effort.py+4-1
- models/image/pgc/pgc.py+5-2
- models/image/probe/README.mdAdded+283
- models/image/probe/__init__.pyAdded
- models/image/probe/official/__init__.pyAdded
- models/image/probe/official/dino_classifier.pyAdded+77
- models/image/probe/official/resnet50.pyAdded+256
- models/image/probe/preprocess.pyAdded+98
- models/image/probe/probe.pyAdded+92
- models/video/waverep/README.mdAdded+266
- models/video/waverep/__init__.pyAdded
10 unmodified lines1112131415161710 unmodified lines| Rank | Method | Eval | Acc | **mAP** | AP | AUROC | Verified | Notes || --- | --- | --- | --- | --- | --- | --- | --- | --- || 1 | FatFormer | official-weights | 98.39 | 99.70 | — | 99.57 | ✓ | ForenSynths-8; official 4-class ProGAN weights (the served fat_former.pth) || 2 | CO-SPY (official weights) | official-weights | 94.64 | 98.50 | — | 98.80 | ✓ | ForenSynths-8; official CO-SPY ProGAN checkpoint in the vendored official architecture (not the served co_spy.pth) || 3 | SAFE | from-scratch | 95.11 | 97.79 | — | 97.86 | ✓ | ForenSynths-8; trained in SynthScope on ProGAN, 40-epoch crop recipe (safe_full_v2/model_38, the served safe.pth) || 4 | UnivFD / CLIP | frozen-probe | 88.28 | 97.22 | — | 97.11 | ✓ | ForenSynths-8; frozen CLIP ViT-L/14 + linear head trained in SynthScope on ProGAN (the served clip.pth) || 5 | AIDE | official-weights | 88.38 | 96.03 | — | 95.60 | ✓ | ForenSynths-8; official ProGAN weights progan_train.pth, vendored official eval (native-resolution 5-view DCT); the served aide.pth is the SD-v1.4 release |10 unmodified lines1112131415161710 unmodified lines| Rank | Method | Eval | Acc | **mAP** | AP | AUROC | Verified | Notes || --- | --- | --- | --- | --- | --- | --- | --- | --- || 1 | FatFormer | official-weights | 98.39 | 99.70 | — | 99.57 | ✓ | ForenSynths-8; official 4-class ProGAN weights (the served fat_former.pth) || 2 | CO-SPY (official weights) | official-weights | 95.12 | 98.85 | — | 99.03 | ✓ | ForenSynths-8, full test sets; official CO-SPY ProGAN checkpoint in the vendored official architecture (not the served co_spy.pth) || 3 | SAFE | from-scratch | 95.11 | 97.79 | — | 97.86 | ✓ | ForenSynths-8; trained in SynthScope on ProGAN, 40-epoch crop recipe (safe_full_v2/model_38, the served safe.pth) || 4 | UnivFD / CLIP | frozen-probe | 88.28 | 97.22 | — | 97.11 | ✓ | ForenSynths-8; frozen CLIP ViT-L/14 + linear head trained in SynthScope on ProGAN (the served clip.pth) || 5 | AIDE | official-weights | 88.38 | 96.03 | — | 95.60 | ✓ | ForenSynths-8; official ProGAN weights progan_train.pth, vendored official eval (native-resolution 5-view DCT); the served aide.pth is the SD-v1.4 release |
14 unmodified lines15161718192018 unmodified lines3940414243442 unmodified lines4748495051524 unmodified lines57585960616214 unmodified lines> non-commercial-only**, and some weights are **gated** (require accepting an upstream license).> The table below is a starting point — verify each entry against its source. (`⚠ verify` = please> confirm and fill in from the official repo before relying on it.)## Detectors18 unmodified lines| `bfree` | B-Free (CVPR'25) | grip-unina/B-Free | GRIP-UNINA license: informational and **nonprofit use only** (notices kept); `official_arch.py` vendors `code/networks/wrapper5crops.py` — see its header | **official** checkpoint (`BFREE_dino2reg4/model_epoch_best.pth` from grip.unina.it, loaded as `bfree.pth`) | GRIP-UNINA license (nonprofit use only) || `mirror` | MIRROR (NeurIPS'26) | handsome-rich/MIRROR | **unclear**: the README badge says MIT, but the repo has no LICENSE file (the badge's link 404s); `official_arch.py` vendors `models/mirror.py`, and `preprocess.py` vendors the eval transform of `data/datasets.py` (see the file headers) | **official** phase-2 checkpoint (`checkpoint-h-cur.pth`, authors' Google Drive, loaded as `mirror.pth`; it contains the DINOv3 ViT-H+ weights) | **unclear** (no licence stated); not redistributed: not in the model zoo or on the Space || `vina`, `vina_video` | VINA (arXiv 2605.21977) | mgiant/VINA | **unclear**: the repo (commit 225d331) has no LICENSE file and the README states no licence; `official_arch.py` vendors the `DINOv3` class of `models/DINOv3.py` (see its header) | **official** checkpoint (`VINA_DINOv3-L_140k+DDA.pth` from HF `mgiant/VINA_checkpoints` @ f258349, loaded as `vina.pth`; it contains the DINOv3 ViT-L/16 weights) | **unclear** (no licence tag on the HF repo, empty model card); not redistributed: not in the model zoo or on the Space || `moejepa` | MoE-JEPA (ECCV'26 W) | ALCOR-Lab-DIAG/MoE-JEPA | MIT; `official_arch.py` vendors the blocks of `model/model.py` — see its header | **official** checkpoint (`moejepa_sidset.safetensors`, v1.0 GitHub release, loaded as `moejepa.safetensors`) | MIT || `effort`, `effort_chameleon` | Effort (ICML'25) | YZY-stack/Effort-AIGI-Detection | CC BY-NC 4.0 (README badge); `official_arch.py` vendors the SVD-residual layers of `DeepfakeBench/training/detectors/effort_detector.py` — see its header | **official** checkpoints (`effort_clip_L14_trainOn_{sdv14,chameleon}.pth` from the authors' Google Drive, loaded as `<key>.pth`); the SynthScope-trained ProGAN model (config `image/effort_ufd`) is not a served key and stays on the shared filesystem | CC BY-NC 4.0 (non-commercial) || `dinov2` | DINOv2 probe | facebookresearch/dinov2 | Apache-2.0 (verify) | DINOv2 backbone | Apache-2.0 (verify) |2 unmodified lines| `d3` | D3 (ICCV'25) | Zig-HS/D3 | MIT (repo `LICENSE`) | training-free (no weights) | n/a || `split` | SPLIT (ECCV'26) | mldljyh/SPLIT | MIT (LICENSE added 2026-11-02); no code copied: `models/video/split/split.py` is SynthScope's own implementation of the paper's equations | training-free (no weights) | n/a || `restrav` | ReStraV | ⚠ verify (official repo) | ⚠ verify | — (SynthScope-trained) | n/a (backbone: see below) || `stall` | STALL (CVPR'26) | OmerBenHayun/STALL | CC BY-NC 4.0 (`LICENSE.txt`) | training-free; needs the DINOv3 backbone (and ships the VATEX calibration `.npz`) | DINOv3 License (gated download) |## Backbones / foundation models (downloaded on first use)4 unmodified lines| OpenAI CLIP ViT-L/14@336 (HF `openai/clip-vit-large-patch14-336`) | `omniaid`, `omniaid_v1`, `omniaid_genimage` | MIT || OpenCLIP (ConvNeXt-XXL, LAION) | `aide` | code MIT; weights per LAION / model card (verify) || DINOv2 (ViT-L/14, ViT-S/14) | `dinov2`, `adapted_dino`, `restrav`, `dda` | Apache-2.0 (verify) || DINOv3 (ViT-L/16) | `dinov3`, `stall`, `vina` / `vina_video` (its weights are inside the VINA checkpoint; the gated HF `facebook/dinov3-vitl16-pretrain-lvd1689m` is only needed for training) | **gated** download — DINOv3 License (use and redistribution allowed with the license and attribution; trade-control restrictions) || DINOv3 ViT-H+/16 (HF `facebook/dinov3-vith16plus-pretrain-lvd1689m`) | `mirror` (its weights are inside the MIRROR checkpoint; the gated download is only needed for training) | **gated** - DINOv3 License || SigLIP | `co_spy` | Apache-2.0 (verify) |14 unmodified lines15161718192021222318 unmodified lines424344454647482 unmodified lines515253545556574 unmodified lines626364656667686914 unmodified lines> non-commercial-only**, and some weights are **gated** (require accepting an upstream license).> The table below is a starting point — verify each entry against its source. (`⚠ verify` = please> confirm and fill in from the official repo before relying on it.)>> `synthscope push` enforces this for the rows marked **unclear** / **not redistributed** below: the keys in> `NEVER_REDISTRIBUTE` (`synthscope/hub.py`) are refused even with `--include-official`; update that constant together with the table when a licence is clarified.## Detectors18 unmodified lines| `bfree` | B-Free (CVPR'25) | grip-unina/B-Free | GRIP-UNINA license: informational and **nonprofit use only** (notices kept); `official_arch.py` vendors `code/networks/wrapper5crops.py` — see its header | **official** checkpoint (`BFREE_dino2reg4/model_epoch_best.pth` from grip.unina.it, loaded as `bfree.pth`) | GRIP-UNINA license (nonprofit use only) || `mirror` | MIRROR (NeurIPS'26) | handsome-rich/MIRROR | **unclear**: the README badge says MIT, but the repo has no LICENSE file (the badge's link 404s); `official_arch.py` vendors `models/mirror.py`, and `preprocess.py` vendors the eval transform of `data/datasets.py` (see the file headers) | **official** phase-2 checkpoint (`checkpoint-h-cur.pth`, authors' Google Drive, loaded as `mirror.pth`; it contains the DINOv3 ViT-H+ weights) | **unclear** (no licence stated); not redistributed: not in the model zoo or on the Space || `vina`, `vina_video` | VINA (arXiv 2605.21977) | mgiant/VINA | **unclear**: the repo (commit 225d331) has no LICENSE file and the README states no licence; `official_arch.py` vendors the `DINOv3` class of `models/DINOv3.py` (see its header) | **official** checkpoint (`VINA_DINOv3-L_140k+DDA.pth` from HF `mgiant/VINA_checkpoints` @ f258349, loaded as `vina.pth`; it contains the DINOv3 ViT-L/16 weights) | **unclear** (no licence tag on the HF repo, empty model card); not redistributed: not in the model zoo or on the Space || `probe`, `probe_resnet` | PROBE (ICML'26) | Amamiya-C/PROBE-AIGI-Detection | **unclear**: the repo (commit b145f71) has no LICENSE file, GitHub reports no licence and the README states none; `official/dino_classifier.py` and `official/resnet50.py` vendor `Detector/model/*.py`, and `preprocess.py` vendors `pad_image` and the sliding-patch step of `Detector/util.py` / `evaluate_dino.py` (see the file headers) | **official** checkpoints (`DINOv2_best_model_step_34999.pth` and `ResNet50_best_model_step_19343.pth` from ModelScope `shuinishaojiu/PROBE-AIGI-Detection`, loaded as `probe.pth` / `probe_resnet.pth`; the DINOv2 one contains the DINOv2-with-registers ViT-L/14 weights) | **unclear** (the ModelScope licence field is empty); not redistributed: not in the model zoo or on the Space || `moejepa` | MoE-JEPA (ECCV'26 W) | ALCOR-Lab-DIAG/MoE-JEPA | MIT; `official_arch.py` vendors the blocks of `model/model.py` — see its header | **official** checkpoint (`moejepa_sidset.safetensors`, v1.0 GitHub release, loaded as `moejepa.safetensors`) | MIT || `effort`, `effort_chameleon` | Effort (ICML'25) | YZY-stack/Effort-AIGI-Detection | CC BY-NC 4.0 (README badge); `official_arch.py` vendors the SVD-residual layers of `DeepfakeBench/training/detectors/effort_detector.py` — see its header | **official** checkpoints (`effort_clip_L14_trainOn_{sdv14,chameleon}.pth` from the authors' Google Drive, loaded as `<key>.pth`); the SynthScope-trained ProGAN model (config `image/effort_ufd`) is not a served key and stays on the shared filesystem | CC BY-NC 4.0 (non-commercial) || `dinov2` | DINOv2 probe | facebookresearch/dinov2 | Apache-2.0 (verify) | DINOv2 backbone | Apache-2.0 (verify) |2 unmodified lines| `d3` | D3 (ICCV'25) | Zig-HS/D3 | MIT (repo `LICENSE`) | training-free (no weights) | n/a || `split` | SPLIT (ECCV'26) | mldljyh/SPLIT | MIT (LICENSE added 2026-11-02); no code copied: `models/video/split/split.py` is SynthScope's own implementation of the paper's equations | training-free (no weights) | n/a || `restrav` | ReStraV | ⚠ verify (official repo) | ⚠ verify | — (SynthScope-trained) | n/a (backbone: see below) || `waverep`, `waverep_g4` | WaveRep (NeurIPS'25) | grip-unina/WaveRep-SyntheticVideoDetection | GRIP-UNINA license (`LICENSE.md`): informational and **nonprofit use only** (notices kept, authors credited); `official_utils.py` vendors `demo/utils.py` — see its header | **official** checkpoints (`weights_dinov2_G1.ckpt` / `weights_dinov2_G4.ckpt` from grip.unina.it, md5 as the demo README, loaded as `waverep.pth` / `waverep_g4.pth`; they contain the DINOv2 ViT-B/14 + registers weights) | GRIP-UNINA license (nonprofit use only); not in the model zoo; not on the Space (pending user approval) || `stall` | STALL (CVPR'26) | OmerBenHayun/STALL | CC BY-NC 4.0 (`LICENSE.txt`) | training-free; needs the DINOv3 backbone (and ships the VATEX calibration `.npz`) | DINOv3 License (gated download) |## Backbones / foundation models (downloaded on first use)4 unmodified lines| OpenAI CLIP ViT-L/14@336 (HF `openai/clip-vit-large-patch14-336`) | `omniaid`, `omniaid_v1`, `omniaid_genimage` | MIT || OpenCLIP (ConvNeXt-XXL, LAION) | `aide` | code MIT; weights per LAION / model card (verify) || DINOv2 (ViT-L/14, ViT-S/14) | `dinov2`, `adapted_dino`, `restrav`, `dda` | Apache-2.0 (verify) || DINOv2 with registers ViT-B/14 (timm `vit_base_patch14_reg4_dinov2.lvd142m`) | `bfree`, `waverep` / `waverep_g4` (their weights are inside the official checkpoints; the timm download is only needed for training) | Apache-2.0 (timm / DINOv2 model card) || DINOv2 with registers ViT-L/14 (HF `facebook/dinov2-with-registers-large`) | `probe` (its weights are inside the PROBE checkpoint; the HF download is only needed for training) | Apache-2.0 (HF model card) || DINOv3 (ViT-L/16) | `dinov3`, `stall`, `vina` / `vina_video` (its weights are inside the VINA checkpoint; the gated HF `facebook/dinov3-vitl16-pretrain-lvd1689m` is only needed for training) | **gated** download — DINOv3 License (use and redistribution allowed with the license and attribution; trade-control restrictions) || DINOv3 ViT-H+/16 (HF `facebook/dinov3-vith16plus-pretrain-lvd1689m`) | `mirror` (its weights are inside the MIRROR checkpoint; the gated download is only needed for training) | **gated** - DINOv3 License || SigLIP | `co_spy` | Apache-2.0 (verify) |
190 unmodified lines191192193194195196197198190 unmodified linestf = transform if transform is not None else spec.transform# Native-resolution specs (SPAI any-res) produce variable-size tensors that cannot be stacked,# so they MUST be scored one image at a time.if getattr(spec, "native_res", False):bs = 1probs, kept = [], []for i in range(0, len(paths), bs):batch = []190 unmodified lines191192193194195196197190 unmodified linestf = transform if transform is not None else spec.transform# Native-resolution specs (SPAI any-res) produce variable-size tensors that cannot be stacked,# so they MUST be scored one image at a time.bs = spec.eval_batch_size(bs)probs, kept = [], []for i in range(0, len(paths), bs):batch = []
12349 unmodified lines1415161718193 unmodified lines23242526272829301 unmodified line32333435363752 unmodified lines909192939495969798991001011024 unmodified lines1071081091101111121131141151161171181191201211221235 unmodified lines1291301311321331341355 unmodified lines1411421431441451461477 unmodified lines1551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042056 unmodified lines212213214215216217218219220221222"""Unified VIDEO benchmark eval for SynthScope video detectors (d3, split, restrav, stall, vina_video).Scores each video through the SAME verified synthscope engine path the web app uses(engine.predict_video_clip -> native clip pipeline + per-model norm + fake-prob), computes9 unmodified linesEach generator reports AP with fake as the positive class (``ap``) and with real as the positive class(``ap_real``, what D3's official eval.py computes: ``average_precision_score(1 - y_true, std)``).Benchmark layouts:genvideo <data>/Fake/<gen>/*.mp4 + <data>/Real/*.mp4 (shared real pool) [GenVideo-Val]fakeonly <data>/<gen>/*.mp4 (all fake) + --reals DIR of real videos [EvalCrafter]3 unmodified linesimport argparseimport datetimeimport jsonimport sysfrom pathlib import Pathimport numpy as np1 unmodified linesys.path.insert(0, str(Path(__file__).resolve().parents[1] / "interface"))from backend.engine import get_engine # noqa: E402from backend.registry import get_spec # noqa: E402from datasets_util import ensure_dataset # noqa: E40252 unmodified linesreturn outdef metrics(fake_probs: torch.Tensor, labels: torch.Tensor):from torchmetrics.functional import auroc, average_precisionif labels.unique().numel() < 2:return Noneap = float(average_precision(fake_probs, labels, task="binary")) * 100ap_real = float(average_precision(1 - fake_probs, 1 - labels, task="binary")) * 100au = float(auroc(fake_probs, labels, task="binary")) * 100preds = (fake_probs >= 0.5).int()real_acc = float((preds[labels == 0] == 0).float().mean()) * 100fake_acc = float((preds[labels == 1] == 1).float().mean()) * 1004 unmodified linesFPRS = (0.001, 0.01, 0.05)@torch.no_grad()def score_videos(engine, spec, paths, raw=False):"""P(fake) per video; with ``raw`` (training-free detectors with a ``score``), the raw score oriented so that highermeans generated instead, which keeps the order at the extremes where probabilities saturate."""probs = []for p in paths:try:probs.append(engine.video_raw_score(spec, str(p)) if raw else engine.predict_video_clip(spec, str(p))["fake_probability"])except Exception as e: # noqa: BLE001print(f" bad video {p.name}: {e}")return probsdef fake_recall_at_fpr(real_scores, fake_scores):5 unmodified linesdef main(argv=None) -> int:ap = argparse.ArgumentParser()ap.add_argument("-m", "--model", required=True, choices=["d3", "split", "restrav", "stall", "vina_video"])ap.add_argument("--benchmark", choices=["genvideo", "fakeonly", "pergen"], help="layout (not needed with --dataset)")ap.add_argument("--data", help="benchmark root (not needed with --dataset)")ap.add_argument("--dataset", help="a supported video dataset (genvideo, videophy, vidprom, evalcrafter, ...): downloads "5 unmodified linesap.add_argument("--limit", type=int, default=None, help="cap videos per class per generator")ap.add_argument("--tag", help="run tag (output filename + log); default <model>_<dataset>")ap.add_argument("--out", default=None)args = ap.parse_args(argv)if args.dataset:droot = ensure_dataset(args.dataset, "video", args.root, download=not args.no_download)7 unmodified linesif not (args.data and args.benchmark and args.tag):raise SystemExit("pass --dataset, or --data, --benchmark and --tag")engine = get_engine()spec = get_spec(args.model)engine._get_model(spec)root = Path(args.data)select = set(args.select.split(",")) if args.select else Nonegens = discover(args.benchmark, root, Path(args.reals) if args.reals else None, select)if not gens:print(f"No generators with real+fake videos under {root} ({args.benchmark})")return 1print(f"=== bench_eval_video {args.tag} | {args.model} | {args.benchmark} | {len(gens)} gens "f"| device={engine.device} ===", flush=True)per_gen, agg = {}, {"ap": [], "ap_real": [], "auroc": [], "acc": []}pooled_fake_raw = [] # every generator's fakes, for the pooled ("Overall") recallraw = hasattr(engine._get_model(spec), "score") # training-free detectors: also fake recall at fixed FPR# score the shared real pool once if it is identical across generatorsreal_cache = {}for name, reals, fakes in gens:if args.limit:reals, fakes = reals[:args.limit], fakes[:args.limit]rk = (id(reals) if args.limit is None else None)print(f" {name}: {len(reals)} real + {len(fakes)} fake ...", flush=True)key = (len(reals), reals[0].name, reals[-1].name) # the same pool hard-linked per generator is scored onceif key in real_cache:rp = real_cache[key]else:rp = score_videos(engine, spec, reals)real_cache[key] = rpfp = score_videos(engine, spec, fakes)if raw:rraw = real_cache.setdefault(("raw",) + key, None) or score_videos(engine, spec, reals, raw=True)real_cache[("raw",) + key] = rrawfraw = score_videos(engine, spec, fakes, raw=True)pooled_fake_raw += frawprobs = torch.tensor(rp + fp)labels = torch.tensor([0] * len(rp) + [1] * len(fp))m = metrics(probs, labels)if m is None:print(f" skip {name}: one class"); continueif raw:m["fake_recall_at_fpr"] = fake_recall_at_fpr(rraw, fraw)per_gen[name] = mfor k in agg:agg[k].append(m[k])print(f" {name}: acc={m['acc']} AP={m['ap']} AP_real={m['ap_real']} AUROC={m['auroc']}", flush=True)if not per_gen:print("No generator produced metrics."); return 16 unmodified linesmeans["fake_recall_at_fpr"] = {k: mean([g["fake_recall_at_fpr"][k] for g in per_gen.values()])for k in next(iter(per_gen.values()))["fake_recall_at_fpr"]}# Overall: all fakes against the real pool(s) (each distinct pool once), as the SPLIT paper's "Overall" rowpooled_real_raw = [s for k, v in real_cache.items() if k[0] == "raw" for s in v]means["overall_fake_recall_at_fpr"] = fake_recall_at_fpr(pooled_real_raw, pooled_fake_raw)result = {"tag": args.tag, "model": args.model, "ckpt": "registry-default","benchmark": f"video:{args.benchmark}", "data_root": str(root),"n_generators": len(per_gen), "means": means, "per_generator": per_gen,"date": datetime.datetime.now().isoformat(timespec="seconds"),"synthscope_version": "video"}out = Path(args.out) if args.out else (REPRO / "bench_results" / f"{args.tag}.json")123459 unmodified lines15161718192021222324252627282930313 unmodified lines35363738394041424344451 unmodified line4748495051525352 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271284 unmodified lines1331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802815 unmodified lines2872882892902912922932945 unmodified lines3003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333347 unmodified lines3423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224236 unmodified lines430431432433434435436437438439440441442"""Unified VIDEO benchmark eval for SynthScope video detectors (d3, split, restrav, stall, vina_video, waverep,waverep_g4).Scores each video through the SAME verified synthscope engine path the web app uses(engine.predict_video_clip -> native clip pipeline + per-model norm + fake-prob), computes9 unmodified linesEach generator reports AP with fake as the positive class (``ap``) and with real as the positive class(``ap_real``, what D3's official eval.py computes: ``average_precision_score(1 - y_true, std)``).Resumable / parallel scoring (long benchmarks): ``--cache-dir DIR`` stores every scored video (P(fake), the raw logitwhen the detector reports one, or the decode error) in DIR/scores.*.jsonl, keyed by the last three path components, and reuses it on the next run; ``--shard K/N`` scores only the K-th of N slices of the unique videos and stops(run the N slices on N GPUs, then one final run without ``--shard`` reads every slice and writes the metrics).A detector that reports a raw logit (WaveRep) is ranked by it (AP / AUROC), because the 6-dp rounded P(fake) tiesvery confident videos at 0 / 1; accuracy still thresholds P(fake) at 0.5. Videos that cannot be decoded(backend.media.VideoDecodeError) are counted per generator (failed_real / failed_fake) and in the result JSON(failed_to_decode: decode failures only, cached); any other error (OOM, I/O) is counted in failed_other, never cachedand retried; both kinds are left out of the metrics. The cache directory carries cache_meta.json (model key, sha256 ofthe resolved checkpoint, frame count / sampler / transform, format version): a run whose setup differs is refused.The result JSON also records limit, reals, ckpt_sha256 and cache_dir.Benchmark layouts:genvideo <data>/Fake/<gen>/*.mp4 + <data>/Real/*.mp4 (shared real pool) [GenVideo-Val]fakeonly <data>/<gen>/*.mp4 (all fake) + --reals DIR of real videos [EvalCrafter]3 unmodified linesimport argparseimport datetimeimport hashlibimport jsonimport osimport sysimport timefrom pathlib import Pathimport numpy as np1 unmodified linesys.path.insert(0, str(Path(__file__).resolve().parents[1] / "interface"))from backend.engine import get_engine # noqa: E402from backend.media import VideoDecodeError # noqa: E402from backend.registry import get_spec # noqa: E402from datasets_util import ensure_dataset # noqa: E40252 unmodified linesreturn outdef metrics(fake_probs: torch.Tensor, labels: torch.Tensor, rank: np.ndarray | None = None):"""acc@0.5 on ``fake_probs``; AP / AP_real / AUROC on ``fake_probs`` (torchmetrics, unchanged) or, when ``rank`` (afloat64 raw score, higher = more likely fake, e.g. the logit) is given, on ``rank`` with scikit-learn, so thatsaturated probabilities do not tie."""from torchmetrics.functional import auroc, average_precisionif labels.unique().numel() < 2:return Noneif rank is None:ap = float(average_precision(fake_probs, labels, task="binary")) * 100ap_real = float(average_precision(1 - fake_probs, 1 - labels, task="binary")) * 100au = float(auroc(fake_probs, labels, task="binary")) * 100else:from sklearn.metrics import average_precision_score, roc_auc_scorey = labels.numpy()ap = float(average_precision_score(y, rank)) * 100ap_real = float(average_precision_score(1 - y, -rank)) * 100au = float(roc_auc_score(y, rank)) * 100preds = (fake_probs >= 0.5).int()real_acc = float((preds[labels == 0] == 0).float().mean()) * 100fake_acc = float((preds[labels == 1] == 1).float().mean()) * 1004 unmodified linesFPRS = (0.001, 0.01, 0.05)CACHE_FORMAT = 2 # 2: error records carry "kind" ("decode" is cached, anything else is retried)def _sha256(path: Path) -> str:h = hashlib.sha256()with path.open("rb") as f:for chunk in iter(lambda: f.read(1 << 24), b""):h.update(chunk)return h.hexdigest()def cache_meta(engine, spec) -> dict:"""What a score cache is valid for: the detector key, the sha256 of the resolved checkpoint, and every spec field thatchanges a video's score (frame count, sampler, preprocessing)."""ck = engine.checkpoint_path(spec)return {"model": spec.key,"ckpt_sha256": _sha256(Path(ck).resolve()) if ck is not None else None,"spec": {"num_frames": spec.num_frames, "video_sampler": spec.video_sampler,"transform": repr(spec.transform),**{k: repr(getattr(spec, k, None)) for k in ("fps", "frame_size", "window_center", "video_norm")}},"cache_format": CACHE_FORMAT}class ScoreCache:"""Per-video score store shared by shards and re-runs: DIR/scores.<tag>.jsonl, one JSON per line, keyed by the lastthree components of the video path. All ``scores.*.jsonl`` in DIR are read; only ``scores.<tag>`` is written (createdon the first write). DIR/cache_meta.json records what the scores are valid for (``cache_meta``): the first use writesit, a later use with a different model / checkpoint / spec / format is refused."""def __init__(self, cache_dir, tag: str, meta: dict | None = None, write_meta=True):self.rec, self.only, self.tag = {}, False, tagself.dir = Path(cache_dir)self.dir.mkdir(parents=True, exist_ok=True)if meta is not None:self._check_meta(meta, write_meta)for f in sorted(self.dir.glob("scores.*.jsonl")):for line in f.read_text().splitlines():if line.strip():r = json.loads(line)self.rec[r["k"]] = rself._out = Nonedef _check_meta(self, meta: dict, write: bool):mp = self.dir / "cache_meta.json"if not mp.exists() and write:tmp = mp.with_name(f".cache_meta.{os.getpid()}.tmp")tmp.write_text(json.dumps(meta, indent=1, sort_keys=True) + "\n")os.replace(tmp, mp) # shards racing here all write the same contentif not mp.exists():raise SystemExit(f"{self.dir} has no cache_meta.json: refusing to read scores of unknown origin")have = json.loads(mp.read_text())want = json.loads(json.dumps(meta))diff = {k: (have.get(k), want[k]) for k in want if have.get(k) != want[k]}if diff:raise SystemExit(f"score cache {self.dir} was written for a different setup, refusing to reuse it "f"(cache value, current value): {json.dumps(diff, sort_keys=True)}")def key(self, p: Path) -> str:return "/".join(p.parts[-3:]) # <split dir>/<generator or class>/<file>: the same on every nodedef get(self, p: Path):return self.rec.get(self.key(p))def put(self, p: Path, r: dict):r = {"k": self.key(p), **r}self.rec[r["k"]] = rif self._out is None:self._out = (self.dir / f"scores.{self.tag}.jsonl").open("a", buffering=1)self._out.write(json.dumps(r) + "\n")def is_decode_error(r: dict) -> bool:"""A genuine decode failure (cached). Records written before ``kind`` existed: the decoder's own message."""return "err" in r and (r.get("kind") == "decode" or ("kind" not in r and r["err"].startswith("ValueError: Could not decode")))@torch.no_grad()def score_one(engine, spec, p: Path, raw=False, cache: ScoreCache | None = None) -> dict:"""{"p": P(fake), "logit": raw logit (only if the detector reports one), "raw": training-free score (if ``raw``; ifonly that raises, "raw_err" and the video still counts)} or {"err", "kind"} when the video cannot be scored(kind "decode": cached; anything else, e.g. OOM / I/O: not cached, retried next time)."""r = cache.get(p) if cache else Noneif r is not None and ("err" in r or not raw or "raw" in r or "raw_err" in r):if "err" not in r or is_decode_error(r):return rr = None # a legacy / non-decode error record: retryif r is None and cache is not None and cache.only:raise SystemExit(f"--cache-only: {p} is not in the score cache")try:if r is None:res = engine.predict_video_clip(spec, str(p))r = {"p": res["fake_probability"]}if "logit" in res:r["logit"] = res["logit"]if raw:try:r["raw"] = engine.video_raw_score(spec, str(p))except Exception as e: # noqa: BLE001 # old behaviour: dropped from the raw scores onlyr["raw_err"] = f"{type(e).__name__}: {e}"[:300]print(f" no raw score for {p.name}: {r['raw_err']}", flush=True)except Exception as e: # noqa: BLE001r = {"err": f"{type(e).__name__}: {e}"[:300], "kind": "decode" if isinstance(e, VideoDecodeError) else "other"}print(f" bad video {p.name} ({r['kind']}): {r['err']}", flush=True)if r["kind"] != "decode":return rif cache:cache.put(p, r)return rdef score_videos(engine, spec, paths, raw=False, cache: ScoreCache | None = None, label=""):"""Score ``paths`` -> (records of the videos that scored, decode failures, other failures)."""out, bad, other, t0 = [], 0, 0, time.time()for i, p in enumerate(paths, 1):r = score_one(engine, spec, p, raw, cache)if "err" not in r:out.append(r)elif is_decode_error(r):bad += 1else:other += 1if i % 250 == 0:print(f" {label} {i}/{len(paths)} ({(time.time() - t0) / i:.2f} s/video, {bad} decode + {other} other failures)",flush=True)return out, bad, otherdef rank_scores(recs) -> np.ndarray | None:"""The float64 raw logits to rank by (AP / AUROC) when every record has one, else None (rank by the P(fake))."""if recs and all("logit" in r for r in recs):return np.array([r["logit"] for r in recs], dtype="float64")return Nonedef unique_videos(gens, pool_key) -> list[Path]:"""The videos to score once: each distinct real pool (the same pool is hard-linked per generator) and every fake."""jobs, seen = [], set()for _, reals, fakes in gens:if pool_key(reals) not in seen:seen.add(pool_key(reals))jobs += realsjobs += fakesreturn jobsdef fake_recall_at_fpr(real_scores, fake_scores):5 unmodified linesdef main(argv=None) -> int:ap = argparse.ArgumentParser()ap.add_argument("-m", "--model", required=True, choices=["d3", "split", "restrav", "stall", "vina_video", "waverep","waverep_g4"])ap.add_argument("--benchmark", choices=["genvideo", "fakeonly", "pergen"], help="layout (not needed with --dataset)")ap.add_argument("--data", help="benchmark root (not needed with --dataset)")ap.add_argument("--dataset", help="a supported video dataset (genvideo, videophy, vidprom, evalcrafter, ...): downloads "5 unmodified linesap.add_argument("--limit", type=int, default=None, help="cap videos per class per generator")ap.add_argument("--tag", help="run tag (output filename + log); default <model>_<dataset>")ap.add_argument("--out", default=None)ap.add_argument("--cache-dir", default=None, help="store / reuse the per-video scores here (resumable, see above)")ap.add_argument("--cache-only", action="store_true", help="with --cache-dir: fail on a video that is not cached ""instead of scoring it (the final aggregation run)")ap.add_argument("--list-out", default=None, help="with --shard: write the slice's video paths (relative to --base) to ""this file and stop (no model needed); for staging only those files")ap.add_argument("--score-list", default=None, help="score exactly the videos listed in this file (paths relative to ""--base) into --cache-dir and stop (a staged slice, no discovery)")ap.add_argument("--base", default=None, help="with --list-out / --score-list: the directory the listed paths are relative to")ap.add_argument("--shard", default=None, help="K/N: score only slice K of N of the unique videos into --cache-dir, ""then stop (no metrics)")args = ap.parse_args(argv)if args.shard and not (args.cache_dir or args.list_out):raise SystemExit("--shard needs --cache-dir (or --list-out)")if args.list_out and not (args.shard and args.base):ap.error("--list-out needs --shard K/N and --base")if args.score_list:if not (args.cache_dir and args.base):raise SystemExit("--score-list needs --cache-dir and --base")engine, spec = get_engine(), get_spec(args.model)engine._get_model(spec)paths = [Path(args.base) / line.strip() for line in Path(args.score_list).read_text().splitlines() if line.strip()]cache = ScoreCache(args.cache_dir, Path(args.score_list).stem, cache_meta(engine, spec))print(f"score cache {args.cache_dir}: {len(cache.rec)} videos already scored; {len(paths)} listed | device={engine.device}",flush=True)recs, bad, other = score_videos(engine, spec, paths, hasattr(engine._get_model(spec), "score"), cache, label="list")print(f"=== LIST DONE {args.model} {Path(args.score_list).name}: scored {len(recs)} ok + {bad} decode failures + "f"{other} other failures of {len(paths)} ===", flush=True)return 0if args.dataset:droot = ensure_dataset(args.dataset, "video", args.root, download=not args.no_download)7 unmodified linesif not (args.data and args.benchmark and args.tag):raise SystemExit("pass --dataset, or --data, --benchmark and --tag")root = Path(args.data)select = set(args.select.split(",")) if args.select else Nonegens = discover(args.benchmark, root, Path(args.reals) if args.reals else None, select)if not gens:print(f"No generators with real+fake videos under {root} ({args.benchmark})")return 1if args.limit:gens = [(n, r[:args.limit], f[:args.limit]) for n, r, f in gens]pool_key = lambda reals: (len(reals), reals[0].name, reals[-1].name) # the same pool hard-linked per generatorif args.list_out:k, n = (int(x) for x in args.shard.split("/"))jobs = unique_videos(gens, pool_key)Path(args.list_out).write_text("".join(f"{p.relative_to(args.base)}\n" for p in jobs[k::n]))print(f"{args.list_out}: shard {k}/{n} = {len(jobs[k::n])} of {len(jobs)} unique videos")return 0engine = get_engine()spec = get_spec(args.model)engine._get_model(spec)print(f"=== bench_eval_video {args.tag} | {args.model} | {args.benchmark} | {len(gens)} gens "f"| device={engine.device} ===", flush=True)raw = hasattr(engine._get_model(spec), "score") # training-free detectors: also fake recall at fixed FPRmeta = cache_meta(engine, spec)cache = Noneif args.cache_dir:tag = f"{args.shard.replace('/', 'of')}" if args.shard else f"agg{os.getpid()}"cache = ScoreCache(args.cache_dir, tag, meta, write_meta=not args.cache_only)cache.only = args.cache_onlyprint(f"score cache {args.cache_dir}: {len(cache.rec)} videos already scored", flush=True)if args.shard:k, n = (int(x) for x in args.shard.split("/"))jobs = unique_videos(gens, pool_key)mine = jobs[k::n]print(f"shard {k}/{n}: {len(mine)} of {len(jobs)} unique videos", flush=True)recs, bad, other = score_videos(engine, spec, mine, raw, cache, label=f"shard{k}")print(f"=== SHARD DONE {args.tag} {k}/{n}: scored {len(recs)} ok + {bad} decode failures + {other} other failures "f"of {len(mine)} ===", flush=True)return 0per_gen, agg = {}, {"ap": [], "ap_real": [], "auroc": [], "acc": []}pooled_fake_raw = [] # every generator's fakes, for the pooled ("Overall") recallreal_cache = {} # score the shared real pool once if it is identical across generatorsfailed = {"fake": 0, "real_unique": 0} # decode failures (kind "decode") onlyfailed_other = {"fake": 0, "real_unique": 0} # any other error (OOM, I/O): dropped, never cachedfor name, reals, fakes in gens:print(f" {name}: {len(reals)} real + {len(fakes)} fake ...", flush=True)key = pool_key(reals)if key in real_cache:rrec, rbad, rother = real_cache[key]else:rrec, rbad, rother = score_videos(engine, spec, reals, raw, cache, label=f"{name} real")real_cache[key] = (rrec, rbad, rother)failed["real_unique"] += rbadfailed_other["real_unique"] += rotherfrec, fbad, fother = score_videos(engine, spec, fakes, raw, cache, label=f"{name} fake")failed["fake"] += fbadfailed_other["fake"] += fotherprobs = torch.tensor([r["p"] for r in rrec + frec])labels = torch.tensor([0] * len(rrec) + [1] * len(frec))rank = rank_scores(rrec + frec) # the raw logit, not the rounded P(fake), when there is onem = metrics(probs, labels, rank)if m is None:print(f" skip {name}: one class"); continuem.update({"n_real": len(rrec), "n_fake": len(frec), "failed_real": rbad, "failed_fake": fbad,"failed_other_real": rother, "failed_other_fake": fother,"rank_by": "logit" if rank is not None else "fake_probability"})if raw:rraw = [r["raw"] for r in rrec if "raw" in r]fraw = [r["raw"] for r in frec if "raw" in r]pooled_fake_raw += frawm["fake_recall_at_fpr"] = fake_recall_at_fpr(rraw, fraw)per_gen[name] = mfor k in agg:agg[k].append(m[k])print(f" {name}: acc={m['acc']} AP={m['ap']} AP_real={m['ap_real']} AUROC={m['auroc']} "f"(n={len(rrec)}+{len(frec)}, failed {rbad}+{fbad} decode + {rother}+{fother} other, rank by {m['rank_by']})", flush=True)if not per_gen:print("No generator produced metrics."); return 16 unmodified linesmeans["fake_recall_at_fpr"] = {k: mean([g["fake_recall_at_fpr"][k] for g in per_gen.values()])for k in next(iter(per_gen.values()))["fake_recall_at_fpr"]}# Overall: all fakes against the real pool(s) (each distinct pool once), as the SPLIT paper's "Overall" rowpooled_real_raw = [r["raw"] for rrec, _, _ in real_cache.values() for r in rrec if "raw" in r]means["overall_fake_recall_at_fpr"] = fake_recall_at_fpr(pooled_real_raw, pooled_fake_raw)result = {"tag": args.tag, "model": args.model, "ckpt": "registry-default","benchmark": f"video:{args.benchmark}", "data_root": str(root),"n_generators": len(per_gen), "means": means, "per_generator": per_gen, "failed_to_decode": failed,"failed_other": failed_other, "limit": args.limit, "reals": args.reals,"ckpt_sha256": meta["ckpt_sha256"], "cache_dir": args.cache_dir,"date": datetime.datetime.now().isoformat(timespec="seconds"),"synthscope_version": "video"}out = Path(args.out) if args.out else (REPRO / "bench_results" / f"{args.tag}.json")
70 unmodified lines71727374757670 unmodified linesdet._ensure_weights()model = det._engine._get_model(det.spec) # build + load (verified path)spec, device = det.spec, det._engine.deviceprobs = []for i in range(0, len(paths), batch_size):batch = []70 unmodified lines717273747576777870 unmodified linesdet._ensure_weights()model = det._engine._get_model(det.spec) # build + load (verified path)spec, device = det.spec, det._engine.device# native-resolution specs (LTF, B-Free, SPAI, PROBE) give variable-size tensors that cannot be stackedbatch_size = spec.eval_batch_size(batch_size)probs = []for i in range(0, len(paths), batch_size):batch = []
57 unmodified lines585960616263646557 unmodified lines"ForenSynths-8; official 4-class ProGAN weights (the served fat_former.pth)"),"co_spy_official": Entry("CO-SPY (official weights)", "forensynths", "co_spy", "Cheng et al., CVPR'25", "official-weights","cospy_official_forensynths.json", FS8, JUNE_LOG, True,"ForenSynths-8; official CO-SPY ProGAN checkpoint in the vendored official architecture ""(not the served co_spy.pth)"),"npr": Entry("NPR", "forensynths", "npr", "Tan et al., CVPR'24", "official-weights",57 unmodified lines585960616263646557 unmodified lines"ForenSynths-8; official 4-class ProGAN weights (the served fat_former.pth)"),"co_spy_official": Entry("CO-SPY (official weights)", "forensynths", "co_spy", "Cheng et al., CVPR'25", "official-weights","cospy_official_fs8_nov.json", None, "DAS6 job 66671 (repro/logs/lbfu_cospyoff_das6_66671.out)", True,"ForenSynths-8, full test sets; official CO-SPY ProGAN checkpoint in the vendored official architecture ""(not the served co_spy.pth)"),"npr": Entry("NPR", "forensynths", "npr", "Tan et al., CVPR'24", "official-weights",
6 unmodified lines789101112131415161718192021222324252627282930313233343536373 unmodified lines41424344454647484950515253545556575859606162636 unmodified lines"url": "https://github.com/SMSD75/SynthScope","evaluation": "official-weights","metrics": {"acc": 94.64,"map": 98.5,"ap": null,"auroc": 98.8},"per_generator": {"biggan": {"ap": 97.76,"auroc": 98.18,"acc": 93.95},"cyclegan": {"ap": 99.43,"auroc": 99.74,"acc": 99.25},"deepfake": {"ap": 93.4,"auroc": 93.91,"acc": 75.6},"gaugan": {"ap": 97.49,"auroc": 98.62,"acc": 95.05},"progan": {"ap": 100.0,3 unmodified lines"stargan": {"ap": 100.0,"auroc": 100.0,"acc": 99.4},"stylegan": {"ap": 99.94,"auroc": 99.93,"acc": 93.85},"stylegan2": {"ap": 100.0,"auroc": 100.0,"acc": 100.0}},"submitted_by": "SynthScope","date": "2026-06-04","verified": true,"source": "repro/bench_results/cospy_official_forensynths.json (tag cospy_official_forensynths, 8 of its 13 generators); job log not kept on the shared filesystem; MASTER_RESULTS.jsonl row of the same tag","protocol_notes": "ForenSynths-8; official CO-SPY ProGAN checkpoint in the vendored official architecture (not the served co_spy.pth)","synthscope_version": "0.1.0"}6 unmodified lines789101112131415161718192021222324252627282930313233343536373 unmodified lines41424344454647484950515253545556575859606162636 unmodified lines"url": "https://github.com/SMSD75/SynthScope","evaluation": "official-weights","metrics": {"acc": 95.12,"map": 98.85,"ap": null,"auroc": 99.03},"per_generator": {"biggan": {"ap": 98.19,"auroc": 98.47,"acc": 94.6},"cyclegan": {"ap": 99.38,"auroc": 99.74,"acc": 99.28},"deepfake": {"ap": 95.15,"auroc": 95.24,"acc": 77.77},"gaugan": {"ap": 98.1,"auroc": 98.88,"acc": 95.16},"progan": {"ap": 100.0,3 unmodified lines"stargan": {"ap": 100.0,"auroc": 100.0,"acc": 99.6},"stylegan": {"ap": 99.97,"auroc": 99.96,"acc": 97.75},"stylegan2": {"ap": 99.99,"auroc": 99.99,"acc": 96.78}},"submitted_by": "SynthScope","date": "2026-11-08","verified": true,"source": "repro/bench_results/cospy_official_fs8_nov.json (tag cospy_official_fs8_nov, all generators); DAS6 job 66671 (repro/logs/lbfu_cospyoff_das6_66671.out)","protocol_notes": "ForenSynths-8, full test sets; official CO-SPY ProGAN checkpoint in the vendored official architecture (not the served co_spy.pth)","synthscope_version": "0.1.0"}
123456789101112131415161718name: cure_train# CuRe stage 1 (arXiv 2609.14316): GenImage SD v1.4 train, 162,000 ImageNet reals (JPEG) + 162,000 SD v1.4 images# (PNG, re-encoded as JPEG q96 by the endpoint preprocessing, as the paper / DDA). An item is the pixel mixture# (1 - a) x_r + a x_g of a real and an independently drawn generated image, a ~ U(0, 1), target a (dataset.CuReMixDataset);# an epoch = one pass over the 162k reals. Validation: val_pairs fixed mixtures of the SD v1.4 test split (6k + 6k).# Layout as GenImageDataset stores it: <root_dir>/{train,test}/{real,fake}; prefetch fetches it with that loader.root_dir: /hddstore/ssalehi/SynthScope/GenImagehf_repo_id: jzousz/GenImagehf_subdir: stable_diffusion_v_1_4prefetch: falsetrain_batch_size: 64 # per GPU (the paper's per-GPU batch)val_batch_size: 64num_workers: 8val_pairs: 2000max_images: null # smoke runs: the first N reals and N fakes of the split (sorted names)val_max_images: null # null = the whole test split (independent of max_images)seed: 0 # the validation pairstrain_augment: null # null = the recipe; dda = stage-1 investigation R3 (models/image/cure/train_augment.py)9 unmodified lines101112131415165 unmodified lines22232425262728293031329 unmodified linessemantic_dim: 3072semantic_proj_dim: 256resnet_pretrained: truehead_hidden: 1024num_classes: 25 unmodified lines# Test-time preprocessing (official): inference and benchmarks.eval_transform_list: [aide_five_view]# Training augmentation: the five native-resolution views, long side capped at 1024 (the recipe of the SynthScope_train# checkpoint, repro/retrain_aide_native_v2.sbatch).train_transform_list: [random_horizontal_flip, aide_five_view_train]# Validation during training (differs from the test-time preprocessing above).val_transform_list: [aide_five_view_train]# Caps the long side at 1024 to bound dataloader-worker memory during the end-of-training test; inference and# benchmarks use the uncapped eval list.test_transform_list: [aide_five_view_train]9 unmodified lines1011121314151617185 unmodified lines242526272829303132333435369 unmodified linessemantic_dim: 3072semantic_proj_dim: 256# Not read by any code: the two ResNet-50 streams start from random weights, as in the official run (its AIDE_Model builds# a pretrained state dict from --resnet_path but never calls load_state_dict, and conv1 takes 30 HPF channels anyway).resnet_pretrained: falsehead_hidden: 1024num_classes: 25 unmodified lines# Test-time preprocessing (official): inference and benchmarks.eval_transform_list: [aide_five_view]# Training = the official TrainDataset (data/datasets.py): at native resolution Gaussian blur (3x3, sigma 0.1-3, p 0.1)# then JPEG (QF 30-100, p 0.1), then the five views; no flip, no crop. aide_five_view_train differs from the official# transform only in capping the long side at 1024 before the DCT (worker memory).train_transform_list: [aide_blur, aide_jpeg, aide_five_view_train]# Validation during training: the official run validates through the same TrainDataset, so the perturbations apply to the# validation images too.val_transform_list: [aide_blur, aide_jpeg, aide_five_view_train]# Caps the long side at 1024 to bound dataloader-worker memory during the end-of-training test; inference and# benchmarks use the uncapped eval list. No perturbations (the official TestDataset has none).test_transform_list: [aide_five_view_train]
15 unmodified lines16171815 unmodified lines# Test-time preprocessing (official): inference, benchmarks and the end-of-training test.eval_transform_list: [cure_eval]15 unmodified lines161718192021222324252615 unmodified lines# Test-time preprocessing (official): inference, benchmarks and the end-of-training test.eval_transform_list: [cure_eval]# Training (the paper's recipe; the official release has no training code): experiments/image/cure.sh.# Stage 1 = training_stage: ratio (mixing-ratio regression; experiments/image/cure.sh sets it);# stages 2-3 = models/image/cure/train_stages.py. Stage-1 endpoints use eval_transform_list (see dataset.CuReEndpoints).training_stage: null # null = the released 2-way model; ratio = stage 1 (adds the 1024 -> 1 ratio head)grad_checkpointing: false # stage 1: recompute each block in backward (per-GPU batch 64 at 336 px)lora_weight_decay: 0.1 # stage 1 AdamW weight decay on the LoRA tensors (Appendix A)head_weight_decay: 0.01 # stage 1 AdamW weight decay on the ratio head (Appendix A)
1234567891011121314151617181920defaults: - /model/default - _self_
# PROBE-DINOv2 (ICML 2026, arXiv 2605.24906): DINOv2 ViT-L/14 with registers + Linear(1024, 1) on the CLS token, scored# as the mean logit of the image's non-overlapping 336x336 patches at native resolution; P(fake) = sigmoid(mean).# The official DINOv2_best_model_step_34999.pth (ModelScope shuinishaojiu/PROBE-AIGI-Detection) holds the full model# and loads key-for-key as probe.pth.model_type: probebackbone_name: dinov2_with_registers_largebackbone_path: null # null: build the backbone from its config (probe.pth has the weights); a HF-format # directory or hub id (facebook/dinov2-with-registers-large) loads pretrained weightsclassifier_type: linear # the official evaluate_dino.py: dino_classifier(classifier_type='linear')patch_chunk_size: 32 # patches per backbone forward (0 = all of a batch at once, as the official code)
# Test-time preprocessing (official evaluate_dino.py, README: --crop_size 336): pad_image(mode='repeat') tiles an image# with a side under 336 with copies of itself, ToTensor + ImageNet normalization, then the non-overlapping 336 patches# [N, 3, 336, 336]; the model averages the patch logits. The patch count depends on the image size.eval_transform_list: [probe_pad_repeat_336, to_dtype, normalize_imagenet, sliding_patches_336]# No training lists: the official fine-tuning code is not released.123456789101112131415161718defaults: - /model/default - _self_
# PROBE-ResNet50 (ICML 2026, arXiv 2605.24906): the official resnet50(num_classes=1, classifier_type='linear'),# scored as the mean logit of the image's non-overlapping 224x224 patches at native resolution; P(fake) = sigmoid(mean).# The official ResNet50_best_model_step_19343.pth (ModelScope shuinishaojiu/PROBE-AIGI-Detection) holds the full model# and loads key-for-key as probe_resnet.pth.model_type: probe_resnetbackbone_name: resnet50classifier_type: linearpatch_chunk_size: 32 # patches per forward (0 = all of a batch at once, as the official code)
# Test-time preprocessing (official evaluate_resnet.py, README: --crop_size 224): pad_image(mode='pad') pastes an image# with a side under 224 on a black 224x224 square (a longer side is cut), ToTensor + ImageNet normalization, then the# non-overlapping 224 patches [N, 3, 224, 224]; the model averages the patch logits.eval_transform_list: [probe_pad_224, to_dtype, normalize_imagenet, sliding_patches_224]# No training lists: the official fine-tuning code is not released.123456789101112131415161718defaults: - /model/default - _self_
# WaveRep (NeurIPS'25, grip-unina/WaveRep-SyntheticVideoDetection): timm DINOv2 ViT-B/14 + 4 registers at a 504x504# input with one logit, fine-tuned end to end on single video frames; a video's logit is the mean over its frames. The# released weights_dinov2_G{1,4}.ckpt hold the full timm model (strict load); pretrained_backbone: true starts from the# timm DINOv2 weights instead (the official create_model does, then overwrites every key with the checkpoint).model_type: wavereptimm_arch: vit_base_patch14_reg4_dinov2.lvd142mcrop_size: 504pretrained_backbone: falseframe_batch: 16 # frames per forward pass when a clip is scored (memory only; per-frame logits as official)
# Per-frame test-time preprocessing (official demo/utils.py create_transform): CenterCrop((504, 504)) on the PIL frame,# zero-padded when the frame is smaller, no resize; ToTensor; ImageNet normalization. Frame reading and aggregation are# the registry's video settings (interface/backend/registry.py, video_sampler "cv2_frames").eval_transform_list: [center_crop_504, to_dtype, normalize_imagenet]1 unmodified line234567891011121314151617181 unmodified line- /trainer/default- _self_trainer_type: aideepochs: 5lr: 1.0e-4weight_decay: 0.0label_smoothing: 0.0val_interval: 1test_interval: 1save_interval: 1save: falsesave_policy: maxwarmup:mode: offwarmup_ratio: 0.05lr_scheduler: linear1 unmodified line234567891011121314151617181920212223242526272829303132333435361 unmodified line- /trainer/default- _self_# AIDE's released training recipe (shilinyan99/AIDE main_finetune.py + the paper's GenImage setting): AdamW (betas# 0.9/0.999, eps 1e-8) lr 5e-4 at effective batch 256 (blr 5e-4 x 256 / 256), weight decay 0, 5 epochs, per-iteration# half-cosine to min_lr 1e-6 without warmup, timm LabelSmoothingCrossEntropy 0.1, fp32, no gradient clipping, no EMA, seed 0.# The official batch is 8 GPUs x 32; here 4 GPUs x 8 micro-batch x grad_accum_steps 8 = 256 (a 24 GB GPU fits 8). The# BatchNorm statistics of the two ResNets are then taken over all 4 GPUs' micro-batches (sync_batchnorm), the 32 images the# official run normalizes with on each of its GPUs. The checkpoint is the epoch with the highest validation accuracy# (select: accuracy, the official max_accuracy -> model_best.pth); every epoch is kept as model_<epoch>.pth.trainer_type: aideepochs: 5lr: 5.0e-4weight_decay: 0.0label_smoothing: 0.1seed: 0sync_batchnorm: trueval_interval: 1test_interval: 1save_interval: 1save: truesave_policy: maxsave_path: /nvmestore/ssalehi/SynthScope/models/aidewarmup:mode: "off"warmup_ratio: 0.05lr_scheduler: lineartimm_cosine:warmup_epochs: 0warmup_lr: 0.0min_lr: 1.0e-6grad_accum_steps: 8save_all: trueselect: accuracylog_every: 100 # optimizer steps between the loss / lr lines
123456789101112131415161718192021222324252627282930defaults: - /trainer/default - _self_
# CuRe stage 1 (arXiv 2609.14316, Appendix A): LoRA (Q/V, all 24 layers, rank 64, alpha 128, dropout 0) + linear ratio# head, BCE against the mixing ratio; AdamW lr 1e-5, weight decay 0.1 (LoRA) / 0.01 (head) (ModelConfig# lora_weight_decay / head_weight_decay, applied through the model's optimizer_param_groups), betas (0.9, 0.999) (torch# default; not stated), 5 epochs at per-GPU batch 64, two warmup epochs then cosine to 1e-6. Unstated, assumed: the# warmup is linear from 0 per optimizer step and the cosine runs over the remaining 3 epochs from the peak lr (MAE-style,# warmup_prefix); no gradient clipping; fp16 autocast with a loss scaler (the released inference runs fp16); seed 0; the# last epoch is the stage-1 model (the paper states no model selection; every epoch is kept, model_last.pth is used).trainer_type: cureepochs: 5lr: 1.0e-5weight_decay: 0.1 # overridden per group by the model (0.1 LoRA / 0.01 head)label_smoothing: 0.0seed: 0save: truesave_policy: minsave_path: /nvmestore/ssalehi/SynthScope/models/cure/stage1warmup: mode: "off" # quoted: a bare off is YAML boolean Falsetimm_cosine: warmup_epochs: 2 warmup_lr: 0.0 min_lr: 1.0e-6 warmup_prefix: true # cosine over epochs 2-5, from 1e-5 down to 1e-6 grad_accum_steps: 1 # MICRO < 64 per GPU: accumulate 64 / MICRO micro-batches per optimizer step save_all: true log_every: 5031 unmodified lines3233343536373054 unmodified lines309230933094309530963097340 unmodified lines34383439344034413442344331 unmodified linesfrom models.image.dda.official_train_data import MEAN as DDA_MEAN, STD as DDA_STD, build_item as dda_build_item, \create_train_transforms as dda_train_transformsfrom models.image.dda.official_train_transforms import ComposedTransforms as DDAComposedTransformsdef _decode_rgb(path) -> torch.Tensor:3054 unmodified linesreturn Noneclass _TestOnlyImageModule:"""Shared loader for the eval-only image benchmarks (test split only)."""DATASET_CLASS = _TestOnlyImageDataset340 unmodified lines"mirage_test": MirageTestDatasetModule,# Training sets of detectors trained in SynthScope with their official recipe."spai_train": SPAITrainDatasetModule,# Video benchmarks. EvalCrafter/GenVidBench/VideoFeedback/ComGenVid have dedicated classes that# download + extract their HF archives into the real/fake layout; the rest use the generic# VideoFolderDatasetModule.31 unmodified lines32333435363738393054 unmodified lines30943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227340 unmodified lines356835693570357135723573357431 unmodified linesfrom models.image.dda.official_train_data import MEAN as DDA_MEAN, STD as DDA_STD, build_item as dda_build_item, \create_train_transforms as dda_train_transformsfrom models.image.dda.official_train_transforms import ComposedTransforms as DDAComposedTransformsfrom models.image.cure.preprocess import SRC_FORMAT_KEYfrom models.image.cure.train_augment import CuReDDAEndpointdef _decode_rgb(path) -> torch.Tensor:3054 unmodified linesreturn Noneclass CuReEndpoints:"""The real and generated images of a GenImage-layout split (``<root>/<train|test>/{real,fake}``, as:class:`GenImageDataset` stores GenImage SD v1.4: 162k + 162k train, 6k + 6k test), each preprocessed on its own bythe CuRe endpoint transform. The transform is the model config's ``eval_transform_list`` (``cure_eval``: PNG sources-> JPEG q96, which is the paper's re-encoding of the generated PNGs to match the JPEG reals; SmallestMaxSize 390,CenterCrop 390, Resize 336, JPEG q70, mean = std = 0.5): the paper does not state its training preprocessing, andthe released test-time pipeline is the one the trained subspace and head are used with. Images are opened with PIL andtheir source format is recorded (``SRC_FORMAT_KEY``), as ``bench_eval`` does, so the PNG step applies.``max_images`` keeps the first N reals and the first N fakes (sorted file names, over the whole split, not perImageNet class; smoke runs)."""def __init__(self, root_dir, split, transform, max_images=None, augment=None):split_dir = Path(root_dir) / ("train" if split == "train" else "test")# augment: optional ``callable(PIL image, seed) -> tensor`` used instead of ``transform`` when a seed is given# (the stage-1 investigation's R3 run: models/image/cure/train_augment.py); None = the recipe (no augmentation)self.augment = augmentself.reals = sorted(_iter_images(split_dir / "real"))self.fakes = sorted(_iter_images(split_dir / "fake"))if max_images:self.reals, self.fakes = self.reals[:int(max_images)], self.fakes[:int(max_images)]if not self.reals or not self.fakes:raise RuntimeError(f"CuRe data: no real/ or fake/ images under {split_dir}")self.transform = transformdef load(self, path: Path, seed=None) -> torch.Tensor:"""``path`` -> the preprocessed float tensor ``[3, 336, 336]`` (with ``augment`` and a ``seed``: augmented)."""with Image.open(path) as source:source_format = source.formatimage = source.convert("RGB")image.info[SRC_FORMAT_KEY] = source_formatif self.augment is not None and seed is not None:return self.augment(image, seed)return self.transform(image)def load_any(self, paths, index: int, fallback, seed=None) -> torch.Tensor:"""``load(paths[index])``; an unreadable file (GenImage has a few 0-byte PNGs) is replaced by ``paths[fallback()]``."""for _ in range(10):try:return self.load(paths[index], seed)except Exception as exc: # noqa: BLE001print(f"[cure data] unreadable image {paths[index]}: {exc}", flush=True)index = fallback()raise RuntimeError("CuRe data: 10 unreadable images in a row")def cure_mix(x_real: torch.Tensor, x_gen: torch.Tensor, alpha) -> torch.Tensor:"""Eq. 1 / Eq. 5: ``(1 - alpha) x_0 + alpha x_1`` on preprocessed tensors (mean = std = 0.5 is affine, so this equalsthe pixel-space mixture of the preprocessed images, normalized). ``alpha`` is a float or a tensor that broadcasts."""return (1 - alpha) * x_real + alpha * x_genclass CuReMixDataset(Dataset):"""CuRe stage-1 data (arXiv 2609.14316, Sec. 3.1 / Appendix A): an item is the mixture x_a = (1 - a) x_r + a x_g of areal image x_r and an independently drawn generated image x_g, a ~ U(0, 1) per pair, with a as the regression target:``(x_a [3, 336, 336], a, 0)``. Mixing happens after the endpoint preprocessing (see :class:`CuReEndpoints`).``train``: one item per real image (an epoch = 162,000 pairs for GenImage SD v1.4, the reals in the loader's randomorder); the generated partner and a are drawn at random in each ``__getitem__``, so pairs and ratios change everyepoch and partners are drawn with replacement. In a DataLoader worker the draw uses a generator seeded by theworker's seed (new every epoch) and the item index: every DDP process gets the same worker seeds (one global seed),but its own real indices, so the processes' draws stay independent. ``val``: ``val_pairs`` fixed pairs (real i, aseeded random fake, a seeded random a), the same every epoch."""def __init__(self, endpoints: CuReEndpoints, split, val_pairs=None, seed=0):self.ep, self.split, self.seed = endpoints, split, int(seed)self.n = len(endpoints.reals) if split == "train" else min(int(val_pairs or len(endpoints.reals)), len(endpoints.reals))def __len__(self):return self.ndef __getitem__(self, idx):ep = self.epif self.split == "train":worker = torch.utils.data.get_worker_info()g = None if worker is None else torch.Generator().manual_seed((worker.seed * 1_000_003 + idx) % 2 ** 63)else:g = torch.Generator().manual_seed(self.seed * 1_000_003 + idx)draw_fake = lambda: int(torch.randint(len(ep.fakes), (), generator=g))draw_real = lambda: int(torch.randint(len(ep.reals), (), generator=g))fake_idx, alpha = draw_fake(), float(torch.rand((), generator=g))# R3 only (ep.augment set, train split): one augmentation seed per pair, shared by both endpoints (DDA's paired# transforms); drawn after the pair and ratio so the recipe's draws are unchangedaug_seed = int(torch.randint(2 ** 31 - 1, (), generator=g)) if (ep.augment is not None and self.split == "train") else Nonex_real = ep.load_any(ep.reals, idx, draw_real, aug_seed)x_gen = ep.load_any(ep.fakes, fake_idx, draw_fake, aug_seed)return cure_mix(x_real, x_gen, alpha), torch.tensor(alpha, dtype=torch.float32), torch.tensor(0)class CuReTrainDatasetModule:"""CuRe stage 1 for SynthScope's trainer: :class:`CuReMixDataset` on GenImage SD v1.4 ``train`` and, for theper-epoch validation loss, ``val_pairs`` fixed mixtures from its ``test`` split. ``prefetch`` downloads the splitwith :class:`GenImageDataset`'s loader (``hf_repo_id`` / ``hf_subdir``) when it is missing."""def __init__(self, config):self.config = configcfg = config.DatasetConfigroot = Path(cfg.root_dir)if bool(cfg.get("prefetch", False)):GenImageDataset.hf_repo_id = cfg.get("hf_repo_id", None)GenImageDataset.hf_subdir = cfg.get("hf_subdir", None)for split in ("train", "test"):GenImageDataset.prepare_split(root, split)transform = AIGITransformations(list(config.ModelConfig.eval_transform_list))cap = cfg.get("max_images", None)seed = int(cfg.get("seed", 0))augment = cfg.get("train_augment", None)if augment not in (None, "dda"):raise ValueError(f"cure_train: train_augment must be null or 'dda', got {augment!r}")if augment == "dda": # stage-1 investigation R3 only; validation stays un-augmentedaugment = CuReDDAEndpoint(augment=True)self.train_dataset = CuReMixDataset(CuReEndpoints(root, "train", transform, cap, augment=augment), "train", seed=seed)self.val_dataset = CuReMixDataset(CuReEndpoints(root, "test", transform, cfg.get("val_max_images", None)), "val",val_pairs=cfg.get("val_pairs", None), seed=seed)def train_dataloader(self):cfg = self.config.DatasetConfigreturn DataLoader(self.train_dataset, batch_size=cfg.train_batch_size, shuffle=True, num_workers=cfg.num_workers,pin_memory=True, drop_last=True, persistent_workers=False)def val_dataloader(self):cfg = self.config.DatasetConfigreturn DataLoader(self.val_dataset, batch_size=cfg.val_batch_size, shuffle=False, num_workers=cfg.num_workers,pin_memory=True)def test_dataloader(self):return Noneclass _TestOnlyImageModule:"""Shared loader for the eval-only image benchmarks (test split only)."""DATASET_CLASS = _TestOnlyImageDataset340 unmodified lines"mirage_test": MirageTestDatasetModule,# Training sets of detectors trained in SynthScope with their official recipe."spai_train": SPAITrainDatasetModule,"cure_train": CuReTrainDatasetModule,# Video benchmarks. EvalCrafter/GenVidBench/VideoFeedback/ComGenVid have dedicated classes that# download + extract their HF archives into the real/fake layout; the rest use the generic# VideoFolderDatasetModule.
32 unmodified lines333435363738394032 unmodified lines`conf/dataset/...` config are fallbacks, used only for models whose config sets none, and a warning is printedwhen a dataset list is shadowed. Validation and test pipelines run on PIL images like inference, so anend-of-training test with `eval_transform_list` preprocesses exactly as the benchmarks do.Video models are out of scope for now: their preprocessing is the registry's video settings plus the datasetlists. Add `conf/dataset/...` / `conf/trainer/...` only if a new recipe is needed.3. **Dispatch** — add a branch in `trainer.py` `_build_model` (the `if model_type == "<k>": return SynthScope<Name>Model(config)` chain, ~line 69+). The interface lazy-imports by `model_type` in `interface/backend/engine.py` — mirror it if needed.4. **Interface registry** — `interface/backend/registry.py` `_add(ModelSpec(...))`:- `key`, `name`, `paper`, `modality` (`image`|`video`), `overrides=["model@ModelConfig=image/<k>"]`,32 unmodified lines33343536373839404142434432 unmodified lines`conf/dataset/...` config are fallbacks, used only for models whose config sets none, and a warning is printedwhen a dataset list is shadowed. Validation and test pipelines run on PIL images like inference, so anend-of-training test with `eval_transform_list` preprocesses exactly as the benchmarks do.Video models are mostly out of scope for training: their preprocessing is the registry's video settings (framesampler, `num_frames`, window) plus the dataset lists, and most do not use `eval_transform_list`. `waverep` is the exception:its frames go through a per-frame transform, so it sets `eval_transform_list` (`center_crop_504`,`to_dtype`, `normalize_imagenet`) and the registry builds its `transform` from it with `model_transform`like an image detector (`tests/test_model_transforms.py` checks video configs that have a list). Add`conf/dataset/...` / `conf/trainer/...` only if a new recipe is needed.3. **Dispatch** — add a branch in `trainer.py` `_build_model` (the `if model_type == "<k>": return SynthScope<Name>Model(config)` chain, ~line 69+). The interface lazy-imports by `model_type` in `interface/backend/engine.py` — mirror it if needed.4. **Interface registry** — `interface/backend/registry.py` `_add(ModelSpec(...))`:- `key`, `name`, `paper`, `modality` (`image`|`video`), `overrides=["model@ModelConfig=image/<k>"]`,
9 unmodified lines10111213141516171816 unmodified lines353637383940414243444546474844 unmodified lines939495969798997 unmodified lines1071081091101111121139 unmodified lines---## 1. What's already integrated (17 detectors)`synthscope.list_models()` / `from synthscope.api import list_specs`. Each is an `SynthScope<Name>Model` with amatching `conf/model/<modality>/<key>.yaml`, a `trainer.py._build_model` branch, an`interface/backend/registry.py` `ModelSpec`, a per-model `README.md`, and a `tests/test_<k>_smoke.py`.16 unmodified lines| `bfree` | image | bce | official | – | DINOv2 ViT-B/14 + registers, bias-free training data; five 504 crops at native resolution || `mirror` | image | ce | official | – | Frozen DINOv3 ViT-H+/16 + LoRA + memory bank (seeded default initialization in the released checkpoint): reconstruction of an "ideal reference" (center-crop 224, JPEG q96 for PNG/BMP/TIFF) || `vina` | image | bce | official | – | DINOv3 ViT-L/16 + linear head trained on images and video frames together (short side 256, center-crop 256) || `moejepa` | image | ce | official | – | Frozen V-JEPA 2 ViT-L + residual MoE + gated-attention MIL + BayarConv noise branch (3-way head) || `effort` (+ `effort_chameleon`) | image | ce | official | – | CLIP ViT-L/14 + SVD-residual attention (orthogonal subspace decomposition) || `ltf` | image | ce | official | – | Native-resolution 224 tiles + global view, frozen CLIP ViT-L/14, hierarchical MIL + gated fusion (evaluation only) || `vib_net` | image | vib | synthscope | – | Variational information bottleneck on frozen CLIP ViT-L/14 (trained in SynthScope; reproduces the paper) || `d3` | video | video | training-free | – | Disentangled detail dynamics (X-CLIP) || `split` | video | video | training-free | – | Temporal roughness x spatial patch-level motion incoherence (X-CLIP) || `restrav` | video | video | synthscope | – | Representation-trajectory geometry (DINOv2) || `stall` | video | video | training-free | – | Spatio-temporal whitened log-likelihoods (DINOv3) || `vina_video` | video | video | official | – | The `vina` model with the paper's video protocol: ffmpeg 2 fps JPEG frames, the central frame, sigmoid of the mean logit (needs ffmpeg) |`*` served via official weights remapped into the SynthScope class. **`predict_kind`** sets the score44 unmodified lines## 4. Evaluation / benchmarking- **Image**: `benchmark/bench_eval.py --model <k> --benchmark {forensynths|ufd|pergen|pool} --data <root> [--ckpt <pth>] [--native-res] --tag <t>`. Auto-discovers `<gen>/{0_real,1_fake}` (or `{ai,nature}`, shared-reals) layouts; prints per-generator acc/AP/AUROC + mean; writes `repro/bench_results/<tag>.json`.- **Video**: `benchmark/bench_eval_video.py --model {d3|restrav|stall} --dataset NAME` (auto-download) or `--benchmark {genvideo|fakeonly|pergen} --data DIR`.- `--ckpt` overrides the registry checkpoint (for official-vs-SynthScope side-by-side).- `--model-config NAME` (needs `--ckpt`) scores that checkpoint with `conf/model/NAME.yaml` instead of the served model config, keeping the registry's other overrides (e.g. `image/effort_ufd`: a training recipe with its own test preprocessing).- `benchmark/aggregate_results.py`, `leaderboard.py`, `evaluate.py`, `schema.json` aggregate runs.7 unmodified linesKnown image sets: `cnndetection` (ForenSynths/ProGAN), `genimage`, `genimage_full` (8-gen),`universialfakedetection` (Ojha UFD), `aigibench`, `synthbuster`, `ditfake`, `diffusionforensics`,`diffusion1kstep`, `aigcdetect`, `commgen15`, `realchain`, `evalgen`, `synthwildx`, `wildrf`, `bfree_online`, `rrdataset`, `cospy`/`cospy_subset`, `spai_ldm`, `freqnetdetection`.Video: `genvideo_val`, `genvideo`, `videophy`, `vidprom`, `restrav_data`, `evalcrafter`, `genvidbench`, `videofeedback`, `comgenvid`.Each `DatasetDef` lists candidate roots; **`_resolve_root` is node-portable** — it remaps the configured9 unmodified lines1011121314151617181916 unmodified lines363738394041424344454647484950515244 unmodified lines9798991001011021037 unmodified lines1111121131141151161179 unmodified lines---## 1. What's already integrated`synthscope.list_models()` / `from synthscope.api import list_specs` give the current set (36 registry keys on2026-11-11: 29 image, 7 video; the table groups related keys such as the OmniAID, PROBE and Effort variants). Each is an `SynthScope<Name>Model` with amatching `conf/model/<modality>/<key>.yaml`, a `trainer.py._build_model` branch, an`interface/backend/registry.py` `ModelSpec`, a per-model `README.md`, and a `tests/test_<k>_smoke.py`.16 unmodified lines| `bfree` | image | bce | official | – | DINOv2 ViT-B/14 + registers, bias-free training data; five 504 crops at native resolution || `mirror` | image | ce | official | – | Frozen DINOv3 ViT-H+/16 + LoRA + memory bank (seeded default initialization in the released checkpoint): reconstruction of an "ideal reference" (center-crop 224, JPEG q96 for PNG/BMP/TIFF) || `vina` | image | bce | official | – | DINOv3 ViT-L/16 + linear head trained on images and video frames together (short side 256, center-crop 256) || `probe`, `probe_resnet` | image | bce | official | – | PROBE: DINOv2 ViT-L/14 + registers (`probe`, patches of 336) or ResNet-50 (`probe_resnet`, patches of 224), single-logit head; the score is the mean logit of the image's non-overlapping patches at native resolution || `moejepa` | image | ce | official | – | Frozen V-JEPA 2 ViT-L + residual MoE + gated-attention MIL + BayarConv noise branch (3-way head) || `effort` (+ `effort_chameleon`) | image | ce | official | – | CLIP ViT-L/14 + SVD-residual attention (orthogonal subspace decomposition) || `ltf` | image | ce | official | – | Native-resolution 224 tiles + global view, frozen CLIP ViT-L/14, hierarchical MIL + gated fusion (evaluation only) || `vib_net` | image | vib | synthscope | – | Variational information bottleneck on frozen CLIP ViT-L/14 (trained in SynthScope; reproduces the paper) || `vib_net_official` | image | vib | official | – | The same model with the official architecture and test transform (center-crop 224); loads the released checkpoints or a SynthScope-trained one || `d3` | video | video | training-free | – | Disentangled detail dynamics (X-CLIP) || `split` | video | video | training-free | – | Temporal roughness x spatial patch-level motion incoherence (X-CLIP) || `restrav` | video | video | synthscope | – | Representation-trajectory geometry (DINOv2) || `stall` | video | video | training-free | – | Spatio-temporal whitened log-likelihoods (DINOv3) || `waverep` (+ `waverep_g4`) | video | video | official | – | DINOv2 ViT-B/14 + registers fine-tuned frame by frame with a wavelet-band augmentation; the first 64 frames (OpenCV), center 504 crop, sigmoid of the mean frame logit (`waverep` = trained on one generator, `waverep_g4` on four) || `vina_video` | video | video | official | – | The `vina` model with the paper's video protocol: ffmpeg 2 fps JPEG frames, the central frame, sigmoid of the mean logit (needs ffmpeg) |`*` served via official weights remapped into the SynthScope class. **`predict_kind`** sets the score44 unmodified lines## 4. Evaluation / benchmarking- **Image**: `benchmark/bench_eval.py --model <k> --benchmark {forensynths|ufd|pergen|pool} --data <root> [--ckpt <pth>] [--native-res] --tag <t>`. Auto-discovers `<gen>/{0_real,1_fake}` (or `{ai,nature}`, shared-reals) layouts; prints per-generator acc/AP/AUROC + mean; writes `repro/bench_results/<tag>.json`.- **Video**: `benchmark/bench_eval_video.py --model {d3|split|restrav|stall|vina_video|waverep|waverep_g4} --dataset NAME` (auto-download) or `--benchmark {genvideo|fakeonly|pergen} --data DIR`.- `--ckpt` overrides the registry checkpoint (for official-vs-SynthScope side-by-side).- `--model-config NAME` (needs `--ckpt`) scores that checkpoint with `conf/model/NAME.yaml` instead of the served model config, keeping the registry's other overrides (e.g. `image/effort_ufd`: a training recipe with its own test preprocessing).- `benchmark/aggregate_results.py`, `leaderboard.py`, `evaluate.py`, `schema.json` aggregate runs.7 unmodified linesKnown image sets: `cnndetection` (ForenSynths/ProGAN), `genimage`, `genimage_full` (8-gen),`universialfakedetection` (Ojha UFD), `aigibench`, `synthbuster`, `ditfake`, `diffusionforensics`,`diffusion1kstep`, `aigcdetect`, `commgen15`, `realchain`, `evalgen`, `synthwildx`, `wildrf`, `bfree_online`, `rrdataset`, `mirage_test`, `arforensics`, `cospy`/`cospy_subset`, `spai_ldm`, `freqnetdetection`.Video: `genvideo_val`, `genvideo`, `videophy`, `vidprom`, `restrav_data`, `evalcrafter`, `genvidbench`, `videofeedback`, `comgenvid`.Each `DatasetDef` lists candidate roots; **`_resolve_root` is node-portable** — it remaps the configured
1234567891011121314151617181920#!/bin/bashexport TRITON_CACHE_DIR=/nvmestore/ssalehi/.tritonexport HF_HOME=/nvmestore/ssalehi/.cache/huggingfaceexport TORCH_HOME=/nvmestore/ssalehi/.cache/torchexport CUDA_VISIBLE_DEVICES=1,2export OMP_NUM_THREADS=1# Five native-resolution views per image (aide.yaml lists): batch 8 and 5 workers bound memory, as in the run behind# the README's SynthScope_train checkpoint (repro/retrain_aide_native_v2.sbatch)./home/ssalehi/miniconda3/bin/conda run --no-capture-output -n SynthScope accelerate launch --config_file accelerate_config.yaml --num_processes 2 main.py \trainer@TrainerConfig=image/aide \model@ModelConfig=image/aide \dataset@DatasetConfig=image/genimage \DatasetConfig.train_batch_size=8 \DatasetConfig.num_workers=5 \DatasetConfig.val_batch_size=16 \DatasetConfig.test_batch_size=16 \logger.name=aide \logger.mode=online \logger.tags=[SynthScope,AIDE,genimage]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152#!/bin/bash# AIDE (ICLR 2025): the official training recipe (shilinyan99/AIDE main_finetune.py, data/datasets.py + the paper's# GenImage setting), reproduced in SynthScope.# data GenImage SD v1.4 train (162k ImageNet reals + 162k SD v1.4 fakes); validation = the SD v1.4 val split# model frozen OpenCLIP ConvNeXt-XXL (laion2b soup) + two ImageNet ResNet-50 on the SRM-filtered DCT patches + MLP head# train at native resolution: Gaussian blur (3x3, sigma 0.1-3, p 0.1), JPEG (QF 30-100, p 0.1), DCT selection of# 4 patches, every view resized to 256 (no flip, no crop). The one deviation: the long side is capped at# 1024 before the DCT (dataloader-worker memory). The validation images get the same perturbations, as in# the official run (it validates through the training dataset class).# optimizer AdamW 5e-4 at effective batch 256, weight decay 0, 5 epochs, per-iteration cosine to 1e-6, no warmup,# label smoothing 0.1, fp32, no gradient clipping, no EMA# batch the official 8 GPUs x 32 becomes 4 GPUs x 8 x grad_accum 8 = 256 (a 24 GB GPU fits a micro-batch of 8); the# BatchNorm statistics are synchronized over the 4 GPUs (32 images, as on each official GPU)# checkpoint model_best.pth = the epoch with the highest validation accuracy (the official max_accuracy); every epoch# is kept as model_<epoch>.pth# Plain DDP (accelerate --multi_gpu): the repo's accelerate_config.yaml uses DeepSpeed with gradient clipping 1.0, which the# official recipe does not have. Resume: rerun with the same SAVE (the state is saved after every epoch).# Evaluate: python benchmark/bench_eval.py --model aide --ckpt <save_path>/model_best.pth --benchmark genimage# Requires: pip install kornia==0.7.2 (the official perturbations)export TRITON_CACHE_DIR=${TRITON_CACHE_DIR:-/nvmestore/ssalehi/.triton}export HF_HOME=${HF_HOME:-/nvmestore/ssalehi/.cache/huggingface}export TORCH_HOME=${TORCH_HOME:-/nvmestore/ssalehi/.cache/torch}export CUDA_VISIBLE_DEVICES=${CUDA_VISIBLE_DEVICES:-0,1,2,3}export OMP_NUM_THREADS=1DATA=${DATA:-/nvmestore/ssalehi/SynthScope/GenImage}SAVE=${SAVE:-/nvmestore/ssalehi/SynthScope/models/aide}NUM_GPUS=${NUM_GPUS:-4}MICRO=${MICRO:-8} # micro-batch per GPUif [ $((256 % (NUM_GPUS * MICRO))) -ne 0 ]; thenecho "NUM_GPUS x MICRO = $((NUM_GPUS * MICRO)) must divide the effective batch 256" >&2; exit 1fiACCUM=$((256 / (NUM_GPUS * MICRO))) # effective batch 256WORKERS=${WORKERS:-5}# wandb runs offline by default (batch nodes have no login, like the other recipe scripts); LOGGER_MODE=online to sync./home/ssalehi/miniconda3/bin/conda run --no-capture-output -n SynthScope accelerate launch --multi_gpu \--num_processes $NUM_GPUS --mixed_precision no main.py \trainer@TrainerConfig=image/aide \model@ModelConfig=image/aide \dataset@DatasetConfig=image/genimage \DatasetConfig.root_dir=$DATA \DatasetConfig.train_batch_size=$MICRO \DatasetConfig.num_workers=$WORKERS \DatasetConfig.val_batch_size=16 \DatasetConfig.test_batch_size=16 \TrainerConfig.timm_cosine.grad_accum_steps=$ACCUM \TrainerConfig.save_path=$SAVE \"metrics=[real_accuracy,fake_accuracy]" \logger.name=aide \logger.mode=${LOGGER_MODE:-offline} \"logger.tags=[SynthScope,AIDE,genimage]" \"$@"
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697#!/bin/bash# CuRe (arXiv 2609.14316): the paper's three-stage training recipe (Sec. 3, 4.1-4.2, Appendix A); the official release# (github.com/manic-cui/CuRe) has inference code only, so this follows the paper. See models/image/cure/README.md.# data GenImage SD v1.4 train: 162,000 ImageNet reals + 162,000 SD v1.4 images (PNG -> JPEG q96 to match the reals)# model Perception Encoder Core L/14 @336 (facebook/PE-Core-L14-336, frozen) + LoRA on Q and V of all 24 layers# (rank 64, alpha 128, dropout 0); feature = mean of the 576 patch tokens (1024-d)# stage 1 ratio regression: x_a = (1 - a) x_r + a x_g, a ~ U(0, 1), independent real / generated endpoints; linear# ratio head + sigmoid, BCE with soft target a; AdamW lr 1e-5, weight decay 0.1 LoRA / 0.01 head, 5 epochs,# per-GPU batch 64, 2 warmup epochs then cosine to 1e-6 (main.py, conf/trainer/image/cure.yaml)# stage 2 frozen encoder; 20,000 endpoint pairs per trajectory type RF / RR / FF on {0, .2, .4, .6, .8, 1}; slopes,# trace-normalised C_F, C_M, C_S, generalised eigenproblem -> W (1024 x 128), mu (train_stages.py stage2)# stage 3 Linear(128, 2) on W^T (z - mu), dropout 0.05, CE, AdamW lr 2e-4, weight decay 0.1, batch 256, 5 epochs# (train_stages.py stage3) -> $SAVE/stage23/cure_trained.pth, the released adapter's 100 keys# batch per-GPU 64 = MICRO x ACCUM. Measured: 48 GB (A6000 / RTX 6000 Ada): MICRO 64, GRAD_CKPT=false, about 28 GiB;# 24 GB (A5000): MICRO 64 + GRAD_CKPT=true (6.3 GiB peak) or MICRO 32 x ACCUM 2 without checkpointing (14.1 GiB);# the paper does not state its GPU count (global batch = NGPU x 64)# Plain DDP with fp16 autocast + loss scaling, no gradient clipping (not the repo's DeepSpeed accelerate_config.yaml, which# clips at 1.0); the accelerate launch is pinned by an explicit# minimal config file + flags (ACC_ARGS), independent of the host's default accelerate config.# Stage 1 resumes after its last finished epoch when rerun with the same SAVE.# Stage-1 epoch: every epoch is saved (stage1/model_<k>.pth). The last epoch over-adapts to SD v1.4; the SynthScope-trained# checkpoints that partially reproduce the paper use the epoch picked by the pre-registered, non-benchmark rule of# repro/cure_stage1/epoch_select.py (epoch 0 in both runs), set with LORA=$SAVE/stage1/model_<k>.pth for stages 2-3. Optional# DDA-style training augmentation (an assumption; the paper states none): append DatasetConfig.train_augment=dda to stage 1.# See models/image/cure/README.md "Trained checkpoint".# Evaluate: python benchmark/bench_eval.py --model cure --ckpt $SAVE/stage23/cure_trained.pth --dataset wildrfset -eo pipefailexport TRITON_CACHE_DIR=${TRITON_CACHE_DIR:-/nvmestore/ssalehi/.triton}export HF_HOME=${HF_HOME:-/nvmestore/ssalehi/.cache/huggingface}export TORCH_HOME=${TORCH_HOME:-/nvmestore/ssalehi/.cache/torch}export OMP_NUM_THREADS=1DATA=${DATA:-/nvmestore/ssalehi/SynthScope/GenImage}SAVE=${SAVE:-/nvmestore/ssalehi/SynthScope/models/cure}NGPU=${NGPU:-1}MICRO=${MICRO:-64}GRAD_CKPT=${GRAD_CKPT:-true}WORKERS=${WORKERS:-8}STAGES=${STAGES:-"1 2 3"}LORA=${LORA:-} # stage-1 checkpoint for stages 2-3 (default: $SAVE/stage1/model_last.pth)PY=${PY:-/home/ssalehi/miniconda3/envs/SynthScope/bin/python}if (( 64 % MICRO != 0 )); then echo "MICRO must divide the per-GPU batch 64" >&2; exit 1; fiACCUM=$((64 / MICRO))# STEP_MULT (default 1): accumulate STEP_MULT x the per-GPU 64 per optimizer step, i.e. global batch NGPU x 64 x STEP_MULT.# Only for the stage-1 investigation's R2 run (global 512 = 2 GPUs x 64 x 4, the paper's per-GPU 64 on an assumed 8 GPUs);# the recipe default is 1 (global NGPU x 64).STEP_MULT=${STEP_MULT:-1}ACCUM=$((ACCUM * STEP_MULT))MULTI=""; (( NGPU > 1 )) && MULTI="--multi_gpu"# Every accelerate setting is explicit (a minimal config file AND flags), so a default accelerate config on the host# (DeepSpeed, dynamo, other precision) cannot change the run: single machine, no dynamo, fp16 autocast + loss scaling# (CuRe.features always autocasts to fp16).ACC_CFG=$(mktemp --suffix=.yaml)trap 'rm -f "$ACC_CFG"' EXITDIST=MULTI_GPU; (( NGPU > 1 )) || DIST="'NO'"cat > "$ACC_CFG" <<YAMLcompute_environment: LOCAL_MACHINEdistributed_type: $DISTdowncast_bf16: 'no'dynamo_config: {dynamo_backend: 'NO'}gpu_ids: allmachine_rank: 0main_training_function: mainmixed_precision: fp16num_machines: 1num_processes: $NGPUrdzv_backend: staticsame_network: trueuse_cpu: falseYAMLACC_ARGS="--config_file $ACC_CFG --num_machines 1 --dynamo_backend no --mixed_precision fp16 --num_processes $NGPU $MULTI"
if [[ " $STAGES " == *" 1 "* ]]; then "$(dirname $PY)/accelerate" launch $ACC_ARGS main.py \ trainer@TrainerConfig=image/cure \ model@ModelConfig=image/cure \ dataset@DatasetConfig=image/cure_train \ ModelConfig.training_stage=ratio \ ModelConfig.grad_checkpointing=$GRAD_CKPT \ DatasetConfig.root_dir=$DATA \ DatasetConfig.train_batch_size=$MICRO \ DatasetConfig.num_workers=$WORKERS \ TrainerConfig.timm_cosine.grad_accum_steps=$ACCUM \ TrainerConfig.save_path=$SAVE/stage1 \ "metrics=[]" \ logger.name=cure \ logger.mode=${LOGGER_MODE:-offline} \ "logger.tags=[SynthScope,CuRe,genimage_sd14]" \ "$@"fiif [[ " $STAGES " == *" 2 "* ]]; then $PY -m models.image.cure.train_stages stage2 --lora ${LORA:-$SAVE/stage1/model_last.pth} --data $DATA --out $SAVE/stage23 \ --workers $WORKERS ${STAGE2_ARGS:-}fiif [[ " $STAGES " == *" 3 "* ]]; then $PY -m models.image.cure.train_stages stage3 --lora ${LORA:-$SAVE/stage1/model_last.pth} --data $DATA --out $SAVE/stage23 \ --workers $WORKERS ${STAGE3_ARGS:-}fi63 unmodified lines6465666768697071727363 unmodified lines* Models load lazily on first request and are kept in a small LRU (`SYNTHSCOPE_MAX_RESIDENT_MODELS`,default 2) so the GPU is not exhausted by the large backbones.## Detectors (16) & helper scripts13 image (`clip`, `cnn`, `dinov2`, `dinov3`, `adapted_dino`, `safe`, `fat_former`, `co_spy`, `aide`,`spai`, `vib_net`, `npr`, `pgc`) + 3 video (`d3`, `restrav`, `stall`). Per-model held-out numbers and thecheckpoint-zoo table are in the top-level [README](../README.md#web-interface--checkpoint-zoo).| script | purpose |63 unmodified lines6465666768697071727374757663 unmodified lines* Models load lazily on first request and are kept in a small LRU (`SYNTHSCOPE_MAX_RESIDENT_MODELS`,default 2) so the GPU is not exhausted by the large backbones.## Detectors & helper scriptsThe registry (`interface/backend/registry.py`) has 36 keys: 29 image and 7 video.Image: `clip`, `cnn`, `dinov2`, `dinov3`, `adapted_dino`, `safe`, `fat_former`, `aide`, `spai`, `vib_net`,`vib_net_official`, `bfree`, `effort`, `effort_chameleon`, `moejepa`, `co_spy`, `pgc`, `cure`, `dda`, `d3qe`, `ltf`,`mirror`, `probe`, `probe_resnet`, `vina`, `omniaid`, `omniaid_v1`, `omniaid_genimage`, `npr`.Video: `vina_video`, `waverep`, `waverep_g4`, `d3`, `split`, `restrav`, `stall`. Per-model held-out numbers and thecheckpoint-zoo table are in the top-level [README](../README.md#web-interface--checkpoint-zoo).| script | purpose |
16 unmodified lines17181920212223244 unmodified lines293031323334353637383940414243444546145 unmodified lines19219319419519619719819920016 unmodified linesVAL = {# AIGCDetect is the ProGAN-trained setting (B1); we only retrained the SDv1.4 setting, so no SynthScope_train here.("aide", "AIGCDetect"): {"official": {"map": 97.94, "acc": 91.89}},# SynthScope_train = faithful native-res 5-view retrain (aide_native_v2/model_2) — reproduces the official mAP (acc is lower).("aide", "GenImage"): {"official": {"map": 97.12, "acc": 85.91}, "synthscope": {"map": 96.42, "acc": 77.87}},# ForenSynths = the paper's 11 generators (no StyleGAN2 / WhichFaceIsReal), recomputed from the per-generator entries# of {clip,cnn}_{synthscope,official}_forensynths.json; the 8-GAN subset gives clip 97.22 / 96.96, cnn 94.42 / 92.67.("clip", "ForenSynths"): {"synthscope": {"map": 92.83, "acc": 85.39}, "official": {"map": 92.33, "acc": 80.58}},4 unmodified lines("co_spy", "AIGCDetect"): {"official": {"map": 94.59, "acc": 89.25}, "synthscope": {"map": 84.91}},("co_spy", "GenImage"): {"official": {"map": 92.41}, "synthscope": {"map": 90.59, "acc": 76.23}},("co_spy", "ForenSynths"): {"official": {"map": 87.97}, "synthscope": {"map": 96.17}},# CuRe: only the official adapter exists (the training recipe is unreleased), so there is no SynthScope-trained number.("cure", "AIGIBench"): {"official": {"map": 97.0, "acc": 92.85, "auroc": 97.48}},("cure", "UniversalFakeDetect"): {"official": {"map": 99.19, "acc": 93.94}},("cure", "ForenSynths"): {"official": {"map": 94.05, "acc": 81.95}},("cure", "GenImage"): {"official": {"map": 97.3, "acc": 85.18}},("cure", "RealChain"): {"official": {"map": 87.39, "acc": 79.69, "auroc": 85.47}},("cure", "EvalGEN"): {"official": {"map": 99.86, "acc": 98.14, "auroc": 99.66}},("cure", "SynthWildX"): {"official": {"map": 95.61, "acc": 92.69, "auroc": 96.5}},("cure", "WildRF"): {"official": {"map": 99.13, "acc": 95.89, "auroc": 99.14}},("cure", "BFree-Online"): {"official": {"map": 99.06, "acc": 91.64, "auroc": 98.08}},("cure", "RRDataset"): {"official": {"map": 90.4, "acc": 82.04, "auroc": 88.88}},("cure", "AIGCDetect"): {"official": {"map": 98.08, "acc": 89.3, "auroc": 98.02}},# DDA: synthscope = trained in SynthScope with the official recipe (experiments/image/dda.sh; job 267042, eval 267832).("dda", "SynthWildX"): {"official": {"map": 96.47, "acc": 90.8, "auroc": 96.4}, "synthscope": {"map": 96.99, "acc": 88.0, "auroc": 96.88}},("dda", "WildRF"): {"official": {"map": 96.76, "acc": 90.2, "auroc": 96.14}, "synthscope": {"map": 97.83, "acc": 90.56, "auroc": 97.62}},145 unmodified lines("vina", "WildRF"): {"official": {"map": 99.41, "acc": 96.12, "auroc": 99.25}},("vina", "AIGIBench"): {"official": {"map": 97.33, "acc": 92.72, "auroc": 97.6}},("vina", "RRDataset"): {"official": {"map": 92.77, "acc": 82.89, "auroc": 91.69}},("stall", "GenVideo"): {"synthscope": {"map": 82.38, "auroc": 83.51, "acc": 56.88}},("stall", "VideoFeedback"): {"synthscope": {"map": 83.07, "auroc": 85.1, "acc": 62.12}},("stall", "ComGenVid"): {"synthscope": {"map": 82.59, "auroc": 84.0, "acc": 57.34}},# synthscope = trained in SynthScope with the reconstructed recipe at native resolution (experiments/image/vib_net.sh;# job 267846, eval 267928): 15 generators (7 GenImage + 8 ForenSynths GANs), registry vib_net_official.("vib_net", "Diffusion-source (SDv1.4-trained)"): {"synthscope": {"map": 94.08, "acc": 85.22}},16 unmodified lines17181920212223242526274 unmodified lines323334353637383940414243444546474849505152145 unmodified lines19819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924016 unmodified linesVAL = {# AIGCDetect is the ProGAN-trained setting (B1); we only retrained the SDv1.4 setting, so no SynthScope_train here.("aide", "AIGCDetect"): {"official": {"map": 97.94, "acc": 91.89}},# SynthScope_train = the official AIDE recipe in SynthScope (experiments/image/aide.sh; train job 281041, model_best = epoch 4,# eval DAS6 job 66956, tag aide_trained_genimage8: the full GenImage_full/test, the same data as the official row). Below the# paper (acc -6.15) and the official weights (mAP -3.22); the previous native-res retrain (aide_native_v2/model_2, 96.42 / 77.87 on# 300 images per class) had the higher mAP and the lower accuracy.("aide", "GenImage"): {"official": {"map": 97.12, "acc": 85.91}, "synthscope": {"map": 93.9, "acc": 80.73, "auroc": 91.66}},# ForenSynths = the paper's 11 generators (no StyleGAN2 / WhichFaceIsReal), recomputed from the per-generator entries# of {clip,cnn}_{synthscope,official}_forensynths.json; the 8-GAN subset gives clip 97.22 / 96.96, cnn 94.42 / 92.67.("clip", "ForenSynths"): {"synthscope": {"map": 92.83, "acc": 85.39}, "official": {"map": 92.33, "acc": 80.58}},4 unmodified lines("co_spy", "AIGCDetect"): {"official": {"map": 94.59, "acc": 89.25}, "synthscope": {"map": 84.91}},("co_spy", "GenImage"): {"official": {"map": 92.41}, "synthscope": {"map": 90.59, "acc": 76.23}},("co_spy", "ForenSynths"): {"official": {"map": 87.97}, "synthscope": {"map": 96.17}},# CuRe: official = the released adapter (served). synthscope = r3e0, the best SynthScope-trained checkpoint by the pre-registered# non-benchmark selection rule (the paper's recipe + DDA-style augmentation, stage-1 epoch 0; jobs 67199 / 67200, tags# cure_trained_r3e0_*): partially reproduces the paper (4 of 8 comparable benchmarks; mean acc 85.15 vs 90.10). The recipe's# last epoch (tags cure_trained_*, job 66721) and the other runs are in models/image/cure/README.md.("cure", "AIGIBench"): {"official": {"map": 97.0, "acc": 92.85, "auroc": 97.48}, "synthscope": {"map": 96.72, "acc": 91.12, "auroc": 97.1}},("cure", "UniversalFakeDetect"): {"official": {"map": 99.19, "acc": 93.94}, "synthscope": {"map": 98.73, "acc": 93.89, "auroc": 98.31}},("cure", "ForenSynths"): {"official": {"map": 94.05, "acc": 81.95}, "synthscope": {"map": 97.22, "acc": 89.36, "auroc": 96.58}},("cure", "GenImage"): {"official": {"map": 97.3, "acc": 85.18}, "synthscope": {"map": 97.56, "acc": 86.22, "auroc": 97.59}},("cure", "RealChain"): {"official": {"map": 87.39, "acc": 79.69, "auroc": 85.47}, "synthscope": {"map": 83.67, "acc": 72.75, "auroc": 84.7}},("cure", "EvalGEN"): {"official": {"map": 99.86, "acc": 98.14, "auroc": 99.66}, "synthscope": {"map": 99.47, "acc": 93.32, "auroc": 98.85}},("cure", "SynthWildX"): {"official": {"map": 95.61, "acc": 92.69, "auroc": 96.5}, "synthscope": {"map": 97.12, "acc": 91.76, "auroc": 97.09}},("cure", "WildRF"): {"official": {"map": 99.13, "acc": 95.89, "auroc": 99.14}, "synthscope": {"map": 99.3, "acc": 95.58, "auroc": 99.25}},("cure", "BFree-Online"): {"official": {"map": 99.06, "acc": 91.64, "auroc": 98.08}, "synthscope": {"map": 89.48, "acc": 71.19, "auroc": 79.51}},("cure", "RRDataset"): {"official": {"map": 90.4, "acc": 82.04, "auroc": 88.88}, "synthscope": {"map": 84.91, "acc": 73.46, "auroc": 85.32}},("cure", "AIGCDetect"): {"official": {"map": 98.08, "acc": 89.3, "auroc": 98.02}, "synthscope": {"map": 98.59, "acc": 92.01, "auroc": 98.38}},# DDA: synthscope = trained in SynthScope with the official recipe (experiments/image/dda.sh; job 267042, eval 267832).("dda", "SynthWildX"): {"official": {"map": 96.47, "acc": 90.8, "auroc": 96.4}, "synthscope": {"map": 96.99, "acc": 88.0, "auroc": 96.88}},("dda", "WildRF"): {"official": {"map": 96.76, "acc": 90.2, "auroc": 96.14}, "synthscope": {"map": 97.83, "acc": 90.56, "auroc": 97.62}},145 unmodified lines("vina", "WildRF"): {"official": {"map": 99.41, "acc": 96.12, "auroc": 99.25}},("vina", "AIGIBench"): {"official": {"map": 97.33, "acc": 92.72, "auroc": 97.6}},("vina", "RRDataset"): {"official": {"map": 92.77, "acc": 82.89, "auroc": 91.69}},# PROBE (ICML'26): the two official checkpoints (probe = DINOv2 ViT-L/14 with registers, probe_resnet = ResNet-50); no# SynthScope-trained number (the training code is not released). acc / mAP / mauroc = bench_eval means over the paper's# subsets (repro/bench_results/<key>_<benchmark>.json; acc = mean balanced accuracy at 0.5 = the paper's metric).# GenImage = the full val split (100,000 images) with all fakes JPEG q96 as in the paper. Synthbuster uses 5000 MSCOCO# reals, NOT the paper's RAISE-1k (the spec marks it "reference": not like-for-like). AIGI-Bench = CommunityAI + SocialRF# only. Chameleon and AIGI-Quality-Paradox were not run (no loader). Jobs DAS6 66753, 66755, 66790.("probe", "GenImage (8 subsets"): {"official": {"map": 99.77, "acc": 97.47, "auroc": 99.8}},("probe", "Synthbuster"): {"official": {"map": 99.64, "acc": 98.2, "auroc": 99.93}},("probe", "SynthWildX"): {"official": {"map": 98.8, "acc": 97.3, "auroc": 99.18}},("probe", "WildRF"): {"official": {"map": 99.36, "acc": 96.92, "auroc": 99.26}},("probe", "AIGI-Bench"): {"official": {"map": 96.46, "acc": 89.88, "auroc": 95.88}},("probe_resnet", "GenImage (8 subsets"): {"official": {"map": 86.69, "acc": 78.38, "auroc": 84.81}},("probe_resnet", "Synthbuster"): {"official": {"map": 85.23, "acc": 83.75, "auroc": 95.88}},("probe_resnet", "SynthWildX"): {"official": {"map": 83.88, "acc": 75.2, "auroc": 82.8}},("probe_resnet", "WildRF"): {"official": {"map": 89.45, "acc": 81.63, "auroc": 85.76}},("probe_resnet", "AIGI-Bench"): {"official": {"map": 79.8, "acc": 70.44, "auroc": 77.55}},("stall", "GenVideo"): {"synthscope": {"map": 82.38, "auroc": 83.51, "acc": 56.88}},("stall", "VideoFeedback"): {"synthscope": {"map": 83.07, "auroc": 85.1, "acc": 62.12}},("stall", "ComGenVid"): {"synthscope": {"map": 82.59, "auroc": 84.0, "acc": 57.34}},# WaveRep (NeurIPS'25): the two official checkpoints (waverep = G1, the paper's single-generator model; waverep_g4 = four# generators); no SynthScope-trained number (no training code). acc / mAP / mauroc = bench_eval_video means (repro/bench_results/# <key>_<set>.json; acc = balanced accuracy at logit 0 = the paper's metric, mAP = AP with fake positive). The "paper's 8" row is the# mean over the paper's 8 GenVideo columns (Crafter, Gen2, HotShot, LaVie, ModelScope, MorphStudio, Show-1, MoonValley) of# <key>_genvideo_full.json per_generator acc / auroc; the other rows are zero-shot references (no paper number).# Jobs: IVI 285376_0 / 285390_3-4 / 285389_2 / 285886_2, DAS6 67328 / 67404, aggregation 286053 / 286059.("waverep", "GenVideo-Val, the paper's 8"): {"official": {"acc": 90.3, "auroc": 95.73}},("waverep", "GenVideo-Val full"): {"official": {"map": 79.85, "acc": 86.87, "auroc": 92.13}},("waverep", "GenVideo-Val --limit"): {"official": {"map": 89.81, "acc": 86.62, "auroc": 92.09}},("waverep", "VideoPhy"): {"official": {"map": 93.21, "acc": 90.0, "auroc": 96.54}},("waverep", "VidProM"): {"official": {"map": 98.11, "acc": 89.85, "auroc": 98.06}},("waverep", "EvalCrafter"): {"official": {"map": 96.93, "acc": 92.84, "auroc": 97.17}},("waverep_g4", "GenVideo-Val, the paper's 8"): {"official": {"acc": 96.3, "auroc": 99.05}},("waverep_g4", "GenVideo-Val full"): {"official": {"map": 88.88, "acc": 93.28, "auroc": 96.69}},("waverep_g4", "GenVideo-Val --limit"): {"official": {"map": 94.47, "acc": 92.65, "auroc": 96.53}},("waverep_g4", "VideoPhy"): {"official": {"map": 98.2, "acc": 95.73, "auroc": 99.29}},("waverep_g4", "VidProM"): {"official": {"map": 99.29, "acc": 95.8, "auroc": 99.25}},("waverep_g4", "EvalCrafter"): {"official": {"map": 99.19, "acc": 96.55, "auroc": 99.29}},# synthscope = trained in SynthScope with the reconstructed recipe at native resolution (experiments/image/vib_net.sh;# job 267846, eval 267928): 15 generators (7 GenImage + 8 ForenSynths GANs), registry vib_net_official.("vib_net", "Diffusion-source (SDv1.4-trained)"): {"synthscope": {"map": 94.08, "acc": 85.22}},
17 unmodified lines18192021222324108 unmodified lines1331341351361371386 unmodified lines14514614714814915026 unmodified lines17717817918018118226 unmodified lines209210211212213214215216217160 unmodified lines3783793803813823833843853863871 unmodified line38939039139239339439515 unmodified lines41141241341441541641741841918 unmodified lines4384394404414424434444454464475 unmodified lines45345445545645745845946017 unmodified linesfrom PIL import Imagefrom safetensors.torch import load_file as load_safetensorsfrom . import configfrom .registry import ModelSpec, get_spec, input_notefrom . import media108 unmodified linesif model_type == "vina":from models.image.vina.vina import SynthScopeVINAModelreturn SynthScopeVINAModel(cfg)if model_type == "stall":from models.video.stall.stall import SynthScopeSTALLModelreturn SynthScopeSTALLModel(cfg)6 unmodified linesif model_type == "restrav":from models.video.restrav.restrav import SynthScopeReStraVModelreturn SynthScopeReStraVModel(cfg)if model_type == "cnn":from models.image.cnn_detection.cnn_detection import SynthScopeCNNModelreturn SynthScopeCNNModel(cfg)26 unmodified linessd = raw["model"] if isinstance(raw, dict) and "model" in raw else rawif spec.remap is not None:sd = spec.remap(sd)missing, unexpected = model.load_state_dict(sd, strict=False)# Buffers that are legitimately reconstructed in __init__ / not in official dumps.benign = {"clip_mean", "clip_std", "imnet_mean", "imnet_std"}26 unmodified linesreturn (f"loaded {len(sd)} tensors from {path.name} "f"(missing={len(real_missing)}, unexpected={len(unexpected)})")class Engine:"""Lazily builds, caches, and runs the detectors."""160 unmodified linesreturn None@staticmethoddef _model_input_data_url(spec: ModelSpec, x: torch.Tensor, max_side: int = 1280) -> str:"""The image exactly as the network receives it (after this detector's preprocessing), as a PNG data URL.Normalization is undone for display; multi-view inputs are laid out side by side (up to 5 views, e.g. AIDE)or in a near-square grid (LTF has one view per tile, up to dozens)."""t = x[0].detach().float().cpu()norm = spec.transform.normalize_step()if norm is not None:1 unmodified lineelif spec.key == "cure": # CuRe maps pixels to (x - 127.5) / 127.5t = t * 0.5 + 0.5if t.dim() == 4:cols = len(t) if len(t) <= 5 else math.ceil(math.sqrt(len(t)))pad = -len(t) % colsif pad:t = torch.cat([t, torch.zeros(pad, *t.shape[1:])])15 unmodified linesres = self._result(spec, p, time.time() - t0)res["orig_size"] = [pil.width, pil.height]res["input_size"] = [int(x.shape[-1]), int(x.shape[-2])] # what the network actually receivedres["input_note"] = input_note(spec)try:res["input_image"] = self._model_input_data_url(spec, x)except Exception: # display-only: never fail a prediction over itpassamap = self._interpret_map(model, spec, x, pil)18 unmodified linesreturn resdef video_clip(self, spec: ModelSpec, path) -> torch.Tensor:"""Decode and normalize a clip exactly as ``spec`` prescribes: ``[T, 3, H, W]``."""if spec.video_sampler == "ffmpeg_fps_center": # VINA: ffmpeg JPEG frames, central window, image transformframes = media.ffmpeg_fps_frames(path, fps=spec.fps, num_frames=spec.num_frames)return torch.stack([spec.transform(f) for f in frames])clip = media.video_clip_tensor(path, num_frames=spec.num_frames, fps=spec.fps, frame_size=spec.frame_size,window_center=spec.window_center, interp=spec.resize_interp,5 unmodified linesmean, std = spec.video_normreturn (clip - torch.tensor(mean).view(1, 3, 1, 1)) / torch.tensor(std).view(1, 3, 1, 1)def predict_video_clip(self, spec: ModelSpec, path) -> dict:"""Run a native *video* detector on a decoded clip."""model = self._get_model(spec)clip = self.video_clip(spec, path)t0 = time.time()17 unmodified lines181920212223242526108 unmodified lines1351361371381391401411421431441451466 unmodified lines15315415515615715815916016126 unmodified lines18818919019119219319419519619719826 unmodified lines225226227228229230231232233234235236237238239240241242243244245246247248160 unmodified lines4094104114124134144154164174184191 unmodified line42142242342442542642715 unmodified lines44344444544644744844945045145245345445545645718 unmodified lines4764774784794804814824834844854864874884894904914924934945 unmodified lines50050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253317 unmodified linesfrom PIL import Imagefrom safetensors.torch import load_file as load_safetensorsfrom models.image.probe.preprocess import ProbePad, SlidingPatchesfrom . import configfrom .hf_compat import translate_hf_keysfrom .registry import ModelSpec, get_spec, input_notefrom . import media108 unmodified linesif model_type == "vina":from models.image.vina.vina import SynthScopeVINAModelreturn SynthScopeVINAModel(cfg)if model_type == "probe":from models.image.probe.probe import SynthScopePROBEModelreturn SynthScopePROBEModel(cfg)if model_type == "probe_resnet":from models.image.probe.probe import SynthScopePROBEResNetModelreturn SynthScopePROBEResNetModel(cfg)if model_type == "stall":from models.video.stall.stall import SynthScopeSTALLModelreturn SynthScopeSTALLModel(cfg)6 unmodified linesif model_type == "restrav":from models.video.restrav.restrav import SynthScopeReStraVModelreturn SynthScopeReStraVModel(cfg)if model_type == "waverep":from models.video.waverep.waverep import SynthScopeWaveRepModelreturn SynthScopeWaveRepModel(cfg)if model_type == "cnn":from models.image.cnn_detection.cnn_detection import SynthScopeCNNModelreturn SynthScopeCNNModel(cfg)26 unmodified linessd = raw["model"] if isinstance(raw, dict) and "model" in raw else rawif spec.remap is not None:sd = spec.remap(sd)# A checkpoint that holds a transformers backbone carries the parameter names of the release that saved it; map them# onto this release's names when the rename is exact (hf_compat.HF_RENAMES), else leave them for the checks below.sd, hf_note = translate_hf_keys(sd, model.state_dict())if hf_note:logger.info("%s: transformers parameter names translated (%s)", spec.key, hf_note)missing, unexpected = model.load_state_dict(sd, strict=False)# Buffers that are legitimately reconstructed in __init__ / not in official dumps.benign = {"clip_mean", "clip_std", "imnet_mean", "imnet_std"}26 unmodified linesreturn (f"loaded {len(sd)} tensors from {path.name} "f"(missing={len(real_missing)}, unexpected={len(unexpected)})"+ (f" [transformers key names translated, {hf_note}]" if hf_note else ""))def patch_layout(spec: ModelSpec, pil: Image.Image, num_patches: int):"""For a detector that scores a bag of non-overlapping patches (PROBE: ``ProbePad`` then ``SlidingPatches``): thepadded image size ``(width, height)`` and the patch grid ``(rows, cols)`` the bag came from, or ``None`` when thetransform is not of that kind or the grid does not hold ``num_patches`` patches."""steps = spec.transform.transforms if spec.transform is not None else []pads = [t for t in steps if isinstance(t, ProbePad)]cuts = [t for t in steps if isinstance(t, SlidingPatches)]if len(pads) != 1 or len(cuts) != 1:return Nonewidth, height = pads[0](pil).sizerows, cols = height // cuts[0].size, width // cuts[0].sizereturn ((width, height), (rows, cols)) if rows * cols == num_patches else Noneclass Engine:"""Lazily builds, caches, and runs the detectors."""160 unmodified linesreturn None@staticmethoddef _model_input_data_url(spec: ModelSpec, x: torch.Tensor, max_side: int = 1280, cols: int | None = None) -> str:"""The image exactly as the network receives it (after this detector's preprocessing), as a PNG data URL.Normalization is undone for display; multi-view inputs are laid out side by side (up to 5 views, e.g. AIDE)or in a near-square grid (LTF has one view per tile, up to dozens). ``cols`` fixes the number of columns of amulti-view layout (PROBE: the patches' real grid)."""t = x[0].detach().float().cpu()norm = spec.transform.normalize_step()if norm is not None:1 unmodified lineelif spec.key == "cure": # CuRe maps pixels to (x - 127.5) / 127.5t = t * 0.5 + 0.5if t.dim() == 4:cols = cols or (len(t) if len(t) <= 5 else math.ceil(math.sqrt(len(t))))pad = -len(t) % colsif pad:t = torch.cat([t, torch.zeros(pad, *t.shape[1:])])15 unmodified linesres = self._result(spec, p, time.time() - t0)res["orig_size"] = [pil.width, pil.height]res["input_size"] = [int(x.shape[-1]), int(x.shape[-2])] # what the network actually receivedlayout = patch_layout(spec, pil, int(x.shape[1])) if x.dim() == 5 else Noneif layout is not None: # a patch bag: report the padded image and its patch grid, not one patch's size(width, height), (rows, cols) = layoutres["input_size"] = [width, height]res["input_grid"] = [rows, cols]res["input_patches"] = rows * colsres["input_note"] = input_note(spec)try:res["input_image"] = self._model_input_data_url(spec, x, cols=layout[1][1] if layout else None)except Exception: # display-only: never fail a prediction over itpassamap = self._interpret_map(model, spec, x, pil)18 unmodified linesreturn resdef video_clip(self, spec: ModelSpec, path) -> torch.Tensor:"""Decode and normalize a clip exactly as ``spec`` prescribes: ``[T, 3, H, W]``.For video_sampler "cv2_frames" (WaveRep) this materializes every selected frame at 504x504 float (~3 MB each):with ``num_frames=0`` (the official demo's default, every frame) a long video needs that much memory per frame;scoring goes through ``video_frame_logits`` instead, which streams."""if spec.video_sampler == "ffmpeg_fps_center": # VINA: ffmpeg JPEG frames, central window, image transformframes = media.ffmpeg_fps_frames(path, fps=spec.fps, num_frames=spec.num_frames)return torch.stack([spec.transform(f) for f in frames])if spec.video_sampler == "cv2_frames": # WaveRep: the first num_frames (0: all) OpenCV framesframes = [spec.transform(f) for f in media.cv2_frames(path, limit=spec.num_frames or None)]if not frames:raise media.VideoDecodeError("Could not decode any frames from the video.")return torch.stack(frames)clip = media.video_clip_tensor(path, num_frames=spec.num_frames, fps=spec.fps, frame_size=spec.frame_size,window_center=spec.window_center, interp=spec.resize_interp,5 unmodified linesmean, std = spec.video_normreturn (clip - torch.tensor(mean).view(1, 3, 1, 1)) / torch.tensor(std).view(1, 3, 1, 1)@torch.no_grad()def video_frame_logits(self, spec: ModelSpec, path) -> torch.Tensor:"""The per-frame logits [T] of a frame-level video detector (video_sampler "cv2_frames", WaveRep): the framesare read, transformed and scored ``frame_batch`` at a time, so a long video is never held in memory at once."""model = self._get_model(spec)batch, logits = [], []for frame in media.cv2_frames(path, limit=spec.num_frames or None):batch.append(spec.transform(frame))if len(batch) == model.frame_batch:logits.append(model.frame_logits(torch.stack(batch).to(self.device)).float().cpu())batch = []if batch:logits.append(model.frame_logits(torch.stack(batch).to(self.device)).float().cpu())if not logits:raise media.VideoDecodeError("Could not decode any frames from the video.")return torch.cat(logits)def predict_video_clip(self, spec: ModelSpec, path) -> dict:"""Run a native *video* detector on a decoded clip."""if spec.video_sampler == "cv2_frames": # frame-level: P(fake) = sigmoid(mean frame logit), officialself._get_model(spec) # load first: elapsed covers decoding and scoring onlyt0 = time.time()logits = self.video_frame_logits(spec, path)logit = logits.double().mean() # the official mean (pandas, float64) of the float32 logitsres = self._result(spec, float(torch.sigmoid(logit)), time.time() - t0) # official: scipy expitres["num_frames"] = int(logits.numel())res["logit"] = round(float(logit), 6)return resmodel = self._get_model(spec)clip = self.video_clip(spec, path)t0 = time.time()
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""Version-tolerant parameter names for checkpoints that hold a Hugging Face ``transformers`` backbone.
A checkpoint that stores a whole ``transformers`` module (PGC's DINOv2-L, ...) carries the parameter names of the``transformers`` release it was saved with. A later release may rename a module, and then a strict load fails on therenamed tensors (``missing=[...q_proj...] unexpected=[...attention.query...]``) although the weights are identical.
``translate_hf_keys`` maps such a state dict onto the model's names, in either direction (an older checkpoint into anewer model, or a newer checkpoint into an older model), and only when the rename is exact: every renamed key must landon a model key that the state dict does not already have, with the same shape. Anything else is returned untouched, soa real mismatch still reaches the loader's strict check."""from __future__ import annotations
# (older name, newer name) of one parameter-path fragment. Every rule below was derived by building the model under# both releases and matching the keys one-to-one by shape (transformers 5.5.4 and 5.22.2 are the two that were compared).HF_RENAMES: tuple[tuple[str, str], ...] = ( # Dinov2Model (DINOv2 / PGC): attention.attention.{query,key,value} and attention.output.dense (transformers # <= 5.5.4) became attention.{q,k,v,o}_proj (5.22.2); 192 keys for DINOv2-L, all other keys unchanged. (".attention.attention.query.", ".attention.q_proj."), (".attention.attention.key.", ".attention.k_proj."), (".attention.attention.value.", ".attention.v_proj."), (".attention.output.dense.", ".attention.o_proj."),)
def _rename(key: str, rules: tuple[tuple[str, str], ...]) -> str: """Apply the first rule whose fragment occurs in ``key`` (the fragments are disjoint, so at most one does).""" for old, new in rules: if old in key: return key.replace(old, new, 1) return key
def translate_hf_keys(sd: dict, model_state: dict) -> tuple[dict, str]: """Rename the ``transformers`` parameter names of ``sd`` that ``model_state`` does not know, when a rule of ``HF_RENAMES`` maps them exactly onto it.
``model_state`` is the model's ``state_dict()``. Returns ``(state_dict, note)``: ``note`` says which direction was applied and how many keys moved (empty when ``sd`` is returned unchanged). A direction is applied only if every key it changes lands on a model key that is not already in ``sd`` (no collisions) and has the same shape. """ unknown = [k for k in sd if k not in model_state] if not unknown: return sd, "" for label, rules in ( ("older -> newer", HF_RENAMES), ("newer -> older", tuple((new, old) for old, new in HF_RENAMES)), ): moved = {k: _rename(k, rules) for k in unknown} moved = {k: new for k, new in moved.items() if new != k} if not moved: continue targets = list(moved.values()) exact = ( len(set(targets)) == len(targets) and all(new in model_state and new not in sd for new in targets) and all( hasattr(sd[k], "shape") and tuple(sd[k].shape) == tuple(model_state[new].shape) for k, new in moved.items() ) ) if exact: return {moved.get(k, k): v for k, v in sd.items()}, f"{label}: renamed {len(moved)} key(s)" return sd, ""
__all__ = ["HF_RENAMES", "translate_hf_keys"]11 unmodified lines12131415161710 unmodified lines28293031323347 unmodified lines818283848586875 unmodified lines9394959697989942 unmodified lines1421431441451461471482 unmodified lines1511521531541551566 unmodified lines16316416516616716816911 unmodified linesimport tempfilefrom pathlib import Pathimport numpy as npimport torchfrom PIL import Image, ImageFile10 unmodified linesfrom dataset import sample_video_frames # noqa: E402from models.image.cure.preprocess import SRC_FORMAT_KEY # noqa: E402IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".jfif", ".png", ".webp", ".bmp", ".gif", ".tif", ".tiff"}VIDEO_EXTENSIONS = {".mp4", ".avi", ".mov", ".mkv", ".webm", ".m4v"}47 unmodified linesreader = decord.VideoReader(str(path), ctx=decord.cpu(0))n_src = len(reader)if n_src == 0:raise ValueError("Could not decode any frames from the video.")n = max(1, min(num_frames, n_src))indices = np.linspace(0, n_src - 1, num=n)indices = np.clip(np.rint(indices).astype(np.int64), 0, n_src - 1).tolist()5 unmodified linesexcept Exception:continueif not frames:raise ValueError("Could not decode any frames from the video.")return frames42 unmodified linesraise ValueError(f"ffmpeg did not finish within {timeout:g} s for this video.") from eids = sorted(int(p.stem) for p in Path(tmp).glob("*.jpg") if p.stem.isdigit())if not ids:raise ValueError("ffmpeg wrote no frames for this video.")if len(ids) >= num_frames:start = (len(ids) - num_frames) // 2ids = ids[start:start + num_frames]2 unmodified linesreturn [open_rgb(Path(tmp) / f"{i}.jpg") for i in ids]def thumbnail_bytes(path: str | Path, modality: str, size: int = 256) -> bytes:"""A small JPEG thumbnail for the dataset explorer grid.6 unmodified linesreader = decord.VideoReader(str(path), ctx=decord.cpu(0))n = len(reader)if n == 0:raise ValueError("Could not decode any frames from the video.")arr = reader[n // 2].asnumpy() # [H,W,3] uint8, middle frameimg = Image.fromarray(arr).convert("RGB")else:11 unmodified lines1213141516171810 unmodified lines293031323334353637383947 unmodified lines878889909192935 unmodified lines9910010110210310410542 unmodified lines1481491501511521531542 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931946 unmodified lines20120220320420520620711 unmodified linesimport tempfilefrom pathlib import Pathimport cv2import numpy as npimport torchfrom PIL import Image, ImageFile10 unmodified linesfrom dataset import sample_video_frames # noqa: E402from models.image.cure.preprocess import SRC_FORMAT_KEY # noqa: E402class VideoDecodeError(ValueError):"""The video file yields no decodable frame (corrupt / empty). A ValueError, so every existing handler still catchesit; benchmark/bench_eval_video.py counts and caches only these as failed-to-decode videos."""IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".jfif", ".png", ".webp", ".bmp", ".gif", ".tif", ".tiff"}VIDEO_EXTENSIONS = {".mp4", ".avi", ".mov", ".mkv", ".webm", ".m4v"}47 unmodified linesreader = decord.VideoReader(str(path), ctx=decord.cpu(0))n_src = len(reader)if n_src == 0:raise VideoDecodeError("Could not decode any frames from the video.")n = max(1, min(num_frames, n_src))indices = np.linspace(0, n_src - 1, num=n)indices = np.clip(np.rint(indices).astype(np.int64), 0, n_src - 1).tolist()5 unmodified linesexcept Exception:continueif not frames:raise VideoDecodeError("Could not decode any frames from the video.")return frames42 unmodified linesraise ValueError(f"ffmpeg did not finish within {timeout:g} s for this video.") from eids = sorted(int(p.stem) for p in Path(tmp).glob("*.jpg") if p.stem.isdigit())if not ids:raise VideoDecodeError("ffmpeg wrote no frames for this video.")if len(ids) >= num_frames:start = (len(ids) - num_frames) // 2ids = ids[start:start + num_frames]2 unmodified linesreturn [open_rgb(Path(tmp) / f"{i}.jpg") for i in ids]def cv2_frames(path: str | Path, limit: int | None = None):"""WaveRep's official frame reader (demo/utils.py ``ReadVideoIteratorCV``, vendored inmodels/video/waverep/official_utils.py): every frame OpenCV's ``VideoCapture`` decodes, in order, converted from BGRto RGB, as PIL images; reading stops at the first failed read, and after ``limit`` frames when it is set (the demo's``--limit``). A generator, so a long video is never held in memory at once.Errors (raised when the generator is first advanced): a path that does not exist is a ``FileNotFoundError`` and afile OpenCV cannot open an ``OSError``; both are I/O problems, not a verdict on the video, so callers do not cachethem as decode failures. An existing but empty (0-byte) file is a ``VideoDecodeError``, as is a file that opens butdecodes no frame (raised by the caller, which sees the empty iterator)."""path = str(path)if not os.path.exists(path):raise FileNotFoundError(f"Video file not found: {path}")if os.path.getsize(path) == 0:raise VideoDecodeError("The video file is empty (0 bytes).")cap = cv2.VideoCapture(path)try:if not cap.isOpened():raise OSError(f"OpenCV could not open the video file: {path}")idx = 0while cap.isOpened():ret, frame = cap.read()if not ret:breakyield Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))idx = idx + 1if limit and idx >= limit:breakfinally:cap.release()def thumbnail_bytes(path: str | Path, modality: str, size: int = 256) -> bytes:"""A small JPEG thumbnail for the dataset explorer grid.6 unmodified linesreader = decord.VideoReader(str(path), ctx=decord.cpu(0))n = len(reader)if n == 0:raise VideoDecodeError("Could not decode any frames from the video.")arr = reader[n // 2].asnumpy() # [H,W,3] uint8, middle frameimg = Image.fromarray(arr).convert("RGB")else:
49 unmodified lines50515253545556575857 unmodified lines11611711811912012138 unmodified lines16016116216316416510 unmodified lines176177178179180181237 unmodified lines41942042142242342422 unmodified lines447448449450451452114 unmodified lines56756856957057157212 unmodified lines58558658758858959049 unmodified linesdef remap_aide(sd: dict) -> dict:"""Official AIDE checkpoint -> SynthScopeAIDEModel. The SynthScope class now wraps the GENUINE arch as``self.net`` (key-for-key identical to the official ``AIDE_Model``), so we just strip anyDataParallel ``module.`` prefix and add the ``net.`` prefix; every official key loads strict."""return {("net." + (k[len("module."):] if k.startswith("module.") else k)): vfor k, v in sd.items()}def remap_npr(sd: dict) -> dict:57 unmodified linesreturn {k.replace("module.", ""): v for k, v in sd.items()}def remap_pgc(sd: dict) -> dict:"""Official PGC checkpoint -> SynthScopePGCModel: the official ``PGCNetwork`` keeps the DINOv2 backbone inside its``RgbStream`` wrapper (``rgb_stream.backbone.*``); the SynthScope class holds it as ``self.backbone``. Strip the38 unmodified linesbgr: bool = False # feed BGR channels (D3's official reader never converts cv2's BGR)# "ffmpeg_fps_center" (VINA): ffmpeg writes JPEG frames at ``fps``, the central ``num_frames`` are read back and# each goes through ``transform`` (the image eval preprocessing) instead of the clip settings above.video_sampler: str = ""video_prob: str = "softmax" # video output -> P(fake): softmax[:, 1] of [1, 2] logits, or "sigmoid"notes: str = ""10 unmodified linesinterpret: str = ""remap: Optional[Callable[[dict], dict]] = field(default=None, repr=False)# ---------------------------------------------------------------------------# The registry.237 unmodified lines"token give the score. Uses the OFFICIAL checkpoint. PNG/BMP inputs get a JPEG q96 round trip (the paper's ""format-aligned inputs), so use the registered transform. Runs fp32, the official default.",))# VINA: one model for images and videos. `vina` scores images (and, like every image detector, sampled frames of a video# with the mean P(fake)); `vina_video` is the official video protocol, so the paper's video benchmarks run through it._VINA_NOTES = ("DINOv3 ViT-L/16 fine-tuned end to end with a linear head, trained on images and video frames together "22 unmodified linesnotes=_VINA_NOTES + "Videos: the official protocol - ffmpeg writes the clip as JPEG frames at 2 fps and the ""central frame is scored with the image preprocessing (needs ffmpeg).",))# OmniAID's official eval preprocessing: v2 resizes straight to 336 (data/datasets.py); the v1-era releases used a# double resize (512x512, then 336x336) - the commented-out pipeline that the official code says to use for v1 weights.for _key, _name, _ckpt, _note in [114 unmodified lines"ltf": ("Native-res 224 tiles + global view", "The image is cut into 224×224 tiles at its own resolution (no ""scaling; edge tiles are aligned to the border, a side under 224 px is padded with black), plus one view of ""the whole image resized to 224 and center-cropped."),"vina": ("Resize + center-crop 256 (bicubic)", "The shorter side is scaled to 256 px (bicubic) and the central ""256×256 square is used. The aspect ratio is kept; anything outside the square is not seen by the ""detector."),12 unmodified linesf"them {'is' if one else 'are'} scored like an image: the shorter side is scaled to "f"{spec.frame_size} px (bicubic) and the central {spec.frame_size}×{spec.frame_size} ""square is used. This matches the paper's evaluation."}if spec.modality == "video":crop = f", after trimming {int(spec.edge_crop * 100)}% off every edge" if spec.edge_crop else ""return {"label": f"{spec.num_frames} sampled frames",49 unmodified lines505152535455565758596061626357 unmodified lines12112212312412512612712812913013113213313413513613713813914014114238 unmodified lines18118218318418518618718810 unmodified lines199200201202203204205206207208209237 unmodified lines44744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348422 unmodified lines507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538114 unmodified lines65365465565665765865966066166266366466566666712 unmodified lines68068168268368468568668768868969069169249 unmodified linesdef remap_aide(sd: dict) -> dict:"""Official AIDE checkpoint -> SynthScopeAIDEModel. The SynthScope class now wraps the GENUINE arch as``self.net`` (key-for-key identical to the official ``AIDE_Model``), so we just strip anyDataParallel ``module.`` prefix and add the ``net.`` prefix; every official key loads strict. A SynthScope-TRAINEDcheckpoint (the trainer saves the model's own state dict) already carries ``net.`` and keeps it, so``bench_eval --model aide --ckpt <trained>`` loads it; no official key starts with ``net.``."""out = {}for k, v in sd.items():k = k[len("module."):] if k.startswith("module.") else kout[k if k.startswith("net.") else "net." + k] = vreturn outdef remap_npr(sd: dict) -> dict:57 unmodified linesreturn {k.replace("module.", ""): v for k, v in sd.items()}def remap_waverep(sd: dict) -> dict:"""Official WaveRep checkpoint -> SynthScopeWaveRepModel: the released weights_dinov2_G{1,4}.ckpt are flat timmstate dicts; the official create_model also accepts a Lightning ``{"state_dict": {"model.<timm key>": ...}}`` (it keepsthe keys starting with ``model`` and drops that prefix). Either way the timm keys go under ``model.``."""if "state_dict" in sd:sd = {k[6:]: v for k, v in sd["state_dict"].items() if k.startswith("model")}return {"model." + k: v for k, v in sd.items()}def remap_probe(sd: dict) -> dict:"""Official PROBE checkpoint ({"model_state_dict": ...}) -> SynthScopePROBEModel / SynthScopePROBEResNetModel: theofficial evaluate_dino.py / evaluate_resnet.py load ``checkpoint['model_state_dict']`` strictly; the names are theofficial ones."""return sd.get("model_state_dict", sd)def remap_pgc(sd: dict) -> dict:"""Official PGC checkpoint -> SynthScopePGCModel: the official ``PGCNetwork`` keeps the DINOv2 backbone inside its``RgbStream`` wrapper (``rgb_stream.backbone.*``); the SynthScope class holds it as ``self.backbone``. Strip the38 unmodified linesbgr: bool = False # feed BGR channels (D3's official reader never converts cv2's BGR)# "ffmpeg_fps_center" (VINA): ffmpeg writes JPEG frames at ``fps``, the central ``num_frames`` are read back and# each goes through ``transform`` (the image eval preprocessing) instead of the clip settings above.# "cv2_frames" (WaveRep): the first ``num_frames`` frames OpenCV decodes (0: every frame), each through# ``transform`` and scored on its own; P(fake) = sigmoid of the mean frame logit (Engine.video_frame_logits).video_sampler: str = ""video_prob: str = "softmax" # video output -> P(fake): softmax[:, 1] of [1, 2] logits, or "sigmoid"notes: str = ""10 unmodified linesinterpret: str = ""remap: Optional[Callable[[dict], dict]] = field(default=None, repr=False)def eval_batch_size(self, batch_size: int) -> int:"""Batch size an evaluation loop may use: 1 for a ``native_res`` spec (its inputs differ in size and cannot bestacked), else ``batch_size``."""return 1 if self.native_res else batch_size# ---------------------------------------------------------------------------# The registry.237 unmodified lines"token give the score. Uses the OFFICIAL checkpoint. PNG/BMP inputs get a JPEG q96 round trip (the paper's ""format-aligned inputs), so use the registered transform. Runs fp32, the official default.",))# PROBE: two released detectors (Table 1 of the paper has both rows), each scored as the official evaluate_*.py does:# the mean logit of the image's non-overlapping crop-size patches at native resolution._PROBE_NOTES = ("Trained with PROBE, which steers a generative model through small edits of its internal ""representations to find realistic images the detector gets wrong, then refines the detector on them. ")_add(ModelSpec(key="probe", name="PROBE (DINOv2)", paper="Cao et al., ICML'26",modality="image", predict_kind="bce", checkpoint="probe.pth", ckpt_kind="official_probe", remap=remap_probe,weights="official",# probe.pth = the official DINOv2_best_model_step_34999.pth unchanged (ModelScope# shuinishaojiu/PROBE-AIGI-Detection, sha256 c8caa9ba...450156); it holds the full model (DINOv2-reg ViT-L/14 +# head), so no backbone download.overrides=["model@ModelConfig=image/probe"],transform=model_transform("image/probe"), # official evaluate_dino.py: repeat-pad to 336, 336 patches, ImageNetnative_res=True, # the patch count depends on the image size: score one image at a timenotes=_PROBE_NOTES + "DINOv2 ViT-L/14 with registers + a linear head on the CLS token, trained on the paper's ""reconstruction training set (SD 2.1 reconstructions of real images) plus PROBE samples. Uses ""the OFFICIAL checkpoint (licence unclear: not in the zoo or on the Space). The image is cut ""into 336x336 patches at its own resolution and the patch logits are averaged.",))_add(ModelSpec(key="probe_resnet", name="PROBE (ResNet-50)", paper="Cao et al., ICML'26",modality="image", predict_kind="bce", checkpoint="probe_resnet.pth", ckpt_kind="official_probe",remap=remap_probe, weights="official",# probe_resnet.pth = the official ResNet50_best_model_step_19343.pth unchanged (same ModelScope repo, sha256# 71ef257e...20f0507c).overrides=["model@ModelConfig=image/probe_resnet"],transform=model_transform("image/probe_resnet"), # official evaluate_resnet.py: black-pad to 224, 224 patchesnative_res=True,notes=_PROBE_NOTES + "ResNet-50 with a linear head, trained on GenImage SD v1.4 plus PROBE samples. Uses the ""OFFICIAL checkpoint (licence unclear: not in the zoo or on the Space). The image is cut into ""224x224 patches at its own resolution and the patch logits are averaged.",))# VINA: one model for images and videos. `vina` scores images (and, like every image detector, sampled frames of a video# with the mean P(fake)); `vina_video` is the official video protocol, so the paper's video benchmarks run through it._VINA_NOTES = ("DINOv3 ViT-L/16 fine-tuned end to end with a linear head, trained on images and video frames together "22 unmodified linesnotes=_VINA_NOTES + "Videos: the official protocol - ffmpeg writes the clip as JPEG frames at 2 fps and the ""central frame is scored with the image preprocessing (needs ffmpeg).",))# WaveRep: two released checkpoints. The demo README says G1 is trained on "a single generator" and G4 on "four generators"# (the demo's default); we infer the paper's Pyramid Flow detector (Tables 1-2) and its Table 5 set (+ CogVideoX 1.5,# Allegro, Open-Sora Plan)._WAVEREP_NOTES = ("DINOv2 ViT-B/14 with registers, fine-tuned end to end on single video frames with a forensic ""augmentation: a fake frame's low-pass and horizontal / vertical wavelet bands are replaced by a ""real frame's, steering the detector to the diagonal high-frequency bands. Uses the OFFICIAL checkpoint ""{ckpt} (GRIP license: nonprofit use). The first 64 frames (the paper's protocol) are decoded with ""OpenCV; each frame's central 504x504 pixels are scored (no resize; a smaller frame is zero-padded) ""and P(fake) is the sigmoid of the mean frame logit.")for _key, _name, _ckpt, _note in [("waverep", "WaveRep (video)", "waverep.pth", "weights_dinov2_G1, trained on one generator (Pyramid Flow, as we infer)"),("waverep_g4", "WaveRep-G4 (video)", "waverep_g4.pth", "weights_dinov2_G4, trained on four generators"),]:_add(ModelSpec(key=_key, name=_name, paper="Corvi et al., NeurIPS'25",modality="video", predict_kind="video", checkpoint=_ckpt, ckpt_kind="official_waverep", remap=remap_waverep,weights="official",# <key>.pth = the official weights_dinov2_G{1,4}.ckpt unchanged (grip.unina.it, md5 as the demo README); a flat# timm state dict holding the full model, strict load.overrides=["model@ModelConfig=video/waverep"],transform=model_transform("video/waverep"), # official create_transform: CenterCrop(504), ToTensor, ImageNet# official demo/utils.py: ReadVideoIteratorCV (every cv2 frame, BGR->RGB) limited to the paper's first 64# frames (the demo's --limit 64; without it the demo scores every frame), mean logit, expit.num_frames=64, fps=None, frame_size=504, video_sampler="cv2_frames", video_prob="sigmoid",notes=_WAVEREP_NOTES.format(ckpt=_note),))# OmniAID's official eval preprocessing: v2 resizes straight to 336 (data/datasets.py); the v1-era releases used a# double resize (512x512, then 336x336) - the commented-out pipeline that the official code says to use for v1 weights.for _key, _name, _ckpt, _note in [114 unmodified lines"ltf": ("Native-res 224 tiles + global view", "The image is cut into 224×224 tiles at its own resolution (no ""scaling; edge tiles are aligned to the border, a side under 224 px is padded with black), plus one view of ""the whole image resized to 224 and center-cropped."),"probe": ("Native-res 336 patches, mean logit", "The image is cut into non-overlapping 336×336 patches at its own ""resolution (no scaling; a strip at the right / bottom edge narrower than 336 px is not seen); a side ""under 336 px is first tiled with copies of the image. Each patch is scored and the scores are ""averaged."),"probe_resnet": ("Native-res 224 patches, mean logit", "The image is cut into non-overlapping 224×224 patches at ""its own resolution (no scaling; a strip at the right / bottom edge narrower than 224 px is not ""seen); an image with a side under 224 px is centered on a black 224×224 square instead (its ""other side, if longer, is cut to the central 224 px). Each patch is scored and the scores are ""averaged."),"vina": ("Resize + center-crop 256 (bicubic)", "The shorter side is scaled to 256 px (bicubic) and the central ""256×256 square is used. The aspect ratio is kept; anything outside the square is not seen by the ""detector."),12 unmodified linesf"them {'is' if one else 'are'} scored like an image: the shorter side is scaled to "f"{spec.frame_size} px (bicubic) and the central {spec.frame_size}×{spec.frame_size} ""square is used. This matches the paper's evaluation."}if spec.video_sampler == "cv2_frames":frames = f"The first {spec.num_frames} frames" if spec.num_frames else "Every frame"return {"label": f"{frames}, center {spec.frame_size}","explanation": f"{frames} of the clip {'are' if spec.num_frames else 'is'} scored one by one: the "f"central {spec.frame_size}×{spec.frame_size} pixels of each frame are used exactly ""as they are (no scaling; a smaller frame is padded with black), and the frame scores ""are averaged. This matches the paper's evaluation."}if spec.modality == "video":crop = f", after trimming {int(spec.edge_crop * 100)}% off every edge" if spec.edge_crop else ""return {"label": f"{spec.num_frames} sampled frames",
13 unmodified lines1415161718192021222324199 unmodified lines224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334878 unmodified lines121312141215121612171218377 unmodified lines1596159715981599160013 unmodified lines"benchmark": "GenImage (B2, Setting-I, SDv1.4-trained)","metric": "acc","paper": "acc=86.88","ours": "SynthScope mAP=96.42 / acc=77.87 \u00b7 official mAP=97.12 / acc=85.91","ours_synthscope": "mAP=96.42 / acc=77.87","ours_official": "mAP=97.12 / acc=85.91","status": "official","note": "official sd14_train.pth, faithful vendored eval; acc 85.91 ~ paper 86.88 (tag aide_official_genimage8). FROM-SCRATCH reproduction (native-res 5-view, aide_native_v2/model_2): GenImage-8 96.42 mAP / 97.07 mAUROC / 77.9 acc (tag aide_retrain_native_g8) = reproduces official 97.12. The old resize-256 retrains (91.75 / 92.47) were capped by the resize-before-DCT bug."},{"benchmark": "Chameleon (B3, Setting-II, in-the-wild)",199 unmodified lines"benchmark": "AIGIBench (20 full-image-synthesis subsets, full test data)","metric": "balanced accuracy / AUROC","paper": "acc=92.8 / auroc=97.5","ours": "mAP=97.0 / acc=92.85 / AUROC=97.48 (official wts)","ours_synthscope": "","ours_official": "mAP=97.0 / acc=92.85 / AUROC=97.48","status": "official","note": "Official adapter through SynthScope reproduces every one of the 20 subsets within 0.10 pt (92.85 acc / 97.48 AUROC)."},{"benchmark": "UniversalFakeDetect (UFD-8, diffusion and DALL-E half)","metric": "balanced accuracy","paper": "\u2014","ours": "mAP=99.19 / acc=93.94 (official wts)","ours_synthscope": "","ours_official": "mAP=99.19 / acc=93.94","status": "reference","note": "UFD-8 mean balanced accuracy 93.94; 16-generator union 89.27 (aggregation differs from the paper)."},{"benchmark": "ForenSynths (13 GAN generators)","metric": "balanced accuracy","paper": "\u2014","ours": "mAP=94.05 / acc=81.95 (official wts)","ours_synthscope": "","ours_official": "mAP=94.05 / acc=81.95","status": "reference","note": "Mean balanced accuracy 81.95 (low scores are fake-recall; AP/AUROC are 95-99 on those generators)."},{"benchmark": "GenImage-8 (CuRe's training set, in-distribution sanity check)","metric": "balanced accuracy","paper": "\u2014","ours": "mAP=97.3 / acc=85.18 (official wts)","ours_synthscope": "","ours_official": "mAP=97.3 / acc=85.18","status": "reference","note": "SD-v1.4 99.73, SD-v1.5 99.80, Wukong 99.87; weaker on ADM/BigGAN/VQDM at the fixed 0.5 threshold."},{"benchmark": "AIGCDetectBenchmark (17 generators, full data)","metric": "balanced accuracy","paper": "acc=89.3 / auroc=98.0","ours": "mAP=98.08 / acc=89.3 / AUROC=98.02 (official wts)","ours_synthscope": "","ours_official": "mAP=98.08 / acc=89.3 / AUROC=98.02","status": "official","note": "Official adapter through SynthScope: 89.30 balanced acc / 98.02 AUROC (mAP 98.08) on all 17 generators, full test data, 76,299 real / 76,299 fake (tag cure_aigcdetect, job 251523)."},{"benchmark": "EvalGEN (5 generators, full data)","metric": "balanced accuracy","paper": "acc=98.1","ours": "mAP=99.86 / acc=98.14 / AUROC=99.66 (official wts)","ours_synthscope": "","ours_official": "mAP=99.86 / acc=98.14 / AUROC=99.66","status": "official","note": "Official adapter through SynthScope: 98.14 balanced acc (mAP 99.86, AUROC 99.66) on all 55,298 fakes vs MSCOCO val2017 (5000 reals; our choice of pool) (tag cure_evalgen, job 251412)."},{"benchmark": "SynthWildX (3 generators, images still online on X)","metric": "balanced accuracy","paper": "acc=92.7","ours": "mAP=95.61 / acc=92.69 / AUROC=96.5 (official wts)","ours_synthscope": "","ours_official": "mAP=95.61 / acc=92.69 / AUROC=96.5","status": "official","note": "Official adapter through SynthScope: 92.69 balanced acc (mAP 95.61, AUROC 96.50) on the 1713 of 2000 images still online on X (413 real; 392/473/435 fake) (tag cure_synthwildx, job 251435)."},{"benchmark": "WildRF (Facebook, Reddit, Twitter test sets)","metric": "balanced accuracy","paper": "acc=95.8","ours": "mAP=99.13 / acc=95.89 / AUROC=99.14 (official wts)","ours_synthscope": "","ours_official": "mAP=99.13 / acc=95.89 / AUROC=99.14","status": "official","note": "Official adapter through SynthScope: 95.89 balanced acc (mAP 99.13, AUROC 99.14) on the full test split, 1251 real / 1252 fake (tag cure_wildrf, job 251440)."},{"benchmark": "BFree-Online (viral images still online)","metric": "balanced accuracy","paper": "acc=90.9","ours": "mAP=99.06 / acc=91.64 / AUROC=98.08 (official wts)","ours_synthscope": "","ours_official": "mAP=99.06 / acc=91.64 / AUROC=98.08","status": "reference","note": "Official adapter through SynthScope: 91.64 balanced acc (mAP 99.06, AUROC 98.08) on the 807 of 1111 listed images still online (269 real / 538 fake), about 58% of the paper's set, so not a like-for-like comparison (tag cure_bfree_online, job 251449)."},{"benchmark": "RRDataset (original / transfer / redigital)","metric": "balanced accuracy","paper": "acc=81.5","ours": "mAP=90.4 / acc=82.04 / AUROC=88.88 (official wts)","ours_synthscope": "","ours_official": "mAP=90.4 / acc=82.04 / AUROC=88.88","status": "official","note": "Official adapter through SynthScope: 82.04 balanced acc (mAP 90.40, AUROC 88.88) on the public test archive, 25,499 real / 25,500 fake (original 91.08, transfer 85.52, redigital 69.51) (tag cure_rrdataset, job 251476)."},{"benchmark": "RealChain (7 generators, full data)","metric": "balanced accuracy","paper": "acc=79.7","ours": "mAP=87.39 / acc=79.69 / AUROC=85.47 (official wts)","ours_synthscope": "","ours_official": "mAP=87.39 / acc=79.69 / AUROC=85.47","status": "official","note": "Official adapter through SynthScope: 79.69 balanced acc (mAP 87.39, AUROC 85.47) on the full released set (tag cure_realchain, job 251412). The release is one JPEG-q60 image set; the 7000 unpaired reals are split into 7 disjoint slices, so the mean per-generator balanced accuracy equals the pooled one."},{"benchmark": "Chameleon",878 unmodified lines"note": "Official-weights-in-SynthScope reproduces the AP (99.26) and acc 97.39 ~= paper 97.9. SynthScope retrain matches on AP (98.61) but acc collapses (66.66) due to threshold/calibration drift in the from-scratch LoRA head; the released checkpoint's peak-guided calibration is what the paper headline relies on."}],"restrav": [{"benchmark": "A) VidProM vs image-based detectors (Table 2)",377 unmodified lines"status": "missing","note": "Not run: no data or loader in SynthScope."}]}13 unmodified lines1415161718192021222324199 unmodified lines224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334878 unmodified lines121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362377 unmodified lines174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187813 unmodified lines"benchmark": "GenImage (B2, Setting-I, SDv1.4-trained)","metric": "acc","paper": "acc=86.88","ours": "SynthScope mAP=93.9 / acc=80.73 / AUROC=91.66 \u00b7 official mAP=97.12 / acc=85.91","ours_synthscope": "mAP=93.9 / acc=80.73 / AUROC=91.66","ours_official": "mAP=97.12 / acc=85.91","status": "official","note": "official sd14_train.pth, faithful vendored eval; acc 85.91 ~ paper 86.88 (tag aide_official_genimage8, full GenImage_full/test: 1500 real + 1500 fake per generator, 6000 + 6000 for sdv1.4). SYNTHSCOPE-TRAINED (the official recipe through experiments/image/aide.sh, train job 281041 on 4x A6000, model_best = epoch 4, val acc 0.9984): full GenImage-8 93.90 mAP / 91.66 mAUROC / 80.73 acc (tag\u2026"},{"benchmark": "Chameleon (B3, Setting-II, in-the-wild)",199 unmodified lines"benchmark": "AIGIBench (20 full-image-synthesis subsets, full test data)","metric": "balanced accuracy / AUROC","paper": "acc=92.8 / auroc=97.5","ours": "SynthScope mAP=96.72 / acc=91.12 / AUROC=97.1 \u00b7 official mAP=97.0 / acc=92.85 / AUROC=97.48","ours_synthscope": "mAP=96.72 / acc=91.12 / AUROC=97.1","ours_official": "mAP=97.0 / acc=92.85 / AUROC=97.48","status": "reproduced","note": "Reproduced by the SynthScope-trained r3e0 ONLY with the unstated augmentation assumption (pre-registered non-benchmark selection; single seed; the paper-settings-only r1e0 gives 88.85 acc, not reproduced); the served cure model is the official adapter. Official adapter through SynthScope reproduces every one of the 20 subsets within 0.10 pt (92.85 acc / 97.48 AUROC). SynthScope-trained: r3e0\u2026"},{"benchmark": "UniversalFakeDetect (UFD-8, diffusion and DALL-E half)","metric": "balanced accuracy","paper": "\u2014","ours": "SynthScope mAP=98.73 / acc=93.89 / AUROC=98.31 \u00b7 official mAP=99.19 / acc=93.94","ours_synthscope": "mAP=98.73 / acc=93.89 / AUROC=98.31","ours_official": "mAP=99.19 / acc=93.94","status": "reference","note": "UFD-8 mean balanced accuracy 93.94; 16-generator union 89.27 (aggregation differs from the paper). SynthScope-trained: r3e0, the best checkpoint by the pre-registered non-benchmark selection rule (paper recipe + DDA-style augmentation, stage-1 epoch 0; tag cure_trained_r3e0_ufd): acc 93.89 / AUROC 98.31 (reference); the recipe's last epoch (tag cure_trained_ufd): acc 82.69 / AUROC 93.85."},{"benchmark": "ForenSynths (13 GAN generators)","metric": "balanced accuracy","paper": "\u2014","ours": "SynthScope mAP=97.22 / acc=89.36 / AUROC=96.58 \u00b7 official mAP=94.05 / acc=81.95","ours_synthscope": "mAP=97.22 / acc=89.36 / AUROC=96.58","ours_official": "mAP=94.05 / acc=81.95","status": "reference","note": "Mean balanced accuracy 81.95 (low scores are fake-recall; AP/AUROC are 95-99 on those generators). SynthScope-trained: r3e0, the best checkpoint by the pre-registered non-benchmark selection rule (paper recipe + DDA-style augmentation, stage-1 epoch 0; tag cure_trained_r3e0_forensynths): acc 89.36 / AUROC 96.58 (reference); the recipe's last epoch (tag cure_trained_forensynths): acc 75.83 /\u2026"},{"benchmark": "GenImage-8 (CuRe's training set, in-distribution sanity check)","metric": "balanced accuracy","paper": "\u2014","ours": "SynthScope mAP=97.56 / acc=86.22 / AUROC=97.59 \u00b7 official mAP=97.3 / acc=85.18","ours_synthscope": "mAP=97.56 / acc=86.22 / AUROC=97.59","ours_official": "mAP=97.3 / acc=85.18","status": "reference","note": "SD-v1.4 99.73, SD-v1.5 99.80, Wukong 99.87; weaker on ADM/BigGAN/VQDM at the fixed 0.5 threshold. SynthScope-trained: r3e0, the best checkpoint by the pre-registered non-benchmark selection rule (paper recipe + DDA-style augmentation, stage-1 epoch 0; tag cure_trained_r3e0_genimage8): acc 86.22 / AUROC 97.59 (reference); the recipe's last epoch (tag cure_trained_genimage8): acc 77.7 / AUROC 87.88."},{"benchmark": "AIGCDetectBenchmark (17 generators, full data)","metric": "balanced accuracy","paper": "acc=89.3 / auroc=98.0","ours": "SynthScope mAP=98.59 / acc=92.01 / AUROC=98.38 \u00b7 official mAP=98.08 / acc=89.3 / AUROC=98.02","ours_synthscope": "mAP=98.59 / acc=92.01 / AUROC=98.38","ours_official": "mAP=98.08 / acc=89.3 / AUROC=98.02","status": "reproduced","note": "Reproduced by the SynthScope-trained r3e0 (pre-registered non-benchmark selection; single seed) and, without the augmentation assumption, by the paper-settings-only r1e0 (92.25 acc); the served cure model is the official adapter. Official adapter through SynthScope: 89.30 balanced acc / 98.02 AUROC (mAP 98.08) on all 17 generators, full test data, 76,299 real / 76,299 fake (tag cure_aigcdetect\u2026"},{"benchmark": "EvalGEN (5 generators, full data)","metric": "balanced accuracy","paper": "acc=98.1","ours": "SynthScope mAP=99.47 / acc=93.32 / AUROC=98.85 \u00b7 official mAP=99.86 / acc=98.14 / AUROC=99.66","ours_synthscope": "mAP=99.47 / acc=93.32 / AUROC=98.85","ours_official": "mAP=99.86 / acc=98.14 / AUROC=99.66","status": "official","note": "Trained r3e0 not reproduced (-4.8 acc); the served cure model is the official adapter. Official adapter through SynthScope: 98.14 balanced acc (mAP 99.86, AUROC 99.66) on all 55,298 fakes vs MSCOCO val2017 (5000 reals; our choice of pool) (tag cure_evalgen, job 251412). SynthScope-trained: r3e0, the best checkpoint by the pre-registered non-benchmark selection rule (paper recipe + DDA-style\u2026"},{"benchmark": "SynthWildX (3 generators, images still online on X)","metric": "balanced accuracy","paper": "acc=92.7","ours": "SynthScope mAP=97.12 / acc=91.76 / AUROC=97.09 \u00b7 official mAP=95.61 / acc=92.69 / AUROC=96.5","ours_synthscope": "mAP=97.12 / acc=91.76 / AUROC=97.09","ours_official": "mAP=95.61 / acc=92.69 / AUROC=96.5","status": "reproduced","note": "Reproduced by the SynthScope-trained r3e0 (pre-registered non-benchmark selection; single seed) and, without the augmentation assumption, by the paper-settings-only r1e0 (90.99 acc); the served cure model is the official adapter. Official adapter through SynthScope: 92.69 balanced acc (mAP 95.61, AUROC 96.50) on the 1713 of 2000 images still online on X (413 real; 392/473/435 fake) (tag\u2026"},{"benchmark": "WildRF (Facebook, Reddit, Twitter test sets)","metric": "balanced accuracy","paper": "acc=95.8","ours": "SynthScope mAP=99.3 / acc=95.58 / AUROC=99.25 \u00b7 official mAP=99.13 / acc=95.89 / AUROC=99.14","ours_synthscope": "mAP=99.3 / acc=95.58 / AUROC=99.25","ours_official": "mAP=99.13 / acc=95.89 / AUROC=99.14","status": "reproduced","note": "Reproduced by the SynthScope-trained r3e0 (pre-registered non-benchmark selection; single seed) and, without the augmentation assumption, by the paper-settings-only r1e0 (95.23 acc); the served cure model is the official adapter. Official adapter through SynthScope: 95.89 balanced acc (mAP 99.13, AUROC 99.14) on the full test split, 1251 real / 1252 fake (tag cure_wildrf, job 251440).\u2026"},{"benchmark": "BFree-Online (viral images still online)","metric": "balanced accuracy","paper": "acc=90.9","ours": "SynthScope mAP=89.48 / acc=71.19 / AUROC=79.51 \u00b7 official mAP=99.06 / acc=91.64 / AUROC=98.08","ours_synthscope": "mAP=89.48 / acc=71.19 / AUROC=79.51","ours_official": "mAP=99.06 / acc=91.64 / AUROC=98.08","status": "reference","note": "Trained r3e0 not reproduced (-19.7 acc); the served cure model is the official adapter. Official adapter through SynthScope: 91.64 balanced acc (mAP 99.06, AUROC 98.08) on the 807 of 1111 listed images still online (269 real / 538 fake), about 58% of the paper's set, so not a like-for-like comparison (tag cure_bfree_online, job 251449). SynthScope-trained: r3e0, the best checkpoint by the\u2026"},{"benchmark": "RRDataset (original / transfer / redigital)","metric": "balanced accuracy","paper": "acc=81.5","ours": "SynthScope mAP=84.91 / acc=73.46 / AUROC=85.32 \u00b7 official mAP=90.4 / acc=82.04 / AUROC=88.88","ours_synthscope": "mAP=84.91 / acc=73.46 / AUROC=85.32","ours_official": "mAP=90.4 / acc=82.04 / AUROC=88.88","status": "official","note": "Trained r3e0 not reproduced (-8.0 acc); the served cure model is the official adapter. Official adapter through SynthScope: 82.04 balanced acc (mAP 90.40, AUROC 88.88) on the public test archive, 25,499 real / 25,500 fake (original 91.08, transfer 85.52, redigital 69.51) (tag cure_rrdataset, job 251476). SynthScope-trained: r3e0, the best checkpoint by the pre-registered non-benchmark selection\u2026"},{"benchmark": "RealChain (7 generators, full data)","metric": "balanced accuracy","paper": "acc=79.7","ours": "SynthScope mAP=83.67 / acc=72.75 / AUROC=84.7 \u00b7 official mAP=87.39 / acc=79.69 / AUROC=85.47","ours_synthscope": "mAP=83.67 / acc=72.75 / AUROC=84.7","ours_official": "mAP=87.39 / acc=79.69 / AUROC=85.47","status": "official","note": "Trained r3e0 not reproduced (-7.0 acc); the served cure model is the official adapter. Official adapter through SynthScope: 79.69 balanced acc (mAP 87.39, AUROC 85.47) on the full released set (tag cure_realchain, job 251412). The release is one JPEG-q60 image set; the 7000 unpaired reals are split into 7 disjoint slices, so the mean per-generator balanced accuracy equals the pooled one.\u2026"},{"benchmark": "Chameleon",878 unmodified lines"note": "Official-weights-in-SynthScope reproduces the AP (99.26) and acc 97.39 ~= paper 97.9. SynthScope retrain matches on AP (98.61) but acc collapses (66.66) due to threshold/calibration drift in the from-scratch LoRA head; the released checkpoint's peak-guided calibration is what the paper headline relies on."}],"probe": [{"benchmark": "GenImage (8 subsets, val100k, fakes JPEG q96)","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets","paper": "acc=96.8","ours": "mAP=99.77 / acc=97.47 / AUROC=99.8 (official wts)","ours_synthscope": "","ours_official": "mAP=99.77 / acc=97.47 / AUROC=99.8","status": "official","note": "97.47 bAcc / 99.77 mAP, +0.67 vs the paper. Caveats: fakes JPEG q96 as the paper; sdv1.5 8000 per class (paper 6000); DINOv2 ADM/GLIDE/BigGAN about +2 above the paper while SynthScope equals the official code on every file compared (not run on GenImage), cause undetermined. Per subset (diff to the paper): midjourney 98.73 (-0.07); sdv1.4 99.41 (+0.01); sdv1.5 99.39 (-0.01); adm 93.22 (+2.22)\u2026"},{"benchmark": "Synthbuster (9 subsets, vs 5000 MSCOCO reals - not the paper's RAISE-1k)","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets (reals: 5000 MSCOCO val2017, different from the paper)","paper": "acc=97.5","ours": "mAP=99.64 / acc=98.2 / AUROC=99.93 (official wts)","ours_synthscope": "","ours_official": "mAP=99.64 / acc=98.2 / AUROC=99.93","status": "reference","note": "98.2 bAcc / 99.64 mAP with DIFFERENT REALS: 5000 MSCOCO val2017 images (EvalGEN/Flux/0_real) instead of the paper's RAISE-1k (registration-gated, not in SynthScope), so this is not a like-for-like comparison and does not reproduce the paper's number. Per subset (diff to the paper): dalle2 93.47 (-1.13); dalle3 99.57 (+0.17); firefly 99.77 (+0.27); glide 92.22 (+5.52); midjourney-v5 99.77\u2026"},{"benchmark": "SynthWildX (dalle3 / firefly / midjourney_v5)","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets","paper": "acc=96.4","ours": "mAP=98.8 / acc=97.3 / AUROC=99.18 (official wts)","ours_synthscope": "","ours_official": "mAP=98.8 / acc=97.3 / AUROC=99.18","status": "official","note": "97.3 bAcc / 98.8 mAP, +0.90. Per subset (diff): dalle3 97.44 (+0.94); firefly 96.98 (+0.58); midjourney_v5 97.48 (+0.98). Our copy: 413 reals and 392 / 473 / 435 fakes (paper Table 12: 0.5k and 1.5k). The unmodified official code gives the same bAcc on every subset (max |dP| 4.8e-6, 0 flips). Tag probe_synthwildx, job 66753."},{"benchmark": "WildRF (facebook / reddit / twitter)","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets","paper": "acc=96.9","ours": "mAP=99.36 / acc=96.92 / AUROC=99.26 (official wts)","ours_synthscope": "","ours_official": "mAP=99.36 / acc=96.92 / AUROC=99.26","status": "official","note": "96.92 bAcc / 99.36 mAP, +0.02. Per subset (diff): facebook 98.75 (+0.35); reddit 93.33 (-0.07); twitter 98.68 (-0.32). 2503 files (the paper lists 1.25k + 1.25k). The official code drops the 262 .jfif files of twitter (.jpg/.jpeg/.png only); on the common files it equals SynthScope (0 flips, max |dP| 3.0e-6). Tag probe_wildrf, job 66753."},{"benchmark": "AIGI-Bench (CommunityAI + SocialRF)","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets","paper": "acc=89.9","ours": "mAP=96.46 / acc=89.88 / AUROC=95.88 (official wts)","ours_synthscope": "","ours_official": "mAP=96.46 / acc=89.88 / AUROC=95.88","status": "official","note": "89.88 bAcc / 96.46 mAP, -0.02. Per subset (diff): CommunityAI 90.38 (+0.58); SocialRF 89.38 (-0.52). Only the paper's two subsets were scored: CommunityAI 6000 + 6000, SocialRF 3000 + 3000. Tag probe_aigibench, job 66790."},{"benchmark": "Chameleon","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets","paper": "acc=86.6","ours": "","ours_synthscope": "","ours_official": "","status": "missing","note": "Not run: Chameleon is available by request only and has no loader in SynthScope."},{"benchmark": "AIGI-Quality-Paradox","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets","paper": "acc=92.9","ours": "","ours_synthscope": "","ours_official": "","status": "missing","note": "Not run: no loader in SynthScope."}],"probe_resnet": [{"benchmark": "GenImage (8 subsets, val100k, fakes JPEG q96)","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets","paper": "acc=78.4","ours": "mAP=86.69 / acc=78.38 / AUROC=84.81 (official wts)","ours_synthscope": "","ours_official": "mAP=86.69 / acc=78.38 / AUROC=84.81","status": "official","note": "78.38 bAcc / 86.69 mAP, -0.02 vs the paper. Caveats: fakes JPEG q96 as the paper; sdv1.5 8000 per class (paper 6000). Equal to the paper in 7 of 8 subsets (within 0.1); ADM 58.94 vs 60.0. Per subset (diff to the paper): midjourney 90.73 (+0.03); sdv1.4 99.36 (-0.04); sdv1.5 99.24 (+0.04); adm 58.94 (-1.06); glide 63.01 (+0.01); wukong 99.41 (+0.01); vqdm 66.90 (+0.00); biggan 49.41 (+0.01). Full\u2026"},{"benchmark": "Synthbuster (9 subsets, vs 5000 MSCOCO reals - not the paper's RAISE-1k)","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets (reals: 5000 MSCOCO val2017, different from the paper)","paper": "acc=79.1","ours": "mAP=85.23 / acc=83.75 / AUROC=95.88 (official wts)","ours_synthscope": "","ours_official": "mAP=85.23 / acc=83.75 / AUROC=95.88","status": "reference","note": "83.75 bAcc / 85.23 mAP with DIFFERENT REALS: 5000 MSCOCO val2017 images (EvalGEN/Flux/0_real) instead of the paper's RAISE-1k (registration-gated, not in SynthScope), so this is not a like-for-like comparison and does not reproduce the paper's number. Per subset (diff to the paper): dalle2 52.97 (+4.67); dalle3 94.82 (+4.62); firefly 51.57 (+4.67); glide 62.07 (+4.67); midjourney-v5 97.82\u2026"},{"benchmark": "SynthWildX (dalle3 / firefly / midjourney_v5)","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets","paper": "acc=75.6","ours": "mAP=83.88 / acc=75.2 / AUROC=82.8 (official wts)","ours_synthscope": "","ours_official": "mAP=83.88 / acc=75.2 / AUROC=82.8","status": "official","note": "75.2 bAcc / 83.88 mAP, -0.40. Per subset (diff): dalle3 89.71 (-0.59); firefly 56.29 (-0.41); midjourney_v5 79.61 (-0.09). Our copy: 413 reals and 392 / 473 / 435 fakes (paper Table 12: 0.5k and 1.5k). The unmodified official code gives the same bAcc on every subset (max |dP| 4.7e-4, 0 flips). Tag probe_resnet_synthwildx, job 66753."},{"benchmark": "WildRF (facebook / reddit / twitter)","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets","paper": "acc=81.3","ours": "mAP=89.45 / acc=81.63 / AUROC=85.76 (official wts)","ours_synthscope": "","ours_official": "mAP=89.45 / acc=81.63 / AUROC=85.76","status": "official","note": "81.63 bAcc / 89.45 mAP, +0.33. Per subset (diff): facebook 87.81 (+0.01); reddit 72.87 (-0.03); twitter 84.20 (+0.90). 2503 files (the paper lists 1.25k + 1.25k). The official code drops the 262 .jfif files of twitter (.jpg/.jpeg/.png only); on the common files it equals SynthScope (0 flips, max |dP| 1.3e-3). Tag probe_resnet_wildrf, job 66753."},{"benchmark": "AIGI-Bench (CommunityAI + SocialRF)","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets","paper": "acc=70.4","ours": "mAP=79.8 / acc=70.44 / AUROC=77.55 (official wts)","ours_synthscope": "","ours_official": "mAP=79.8 / acc=70.44 / AUROC=77.55","status": "official","note": "70.44 bAcc / 79.8 mAP, +0.04. Per subset (diff): CommunityAI 70.99 (-0.01); SocialRF 69.88 (-0.02). Only the paper's two subsets were scored: CommunityAI 6000 + 6000, SocialRF 3000 + 3000. Tag probe_resnet_aigibench, job 66790."},{"benchmark": "Chameleon","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets","paper": "acc=74.0","ours": "","ours_synthscope": "","ours_official": "","status": "missing","note": "Not run: Chameleon is available by request only and has no loader in SynthScope."},{"benchmark": "AIGI-Quality-Paradox","metric": "balanced accuracy at 0.5 (mean of real and fake accuracy), mean over subsets","paper": "acc=87.7","ours": "","ours_synthscope": "","ours_official": "","status": "missing","note": "Not run: no loader in SynthScope."}],"restrav": [{"benchmark": "A) VidProM vs image-based detectors (Table 2)",377 unmodified lines"status": "missing","note": "Not run: no data or loader in SynthScope."}],"waverep": [{"benchmark": "GenVideo-Val, the paper's 8 GenVideo generators (PARTIAL comparison)","metric": "balanced accuracy at 0.5 and AUC, mean over the paper's 8 GenVideo columns (full GenVideo-Val: 10,000 reals + all fakes of each generator, 64 frames)","paper": "acc=94.83 / auroc=98.03","ours": "acc=90.3 / AUROC=95.73 (official wts)","ours_synthscope": "","ours_official": "acc=90.3 / AUROC=95.73","status": "below","note": "PARTIAL: the paper's 8 GenVideo columns, scored with GenVideo-Val's own 10,000 reals (the paper does not say which reals it paired). 5 of 8 within ~2 pts; HotShot (60.1 vs 81.4), Show-1 (79.7 vs 92.1) and LaVie (92.1 vs 95.5) NOT reproduced; HotShot fake recall 21%, AUC 75.6 (cause untested)."},{"benchmark": "GenVideo-Val full, 10 generators (zero-shot reference)","metric": "mean over 10 generators: balanced accuracy at 0.5, AP (fake positive), AUROC; 10,000 reals + all fakes","paper": "\u2014","ours": "mAP=79.85 / acc=86.87 / AUROC=92.13 (official wts)","ours_synthscope": "","ours_official": "mAP=79.85 / acc=86.87 / AUROC=92.13","status": "reference","note": "Zero-shot reference, NOT a paper reproduction (the 8 paper columns are in the row above; Sora and WildScrape have no paper cell). mAP (fake positive) is low because of the 10,000 : 56-1400 class imbalance; AUROC is not affected the same way."},{"benchmark": "GenVideo-Val --limit 1000 (zero-shot reference)","metric": "mean over 10 generators; first 1000 reals and first 1000 fakes per generator (the D3 protocol)","paper": "\u2014","ours": "mAP=89.81 / acc=86.62 / AUROC=92.09 (official wts)","ours_synthscope": "","ours_official": "mAP=89.81 / acc=86.62 / AUROC=92.09","status": "reference","note": "Zero-shot reference, NOT a paper reproduction: the first 1000 clips per class (--limit 1000), so up to 1000 fakes and exactly 1000 reals per generator."},{"benchmark": "VideoPhy --limit 1000 (zero-shot reference)","metric": "mean over the 8 generators online; first 1000 reals, up to 1000 fakes per generator","paper": "\u2014","ours": "mAP=93.21 / acc=90.0 / AUROC=96.54 (official wts)","ours_synthscope": "","ours_official": "mAP=93.21 / acc=90.0 / AUROC=96.54","status": "reference","note": "Zero-shot reference, NOT a paper reproduction; first 1000 clips per class (--limit 1000); 8 of the 10 VideoPhy generators (dead links skipped). Weakest: OpenSora and ZeroScope."},{"benchmark": "VidProM --limit 1000 (zero-shot reference)","metric": "mean over 4 generators (ModelScope, Pika, Text2Video-Zero, VideoCrafter2); first 1000 clips per class","paper": "\u2014","ours": "mAP=98.11 / acc=89.85 / AUROC=98.06 (official wts)","ours_synthscope": "","ours_official": "mAP=98.11 / acc=89.85 / AUROC=98.06","status": "reference","note": "Zero-shot reference, NOT a paper reproduction; first 1000 clips per class (--limit 1000); 2 Pika fakes (00642, 00891) are empty 0-byte files in our copy, so OpenCV decodes no frame; excluded (998 scored). VidProM is non-commercial."},{"benchmark": "EvalCrafter (zero-shot reference)","metric": "mean over 14 generators; the fakes of each generator vs the first 1000 GenVideo-Val MSR-VTT reals","paper": "\u2014","ours": "mAP=96.93 / acc=92.84 / AUROC=97.17 (official wts)","ours_synthscope": "","ours_official": "mAP=96.93 / acc=92.84 / AUROC=97.17","status": "reference","note": "Zero-shot reference, NOT a paper reproduction. EvalCrafter has no reals of its own: the reals are the first 1000 GenVideo-Val MSR-VTT videos (--limit 1000), the same for every generator."},{"benchmark": "The paper's own test set: Allegro, CogVideoX1.5, Open-Sora-Plan, Mochi-1, NOVA, Sora, FLUX vs 300 Panda-70M reals (NOT HELD)","metric": "balanced accuracy and AUC","paper": "\u2014","ours": "","ours_synthscope": "","ours_official": "","status": "missing","note": "NOT HELD: the 2,100 fakes are downloadable from grip.unina.it, but the 300 real clips are Panda-70M YouTube videos that need dataset/script_download_real.py with a YouTube downloader and cookies; not scraped. Without the reals there is no AUC or balanced accuracy, so a fakes-only run would not be the paper's benchmark."}],"waverep_g4": [{"benchmark": "GenVideo-Val, the paper's 8 GenVideo generators (reference only: G4 is not the paper's single-generator model)","metric": "balanced accuracy at 0.5 and AUC, mean over the paper's 8 GenVideo columns (full GenVideo-Val, 64 frames)","paper": "\u2014","ours": "acc=96.3 / AUROC=99.05 (official wts)","ours_synthscope": "","ours_official": "acc=96.3 / AUROC=99.05","status": "reference","note": "REFERENCE ONLY: G4 is trained on four generators, not the paper's single-generator setting (the paper's G1 values are in the waverep rows). PARTIAL as for G1: GenVideo-Val's own 10,000 reals (the paper's pairing is unstated). Above the paper's G1 on every column but Gen2 AUC, by up to 4.7 bAcc (Show-1)."},{"benchmark": "GenVideo-Val full, 10 generators (zero-shot reference)","metric": "mean over 10 generators: balanced accuracy at 0.5, AP (fake positive), AUROC; 10,000 reals + all fakes","paper": "\u2014","ours": "mAP=88.88 / acc=93.28 / AUROC=96.69 (official wts)","ours_synthscope": "","ours_official": "mAP=88.88 / acc=93.28 / AUROC=96.69","status": "reference","note": "Zero-shot reference, NOT a paper reproduction (the 8 paper columns are in the row above; Sora and WildScrape have no paper cell). mAP (fake positive) is low because of the 10,000 : 56-1400 class imbalance; AUROC is not affected the same way."},{"benchmark": "GenVideo-Val --limit 1000 (zero-shot reference)","metric": "mean over 10 generators; first 1000 reals and first 1000 fakes per generator (the D3 protocol)","paper": "\u2014","ours": "mAP=94.47 / acc=92.65 / AUROC=96.53 (official wts)","ours_synthscope": "","ours_official": "mAP=94.47 / acc=92.65 / AUROC=96.53","status": "reference","note": "Zero-shot reference, NOT a paper reproduction: the first 1000 clips per class (--limit 1000), so up to 1000 fakes and exactly 1000 reals per generator."},{"benchmark": "VideoPhy --limit 1000 (zero-shot reference)","metric": "mean over the 8 generators online; first 1000 reals, up to 1000 fakes per generator","paper": "\u2014","ours": "mAP=98.2 / acc=95.73 / AUROC=99.29 (official wts)","ours_synthscope": "","ours_official": "mAP=98.2 / acc=95.73 / AUROC=99.29","status": "reference","note": "Zero-shot reference, NOT a paper reproduction; first 1000 clips per class (--limit 1000); 8 of the 10 VideoPhy generators (dead links skipped). Weakest: OpenSora and ZeroScope."},{"benchmark": "VidProM --limit 1000 (zero-shot reference)","metric": "mean over 4 generators (ModelScope, Pika, Text2Video-Zero, VideoCrafter2); first 1000 clips per class","paper": "\u2014","ours": "mAP=99.29 / acc=95.8 / AUROC=99.25 (official wts)","ours_synthscope": "","ours_official": "mAP=99.29 / acc=95.8 / AUROC=99.25","status": "reference","note": "Zero-shot reference, NOT a paper reproduction; first 1000 clips per class (--limit 1000); 2 Pika fakes (00642, 00891) are empty 0-byte files in our copy, so OpenCV decodes no frame; excluded (998 scored). VidProM is non-commercial."},{"benchmark": "EvalCrafter (zero-shot reference)","metric": "mean over 14 generators; the fakes of each generator vs the first 1000 GenVideo-Val MSR-VTT reals","paper": "\u2014","ours": "mAP=99.19 / acc=96.55 / AUROC=99.29 (official wts)","ours_synthscope": "","ours_official": "mAP=99.19 / acc=96.55 / AUROC=99.29","status": "reference","note": "Zero-shot reference, NOT a paper reproduction. EvalCrafter has no reals of its own: the reals are the first 1000 GenVideo-Val MSR-VTT videos (--limit 1000), the same for every generator."}]}
5 unmodified lines67891011125 unmodified lines1819202122232425262728293031324 unmodified lines3738394041425 unmodified linesit was obtained (official weights / trained-from-scratch / training-free).Run: conda run -n SynthScope python interface/scripts/collect_checkpoints.pyOverride the destination with SYNTHSCOPE_CKPT_DIR."""import jsonimport os5 unmodified linesfrom backend import config # noqa: E402 (sets paths)from backend.registry import list_specs # noqa: E402# Known source locations of the official weights on this node.REPRO_CKPTS = Path("/hddstore/ssalehi/SynthScope/repro/ckpts")OFFICIAL_SOURCES = {"fat_former.pth": REPRO_CKPTS / "fatformer_official.pth","aide.pth": REPRO_CKPTS / "aide_progan_train.pth","npr.pth": REPRO_CKPTS / "NPR_model_epoch_last_3090.pth",}def link(dest: Path, src: Path) -> str:if not src.exists():return f"source missing: {src}"4 unmodified linesdef main():dst = config.CHECKPOINTS_DIRdst.mkdir(parents=True, exist_ok=True)print(f"checkpoints dir: {dst}")5 unmodified lines67891011125 unmodified lines1819202122232425262728293031323334353637383940414243444 unmodified lines4950515253545556575859606162635 unmodified linesit was obtained (official weights / trained-from-scratch / training-free).Run: conda run -n SynthScope python interface/scripts/collect_checkpoints.pyOverride the destination with SYNTHSCOPE_CKPT_DIR. ``--check`` only verifies that the source files exist."""import jsonimport os5 unmodified linesfrom backend import config # noqa: E402 (sets paths)from backend.registry import list_specs # noqa: E402# Known source locations of the official weights on this node. Every entry must be the file the registry (and the# public Space) actually serves under that name:# fat_former.pth official 4-class ProGAN FatFormer release# aide.pth official SD-v1.4 release (sd14_train.pth), not the ProGAN-trained progan_train.pth# npr.pth official NPR.pth with the DataParallel ``module.`` prefix stripped (NPR_table1.pth, linked 2026-06-09),# not the older model_epoch_last_3090.pthREPRO_CKPTS = Path("/hddstore/ssalehi/SynthScope/repro/ckpts")AIDE_OFFICIAL = Path("/hddstore/ssalehi/SynthScope/repro/official_ckpts/aide/AIDE_checkpoints")OFFICIAL_SOURCES = {"fat_former.pth": REPRO_CKPTS / "fatformer_official.pth","aide.pth": AIDE_OFFICIAL / "sd14_train.pth","npr.pth": REPRO_CKPTS / "NPR_table1.pth",}def missing_sources(sources: dict = None) -> list:"""Names whose source file does not exist (on a node without /hddstore this is all of them)."""sources = OFFICIAL_SOURCES if sources is None else sourcesreturn [name for name, src in sources.items() if not src.exists()]def link(dest: Path, src: Path) -> str:if not src.exists():return f"source missing: {src}"4 unmodified linesdef main():if "--check" in sys.argv[1:]: # only verify that every source exists; link nothing, write nothingmissing = missing_sources()for name in missing:print(f"WARNING: source for {name} is missing: {OFFICIAL_SOURCES[name]}", file=sys.stderr)print(f"{len(OFFICIAL_SOURCES) - len(missing)}/{len(OFFICIAL_SOURCES)} official sources present")sys.exit(1 if missing else 0)for name in missing_sources():print(f"WARNING: source for {name} is missing: {OFFICIAL_SOURCES[name]} "f"(an existing {name} link is left unchanged)", file=sys.stderr)dst = config.CHECKPOINTS_DIRdst.mkdir(parents=True, exist_ok=True)print(f"checkpoints dir: {dst}")
68 unmodified lines69707172737475767768 unmodified linesrandom.Random(2).shuffle(items)print(f"{args.key}: scoring {len(items)} images from [{args.gens}] on {engine.device}")probs, labels = [], []for i in range(0, len(items), args.bs):chunk = items[i:i + args.bs]batch = torch.stack([spec.transform(media.open_rgb(p)) for p, _ in chunk]).to(engine.device)probs += engine._fake_prob(model, spec, batch).float().cpu().tolist()labels += [l for _, l in chunk]68 unmodified lines6970717273747576777868 unmodified linesrandom.Random(2).shuffle(items)print(f"{args.key}: scoring {len(items)} images from [{args.gens}] on {engine.device}")bs = spec.eval_batch_size(args.bs) # native-resolution specs cannot stack variable-size inputsprobs, labels = [], []for i in range(0, len(items), bs):chunk = items[i:i + bs]batch = torch.stack([spec.transform(media.open_rgb(p)) for p, _ in chunk]).to(engine.device)probs += engine._fake_prob(model, spec, batch).float().cpu().tolist()labels += [l for _, l in chunk]
1247 unmodified lines12481249125012511252125312541247 unmodified lines<div class="imgcell seenbox"><img src=${r.input_image} alt="the detector's input" /></div><div class="meta seen-cap">${r.input_note && html`<span class="itag">${r.input_note.label}</span>`}${r.input_size && r.orig_size && html`<b>${r.input_size[0]}×${r.input_size[1]} px</b>${(r.input_size[0] === r.orig_size[0] && r.input_size[1] === r.orig_size[1]) ? " (your image's own size)" : " (from your " + r.orig_size[0] + "×" + r.orig_size[1] + " image)"}. `}${r.input_note && r.input_note.explanation}</div></div>`}1247 unmodified lines12481249125012511252125312541247 unmodified lines<div class="imgcell seenbox"><img src=${r.input_image} alt="the detector's input" /></div><div class="meta seen-cap">${r.input_note && html`<span class="itag">${r.input_note.label}</span>`}${r.input_size && r.orig_size && html`<b>${r.input_size[0]}×${r.input_size[1]} px</b>${(r.input_size[0] === r.orig_size[0] && r.input_size[1] === r.orig_size[1]) ? " (your image's own size)" : " (from your " + r.orig_size[0] + "×" + r.orig_size[1] + " image)"}${r.input_grid ? ", cut into " + r.input_grid[1] + "×" + r.input_grid[0] + " = " + r.input_patches + " patches (as in the official code, padded edges beyond the patch grid are not scored)" : ""}. `}${r.input_note && r.input_note.explanation}</div></div>`}
4 unmodified lines56789101118 unmodified lines303132333435363738394 unmodified lines**AIDE** (ICLR 2025, "A Sanity Check for AI-generated Image Detection") detects generated images byfusing a **semantic** branch and a **low-level artifact** branch:- **Semantic branch** — a frozen OpenCLIP **ConvNeXt-XXL** trunk, mean-pooled and projected to 256-d.- **Artifact branch** — the image is resized to 256×256, then 32×32 patches are **DCT-scored** with `K=6`band-pass filters (weighted `2^k` over `log(|DCT|+1)`); the **2 highest- and 2 lowest-energy patches**are each upsampled to 256×256, passed through **30 fixed SRM high-pass kernels** and two ResNet-5018 unmodified lines| Benchmark | Paper | SynthScope_official | SynthScope_train | Status ||---|---|---|---|---|| AIGCDetectBenchmark (B1, Setting-I, ProGAN-trained) | acc=92.77 | mAP=97.94 / acc=91.89 (official `progan_train.pth`) | — | official || GenImage (B2, Setting-I, SDv1.4-trained) | acc=86.88 | mAP=97.12 / acc=85.91 (served 96.83) | **mAP=96.42 / acc=77.9** | official; trained: mAP matches the official weights, acc below || ForenSynths-13 | — | mAP=94.40 / acc=81.8 (official `progan_train.pth`) | mAP=79.62 (cross-domain) | reference || Chameleon (B3, Setting-II, in-the-wild) | acc=58–66 | — | — | missing |*(**SynthScope_train = a from-scratch retrain with the faithful native-res 5-view preprocessing** (`checkpoints_retrain/aide_native_v2/model_2`, GenImage SDv1.4): GenImage-8 **96.42 mAP / 97.07 mAUROC**, reproducing the official 97.12 mAP (acc 77.9 vs 85.9 is lower) — up from the old resize-256 run's 92.47. This proves the repo can regenerate the AIDE checkpoint from scratch. ForenSynths-13 is cross-domain for it (a GenImage-trained model on the GAN benchmark); the official number there is the ProGAN-trained `progan_train.pth`, not the served `sd14_train.pth`.)***reproduced** = SynthScope-trained checkpoint matches the paper · **official** = official weights loaded into the SynthScope class match (the SynthScope-trained number is shown alongside where we trained from scratch) · **below** = gap remains · **reference** = paper reports no comparable number · **missing** = not yet evaluated.4 unmodified lines56789101118 unmodified lines303132333435363738394041424344454647484950515253545556575859606162634 unmodified lines**AIDE** (ICLR 2025, "A Sanity Check for AI-generated Image Detection") detects generated images byfusing a **semantic** branch and a **low-level artifact** branch:- **Semantic branch** — a frozen OpenCLIP **ConvNeXt-XXL** trunk, mean-pooled and projected to 256-d by a linear layer that is frozen too (the official forward computes it under `torch.no_grad()`, so it keeps its random initialization; training updates only the two ResNet-50 streams and the MLP head).- **Artifact branch** — the image is resized to 256×256, then 32×32 patches are **DCT-scored** with `K=6`band-pass filters (weighted `2^k` over `log(|DCT|+1)`); the **2 highest- and 2 lowest-energy patches**are each upsampled to 256×256, passed through **30 fixed SRM high-pass kernels** and two ResNet-5018 unmodified lines| Benchmark | Paper | SynthScope_official | SynthScope_train | Status ||---|---|---|---|---|| AIGCDetectBenchmark (B1, Setting-I, ProGAN-trained) | acc=92.77 | mAP=97.94 / acc=91.89 (official `progan_train.pth`) | — | official || GenImage (B2, Setting-I, SDv1.4-trained) | acc=86.88 | mAP=97.12 / acc=85.91 (served 96.83) | **mAP=93.90 / acc=80.73** | official; trained: below the paper (acc -6.15, mAP -3.22 vs the official weights) || ForenSynths-13 | — | mAP=94.40 / acc=81.8 (official `progan_train.pth`) | mAP=80.42 / acc=62.5 (cross-domain) | reference || Chameleon (B3, Setting-II, in-the-wild) | acc=58–66 | — | — | missing |*(**SynthScope_train = the official training recipe run in SynthScope** (`bash experiments/image/aide.sh`, train job 281041, `model_best` = epoch 4 of 5, validation accuracy 0.9984), evaluated with `bench_eval --model aide --ckpt model_best.pth`: GenImage-8 on the full test set (tag `aide_trained_genimage8`) **93.90 mAP / 91.66 mAUROC / 80.73 acc**; on the first 300 images per class and generator (the protocol of the served row and of the previous retrain; tag `aide_trained_genimage8_l300`) 92.57 / 89.63 / 80.69. It stays outside the 2-point tolerance of the paper (86.88 acc, -6.15) and below the official weights (97.12 mAP, -3.22): SD v1.4, SD v1.5, Wukong and GLIDE match them (acc 99.97 / 100.0 / 99.93 / 92.00 against 99.76 / 99.80 / 99.13 / 90.83), but ADM (58.63 against 76.60), Midjourney (74.60 against 83.70), VQDM (69.83 against 76.80) and BigGAN (50.87 against 60.63) transfer worse; real accuracy is 99.93-100 on every subset, so the loss is fake recall at the 0.5 threshold. The previous retrain (`aide_native_v2/model_2`; checkpoint deleted 2026-11-10 to free disk space, its result JSONs remain: native-resolution 5-view, but the earlier recipe with lr 1e-4, batch 32, horizontal flip, no perturbations, no label smoothing, DeepSpeed gradient clipping 1.0 and the epoch picked by validation loss; 300 images per class) had 96.42 mAP / 77.87 acc: the faithful recipe gains 2.8 points of accuracy and loses 3.9 mAP on the same images. The cause of the remaining gap is not identified. ForenSynths-13 (tag `aide_trained_forensynths`, 300 per class) is cross-domain for a GenImage-trained model (80.42 mAP / 62.5 acc); the official number there is the ProGAN-trained `progan_train.pth`, not the served `sd14_train.pth`.)***Per-epoch diagnostic (not a reproduction claim; the headline stays `model_best` = epoch 4, chosen by validation accuracy as in the official code).** Each epoch checkpoint `model_0..model_4` of train job 281041 was scored on GenImage-8 (first 300 images per class and generator; epoch 4 is `aide_trained_genimage8_l300`) and, as a transfer probe, on Synthbuster (not an AIDE paper benchmark: the 9 generators' fakes against the 5,000 shared MSCOCO reals, first 300 per class and generator, 5,400 images), DAS6 job 66991, tags `aide_trained_e<k>_genimage8_l300` / `aide_trained_e<k>_synthbuster`:| Epoch | val acc | GenImage-8 mAP / acc | GenImage-8 ADM acc | Synthbuster mAP / acc | Synthbuster DALL-E 2 AP ||---|---:|---:|---:|---:|---:|| 0 | 0.9913 | 93.20 / 77.83 | 52.67 | **96.16** / 72.20 | 98.90 || 1 | 0.9956 | 91.99 / 77.88 | 54.17 | 94.20 / 69.63 | 93.79 || 2 | 0.9973 | 92.96 / 79.73 | 54.67 | 93.13 / 70.37 | 86.57 || 3 | 0.9979 | 92.50 / 79.73 | 54.33 | 92.56 / 70.24 | 84.96 || 4 (best) | 0.9984 | 92.57 / 80.69 | 56.83 | 92.20 / 70.67 | 81.79 |Reading: Synthbuster mAP falls monotonically with training (96.16 to 92.20; DALL-E 2 98.9 to 81.8, Firefly 82.8 to 78.6), the signature of over-adapting to SD v1.4 artifacts, while GenImage-8 mAP is flat (92.0-93.2, within single-run noise) and its accuracy creeps up (77.8 to 80.7) as the 0.5 threshold calibrates. No early epoch comes near the official weights' 97.12 mAP on GenImage-8, so an early checkpoint does not explain the gap on the paper's benchmark. One run, one seed, 300 images per class.### Training recipe (`experiments/image/aide.sh`)The recipe follows the official code (`shilinyan99/AIDE`, `main_finetune.py`, `data/datasets.py`) and the paper's GenImage setting:- **Data**: GenImage SD v1.4 train (162,000 ImageNet reals + 162,000 SD v1.4 fakes); validation = the SD v1.4 val split (6,000 + 6,000).- **Trainable set**: the two ResNet-50 streams and the MLP head (322 tensors, 49,547,778 values). The OpenCLIP ConvNeXt-XXL trunk and its projection stay frozen, the ResNets start from random weights (the official code never loads its ImageNet state dict).- **Transforms** (native resolution, no flip, no crop): `aide_blur` (Gaussian blur, 3x3 kernel, sigma 0.1-3.0, p 0.1) then `aide_jpeg` (JPEG quality 30-100, p 0.1; kornia 0.7.2, images whose sides are not multiples of 16 are edge-padded for the codec and cropped back), then the 5-view DCT patch selection (`aide_five_view_train`). Validation images get the same perturbations, as in the official run. The one deviation is a 1024-pixel cap on the long side before the DCT (dataloader memory); inference never caps.- **Optimisation**: AdamW, lr 5e-4, weight decay 0, 5 epochs, per-iteration cosine decay to 1e-6, no warm-up, label smoothing 0.1, fp32, no gradient clipping, no EMA; plain DDP (no DeepSpeed).- **Batch**: effective batch 256 = 4 GPUs x micro-batch 8 x gradient accumulation 8, with SyncBatchNorm over the 4 GPUs so each BatchNorm layer sees 32 images, as on each of the official 8 GPUs (batch 32 each).- **Selection**: `model_best.pth` = the epoch with the highest validation accuracy (the official `max_accuracy`); every epoch is kept as `model_<epoch>.pth`. Validation accuracy rose every epoch (0.9913, 0.9956, 0.9973, 0.9979, 0.9984), so epoch 4 is also the last.- **Evaluate**: `python benchmark/bench_eval.py --model aide --ckpt <save_path>/model_best.pth --benchmark pergen --data <GenImage test root>`.**reproduced** = SynthScope-trained checkpoint matches the paper · **official** = official weights loaded into the SynthScope class match (the SynthScope-trained number is shown alongside where we trained from scratch) · **below** = gap remains · **reference** = paper reports no comparable number · **missing** = not yet evaluated.
296 unmodified lines29729829930030130214 unmodified lines317318319320321322323324325326327328296 unmodified linesself.convnext_proj = nn.Sequential(nn.Linear(feat_dim, 256))for param in self.openclip_convnext_xxl.parameters():param.requires_grad = False# The ResNet ``fc`` heads are unused (the streams stop at avgpool); they exist only so the# official checkpoint loads strict. Freeze them so the optimizer never touches dead params.for stream in (self.model_min, self.model_max):14 unmodified linestokens = x[:, 4]with torch.no_grad():# FROZEN trunk only: re-normalize the ImageNet/DINOv2-normalized tokens into CLIP space.local = self.openclip_convnext_xxl(tokens * (self.dinov2_std / self.clip_std)+ (self.dinov2_mean - self.clip_mean) / self.clip_std)local = self.avgpool(local).view(tokens.size(0), -1) # [B, feat_dim]x_0 = self.convnext_proj(local) # trainable projection (outside no_grad so it learns)x_1 = (self.model_min(x_minmin) + self.model_max(x_maxmax)+ self.model_min(x_minmin1) + self.model_max(x_maxmax1)) / 4296 unmodified lines29729829930030130230330430530630714 unmodified lines322323324325326327328329330331332333296 unmodified linesself.convnext_proj = nn.Sequential(nn.Linear(feat_dim, 256))for param in self.openclip_convnext_xxl.parameters():param.requires_grad = False# The official forward computes ``convnext_proj`` inside ``torch.no_grad()`` (models/AIDE.py): the projection never# receives gradients and keeps its random initialization, so the trained set is the two ResNets and ``fc``. Freeze# it as well (checkpoints still carry its weights; outputs are unchanged).for param in self.convnext_proj.parameters():param.requires_grad = False# The ResNet ``fc`` heads are unused (the streams stop at avgpool); they exist only so the# official checkpoint loads strict. Freeze them so the optimizer never touches dead params.for stream in (self.model_min, self.model_max):14 unmodified linestokens = x[:, 4]with torch.no_grad():# FROZEN trunk and projection (as the official forward): re-normalize the ImageNet/DINOv2-normalized tokens into CLIP space.local = self.openclip_convnext_xxl(tokens * (self.dinov2_std / self.clip_std)+ (self.dinov2_mean - self.clip_mean) / self.clip_std)local = self.avgpool(local).view(tokens.size(0), -1) # [B, feat_dim]x_0 = self.convnext_proj(local) # as the official forward: inside no_grad, a frozen random projectionx_1 = (self.model_min(x_minmin) + self.model_max(x_maxmax)+ self.model_min(x_minmin1) + self.model_max(x_maxmax1)) / 4
109 unmodified lines110111112113114115109 unmodified lines| ForenSynths (CNNDetection test) | — | mAP=87.97 | mAP=96.17 | reference || In-the-wild (Co-Spy-Bench in-the-wild) | map=84.65 / acc=77.41 | — | — | missing |The served `co_spy.pth` is the SynthScope retrain on GenImage SD v1.4 (`repro/retrain_cospy_full_mgpu.sbatch`,`checkpoints_retrain/cospy_full/model_1.pth`), which gives the Co-Spy-Bench and GenImage SynthScope_train numbers. TheAIGCDetect and ForenSynths SynthScope_train numbers are from earlier SynthScope checkpoints and have not been re-run with it.109 unmodified lines110111112113114115116117109 unmodified lines| ForenSynths (CNNDetection test) | — | mAP=87.97 | mAP=96.17 | reference || In-the-wild (Co-Spy-Bench in-the-wild) | map=84.65 / acc=77.41 | — | — | missing |The ForenSynths row of the official weights (`cospy_official_forensynths`, 13 sets, 87.97 mAP) is a 1000-per-class run (rates are multiples of 0.1; the June job log was not kept). The full ForenSynths-8 run with the same checkpoint and evaluator (`cospy_official_fs8_nov`, DAS6 job 66671, `repro/logs/lbfu_cospyoff_das6_66671.out`) gives 98.85 mAP / 95.12 acc / 99.03 mAUROC and is the leaderboard row.The served `co_spy.pth` is the SynthScope retrain on GenImage SD v1.4 (`repro/retrain_cospy_full_mgpu.sbatch`,`checkpoints_retrain/cospy_full/model_1.pth`), which gives the Co-Spy-Bench and GenImage SynthScope_train numbers. TheAIGCDetect and ForenSynths SynthScope_train numbers are from earlier SynthScope checkpoints and have not been re-run with it.
29 unmodified lines303132333435366 unmodified lines434445464748495051525354555657585960616263646581 unmodified lines14714814915015115229 unmodified lines| Preprocessing in cv2/PIL (`preprocess.py`), not albumentations | No new dependency. Equal to the official pipeline up to **1 float32 ulp (5.96e-8)** on 104 PNG/JPEG images, 200 px–4256 px, square and non-square (`repro/cure_preproc_equiv.py`). || **Source-format hint** `img.info["synthscope_src_format"]` | Official PNG sources get an extra JPEG‑q96 round-trip, decided by the file suffix. `bench_eval` and the web decoder now record the original format on the PIL image; without the hint an image is treated as non-PNG. || fp16 autocast on CUDA inside `forward` | The released results use fp16 AMP; CPU runs in fp32 (scores differ in the 3rd decimal). || `compute_loss` = plain cross-entropy | **The paper's two-stage mixing-ratio-regression training recipe is not in the official release.** `compute_loss` only satisfies SynthScope's trainer interface (LoRA + head trainable); it does **not** reproduce the paper's training. The SynthScope-trained row below is therefore empty. |## Fidelity check (identical to the official model)6 unmodified linesSummary in the repo's **Paper / SynthScope_official / SynthScope_train** schema (`acc` = mean per-generator balanced accuracy at 0.5):| Benchmark | Paper | SynthScope_official | SynthScope_train | Status ||---|---|---|---|---|| AIGIBench (paper's 20 full-image-synthesis subsets, full test data) | acc=92.8 / AUC=97.5 | mAP=97.00 / acc=92.85 / AUROC=97.48 | — | **reproduced** (every subset within 0.10 pt) || UniversalFakeDetect (UFD-8) | acc=82.0 (UnivFD, aggregation unspecified) | mAP=99.19 / acc=93.94 | — | reference || ForenSynths (13) | (GAN half of UnivFD) | mAP=94.05 / acc=81.95 | — | reference || GenImage-8 (its training set) | — | mAP=97.30 / acc=85.18 | — | reference || AIGCDetectBenchmark (17 generators, full data, 76.3k real / 76.3k fake) | acc=89.3 / AUC=98.0 | mAP=98.08 / acc=89.30 / AUROC=98.02 | — | **reproduced** || RealChain (7 generators, 7000 real / 7000 fake, full data) | acc=79.7 | mAP=87.39 / acc=79.69 / AUROC=85.47 | — | **reproduced** || EvalGEN (5 generators, about 55k fakes, MSCOCO val2017 reals) | acc=98.1 | mAP=99.86 / acc=98.14 / AUROC=99.66 | — | **reproduced** (our real pool; see below) || SynthWildX (3 generators; 1713 of 2000 images still online on X) | acc=92.7 | mAP=95.61 / acc=92.69 / AUROC=96.50 | — | **reproduced** (on the images still online) || WildRF (Facebook, Reddit, Twitter test sets, 1251 real / 1252 fake) | acc=95.8 | mAP=99.13 / acc=95.89 / AUROC=99.14 | — | **reproduced** || BFree-Online (807 of the 1111 listed links still online; the paper had about 1400 images) | acc=90.9 | mAP=99.06 / acc=91.64 / AUROC=98.08 | — | close (about 58% of the paper's images) || RRDataset (original / transfer / redigital, public test archive, 25.5k real / 25.5k fake) | acc=81.5 | mAP=90.40 / acc=82.04 / AUROC=88.88 | — | **reproduced** within 0.6 pt (the paper counts 30k/30k) || Chameleon | 93.8 | — | — | missing (available by request only) |`SynthScope_train` is empty: the paper's training recipe is not released. Details and per-generator tables below(official weights through SynthScope; balanced accuracy at 0.5 unless noted).Paper: **89.7 avg over ten benchmarks** — AIGCDetect 89.3 · AIGIBench 92.8 · UnivFD 82.0 · EvalGEN 98.1 ·SynthWildX 92.7 · WildRF 95.8 · BFree-Online 90.9 · RRDataset 81.5 · RealChain 79.7 · Chameleon 93.8.81 unmodified linesofficial PNG to JPEG q96 step (the scorers did not pass the source-format hint then). They were rescored with the step on2026-11-08 (AUROC changes between -2.1 and +0.9, ranks unchanged); see `docs/BENCHMARKS.md`.## Usage```bash29 unmodified lines303132333435366 unmodified lines434445464748495051525354555657585960616263646581 unmodified lines14714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432529 unmodified lines| Preprocessing in cv2/PIL (`preprocess.py`), not albumentations | No new dependency. Equal to the official pipeline up to **1 float32 ulp (5.96e-8)** on 104 PNG/JPEG images, 200 px–4256 px, square and non-square (`repro/cure_preproc_equiv.py`). || **Source-format hint** `img.info["synthscope_src_format"]` | Official PNG sources get an extra JPEG‑q96 round-trip, decided by the file suffix. `bench_eval` and the web decoder now record the original format on the PIL image; without the hint an image is treated as non-PNG. || fp16 autocast on CUDA inside `forward` | The released results use fp16 AMP; CPU runs in fp32 (scores differ in the 3rd decimal). || Training recipe implemented from the paper | **The official release has inference code only.** SynthScope implements the paper's three stages (see *Training recipe* below); without `training_stage` `compute_loss` stays a plain cross-entropy that only satisfies the trainer interface. |## Fidelity check (identical to the official model)6 unmodified linesSummary in the repo's **Paper / SynthScope_official / SynthScope_train** schema (`acc` = mean per-generator balanced accuracy at 0.5):| Benchmark | Paper | SynthScope_official | SynthScope_train | Status (official adapter) ||---|---|---|---|---|| AIGIBench (paper's 20 full-image-synthesis subsets, full test data) | acc=92.8 / AUC=97.5 | mAP=97.00 / acc=92.85 / AUROC=97.48 | mAP=96.72 / acc=91.12 / AUROC=97.10 (**reproduced**) | **reproduced** (every subset within 0.10 pt) || UniversalFakeDetect (UFD-8) | acc=82.0 (UnivFD, aggregation unspecified) | mAP=99.19 / acc=93.94 | mAP=98.73 / acc=93.89 / AUROC=98.31 (**reference**) | reference || ForenSynths (13) | (GAN half of UnivFD) | mAP=94.05 / acc=81.95 | mAP=97.22 / acc=89.36 / AUROC=96.58 (**reference**) | reference || GenImage-8 (its training set) | — | mAP=97.30 / acc=85.18 | mAP=97.56 / acc=86.22 / AUROC=97.59 (**reference**) | reference || AIGCDetectBenchmark (17 generators, full data, 76.3k real / 76.3k fake) | acc=89.3 / AUC=98.0 | mAP=98.08 / acc=89.30 / AUROC=98.02 | mAP=98.59 / acc=92.01 / AUROC=98.38 (**reproduced**) | **reproduced** || RealChain (7 generators, 7000 real / 7000 fake, full data) | acc=79.7 | mAP=87.39 / acc=79.69 / AUROC=85.47 | mAP=83.67 / acc=72.75 / AUROC=84.70 (**not reproduced, -7.0 acc**) | **reproduced** || EvalGEN (5 generators, about 55k fakes, MSCOCO val2017 reals) | acc=98.1 | mAP=99.86 / acc=98.14 / AUROC=99.66 | mAP=99.47 / acc=93.32 / AUROC=98.85 (**not reproduced, -4.8 acc**) | **reproduced** (our real pool; see below) || SynthWildX (3 generators; 1713 of 2000 images still online on X) | acc=92.7 | mAP=95.61 / acc=92.69 / AUROC=96.50 | mAP=97.12 / acc=91.76 / AUROC=97.09 (**reproduced**) | **reproduced** (on the images still online) || WildRF (Facebook, Reddit, Twitter test sets, 1251 real / 1252 fake) | acc=95.8 | mAP=99.13 / acc=95.89 / AUROC=99.14 | mAP=99.30 / acc=95.58 / AUROC=99.25 (**reproduced**) | **reproduced** || BFree-Online (807 of the 1111 listed links still online; the paper had about 1400 images) | acc=90.9 | mAP=99.06 / acc=91.64 / AUROC=98.08 | mAP=89.48 / acc=71.19 / AUROC=79.51 (**not reproduced, -19.7 acc**) | close (about 58% of the paper's images) || RRDataset (original / transfer / redigital, public test archive, 25.5k real / 25.5k fake) | acc=81.5 | mAP=90.40 / acc=82.04 / AUROC=88.88 | mAP=84.91 / acc=73.46 / AUROC=85.32 (**not reproduced, -8.0 acc**) | **reproduced** within 0.6 pt (the paper counts 30k/30k) || Chameleon | 93.8 | — | — | missing (available by request only) |`SynthScope_train` = **r3e0**, the best checkpoint of SynthScope's training investigation by its pre-registered, non-benchmark selection score (see *Trained checkpoint* below): the paper's recipe, plus DDA-style training augmentation (an assumption, the paper states none), stopped after epoch 0 by the selection rule. It is scored with `bench_eval --ckpt` and the same flags as the official rows (tags `cure_trained_r3e0_<bench>`, DAS6 job 67200). By the repo's tolerance (ours >= paper - 2.0 acc, - 2.5 AUROC) it **partially reproduces** the paper: 4 of the 8 comparable benchmarks (AIGIBench, AIGCDetect, SynthWildX, WildRF), mean accuracy 85.15 against the paper's 90.10; BFree-Online, RRDataset, RealChain and EvalGEN stay below. The served `cure` model remains the official adapter.The tables below are the official weights through SynthScope (balanced accuracy at 0.5 unless noted); the trained checkpoint has its own section after the recipe.Paper: **89.7 avg over ten benchmarks** — AIGCDetect 89.3 · AIGIBench 92.8 · UnivFD 82.0 · EvalGEN 98.1 ·SynthWildX 92.7 · WildRF 95.8 · BFree-Online 90.9 · RRDataset 81.5 · RealChain 79.7 · Chameleon 93.8.81 unmodified linesofficial PNG to JPEG q96 step (the scorers did not pass the source-format hint then). They were rescored with the step on2026-11-08 (AUROC changes between -2.1 and +0.9, ranks unchanged); see `docs/BENCHMARKS.md`.## Training recipe (from the paper; no official training code)`experiments/image/cure.sh` runs the three stages of the paper (Sec. 3, 4.1-4.2, Appendix A) on GenImage SD v1.4 train(162,000 ImageNet reals + 162,000 SD v1.4 images) and writes `cure_trained.pth` with exactly the released adapter's 100tensors, so it is scored like the official weights: `bench_eval.py --model cure --ckpt <SAVE>/stage23/cure_trained.pth`.**Status: recipe provided; it partially reproduces the paper (see *Trained checkpoint* below).** Run as written (last epoch) it over-adapts to SD v1.4 in stage 1 and falls 13 points short; with the pre-registered early-stopping rule below it reproduces 3 of 8 comparable benchmarks (4 of 8 with the DDA-style augmentation option, `DatasetConfig.train_augment=dda`). Stages 2-3 are verified with the released encoder. Stage 1 saves every epoch; to build the adapter from the selected epoch run stages 2-3 with `STAGES="2 3" LORA=<SAVE>/stage1/model_<k>.pth bash experiments/image/cure.sh`, with `<k>` from `repro/cure_stage1/epoch_select.py` (the pre-registered rule; epoch 0 in both runs here).| stage | what (paper) | where ||---|---|---|| 1 | x_a = (1 - a) x_r + a x_g with independent real / generated endpoints, a ~ U(0, 1) per pair; linear ratio head + sigmoid on the adapted feature, BCE with soft target a; LoRA on Q and V of all 24 layers (rank 64, alpha 128, dropout 0); AdamW lr 1e-5, weight decay 0.1 (LoRA) / 0.01 (head); 5 epochs, per-GPU batch 64, 2 warmup epochs then cosine to 1e-6 | `main.py` with `trainer/image/cure.yaml`, `dataset/image/cure_train.yaml`, `ModelConfig.training_stage=ratio` (`dataset.CuReMixDataset`, `SynthScopeCuReModel.compute_loss`) || 2 | frozen encoder; 20,000 endpoint pairs; RF / RR / FF trajectories on {0, .2, .4, .6, .8, 1}; slopes (Eq. 6); C_F, C_M, C_S (Eq. 7-9) trace-normalised; generalised eigenproblem (Eq. 10), top k = 128 -> W, mu = mean RF trajectory feature | `train_stages.py stage2`, `subspace.py` || 3 | only Linear(128, 2) on W^T (z - mu): dropout 0.05, CE, AdamW lr 2e-4, weight decay 0.1, batch 256, 5 epochs | `train_stages.py stage3` (features cached once) |**Choices the paper leaves open** (each a documented assumption; the released `W` / `mu` allow checking stage 2):| open point | SynthScope choice | reason ||---|---|---|| training preprocessing | each endpoint goes through the released test pipeline (`cure_eval`: PNG -> JPEG q96, 390 resize / crop, 336, JPEG q70, mean = std = 0.5), then the mixture is formed | the paper re-encodes the PNG fakes as JPEG q96 (the pipeline's first step); the subspace and head are used with this pipeline at test time; no augmentation is mentioned. Check (consistency, not proof): with the released encoder, stage 2 on this preprocessing gives a mu with cosine 0.999998 to the released mu (relative distance 0.19 %, 20,000 pairs per type on the full data, job 66720); the same run without the final JPEG q70 pass (one control) gives cosine 0.982 / distance 19 % and a 17x larger off-diagonal ratio, so the mu match does discriminate that choice, whereas the subspace overlap (0.89 vs 0.86) does not. It is therefore consistent with the release's stage 2 having used this pipeline, but it does not establish it (mixing before q70, and stage 1's own preprocessing, are untested; stage 1 cannot be checked this way). See *Trained checkpoint* || where mixing happens | on the preprocessed tensors | normalisation is affine, so this equals the pixel mixture of the preprocessed images || pairing / epoch | one item per real image (162k per epoch), its generated partner and a drawn at random per item (with replacement), fresh every epoch | "independently drawn" endpoints, "each training pair receives one independently sampled mixing ratio" || warmup / cosine shape | linear from 0 per optimizer step over 2 epochs to 1e-5, then cosine over the remaining 3 epochs to 1e-6 (`timm_cosine.warmup_prefix`) | the usual meaning of "N warmup epochs and cosine decay to a minimum lr" (MAE-style) || GPU count / global batch | per-GPU 64 as stated; the global batch is NGPU x 64 (`STEP_MULT` in `cure.sh` accumulates to NGPU x 64 x STEP_MULT) | not stated. Tested: 192 (3 GPUs x 64, or 1 GPU x 64 x 3) and 512 (2 x 64 x 4, as on 8 GPUs); 512 alone does not reproduce the paper || training augmentation | none by default; `DatasetConfig.train_augment=dda` applies DDA's training augmentations per endpoint (`models/image/cure/train_augment.py`) | the paper states none ("following the setting of DDA" refers to the JPEG format alignment). The option is the R3 run below: DDA's `create_train_transforms` list unchanged, CuRe's random 390 crop in place of the centre crop, one shared seed per pair || precision, clipping, betas, seed | fp16 autocast with loss scaling, no clipping, torch AdamW betas, seed 0 | the released inference is fp16; nothing else stated || stage-1 model selection | every epoch is saved (`save_all`); the epoch is chosen by a pre-registered non-benchmark rule (`repro/cure_stage1/epoch_select.py`, see *Trained checkpoint*) | the paper mentions a "model-selection protocol" (Sec. 4.3) but does not describe it. The last epoch over-adapts (see below) || ratio-head weight decay | 0.01 on all head parameters (bias too) | "weight decay of 0.1 and 0.01, respectively" || pairs per trajectory type | 20,000 for each of RF, RR, FF (360k forwards) | "20,000 sampled endpoint pairs" || lambda_s, lambda_m, eps | 1, 1, 1e-3 (`subspace.py` defaults; `--lambda-s/--lambda-m/--eps`) | not stated. Stage 2 with `--reference-adapter` reports the overlap with the released W and fits the (lambda_s, lambda_m, eps) under which the released W is B-orthonormal. With the **released encoder** on 2500 pairs per type of a 2572 + 2572 subset of the training set (job 283104): fit lambda_s 0.90, lambda_m 1.02, eps 1.05e-3 (relative residual 0.09); with 1, 1, 1e-3 the solved W overlaps the released W at 0.74 (random 0.125), its columns have norms 9.0-9.6 (released 6.8-8.8), and the released W is nearly a generalised eigenbasis of our C_F (off-diagonal ratio 0.03). eps 1e-4 gave overlap 0.19 and 6x larger columns (job 283072, 1000 pairs). Final check on the full data (released encoder, 20,000 pairs per type, job 66720): overlap 0.89, fit lambda_s 0.96, lambda_m 1.02, eps 1.00e-3 (residual 0.036), off-diagonal ratio 0.016, so 1, 1, 1e-3 stand || eigenvector scale | B-orthonormal (W^T B W = I), as LAPACK / scipy generalised solvers return | the released W is not unit-norm (column norms 6.8-8.8) || stage-3 data and schedule | all 324k clean training images, constant lr, last epoch | not stated |**Memory.** On a 24 GB A5000, stage 1 at micro-batch 64 needs gradient checkpointing (`ModelConfig.grad_checkpointing`,6.3 GiB peak, 32 images/s); without it micro-batch 32 takes 14.1 GiB (43 images/s), so a 48 GB GPU can run 64 withoutcheckpointing, or use `MICRO=32` (gradient accumulation 2, same per-GPU batch of 64). Checkpointing gives the same features andgradients (`tests/test_cure_recipe.py`).**Smoke run** (job 283104, one A5000, log `repro/logs/curesmoke_283104.out`; a 2572 + 2572 subset of the training set,every 63rd image of each class; not a result). Stage 1, 200 optimizer steps at per-GPU batch 64 with checkpointing: thevalidation BCE on 256 fixed mixtures falls 0.738, 0.714, 0.698, 0.683, 0.674 over the 5 epochs (0.5 is the floor fora ~ U(0, 1)). Stage 2 on 200 pairs per type, stage 3 on the 5144 subset images (eval-mode accuracy real 0.63 / fake 0.66after 5 epochs of 21 steps), export: 100 tensors, reloaded logits equal the trained head's (max |diff| 3.6e-6), and`synthscope.load("cure", checkpoint=...)` loads it with the same status as the released adapter (`loaded 100 tensors,missing=295` frozen backbone keys, `unexpected=0`). Stage-1 lr (job 283137, `repro/logs/curesmlr_283137.out`): all 45 logged steps equal the intended schedule (linear from 0, 1.000e-05 at the start of epoch 2, cosine to 1.002e-06 at the last step).**Tests.** `tests/test_cure_recipe.py` (CPU): the mixing items, the BCE soft-target loss, the trainable set and weight-decaygroups, gradient checkpointing, the trainer's logged lr at every step against the intended schedule, Eq. 6-10 against numpy/ scipy, and the export format (the released adapter's keys, shapes and dtypes).## Trained checkpoint (SynthScope_train): does the recipe reproduce the paper?**Partially.** The recipe as written, keeping the last stage-1 epoch, falls 13 points short of the paper. Early stopping chosen by a rule fixed in advance on non-benchmark data recovers more than half of that gap. It does not close the gap on degraded and real-world sets.The scripts are in `repro/cure_stage1/` and the JSON outputs in `repro/cure_stage1/results/`.**The checkpoints compared:**- **Original:** the recipe run as written, last epoch. Code 2966f64, DAS6 job 66658 on 3x A6000, global batch 192, sha256 38390ca9...- **R1:** the recipe unchanged with every epoch saved. Global batch 192, run as 1 GPU x 64 x gradient accumulation 3 (IVI job 284138). The epoch was chosen by the pre-registered rule: epoch 0.- Its epoch 4 reproduces the original run (LoRA update norm 3.17 vs 3.18, selection score 83.1 vs 82.9). So the 1-GPU accumulation is not a confound and the original result is not seed noise.- **R2:** as R1 but at global batch 512 (2 GPUs x 64 x accumulation 4), the natural reading of "per-GPU batch 64" on 8 GPUs (IVI job 284137). Its final epoch is used, as decided before the run.- **R2 e1:** R2's epoch 1. It is the epoch whose weight change matches the release (LoRA update norm 0.94x the released adapter's). It was chosen **after the fact**, so it is a diagnostic only.- **R3:** R1 plus DDA-style training augmentation (`DatasetConfig.train_augment=dda`), with the same rule; it selects epoch 0 (DAS6 jobs 67199 / 67200).- **r3e0 is the main SynthScope-trained checkpoint** (sha256 ac70224f...).- It depends on an augmentation assumption the paper does not state.- Among the pre-registered checkpoints it has both the best selection score (94.31 vs r1e0 92.84 vs R2 final 86.86) and the best benchmark mean.- **Disclosure: choosing r3e0 over r1e0 was a run-level decision.**- The pre-registered rule selects an epoch *within* a run.- Running R3 at all, and making it the main checkpoint, was decided after the R1 benchmark results were known.- The cross-run selection scores were computed on different GPUs: R1 on an RTX 6000 Ada, R2 on an RTX A5000, R3 on an RTX A6000. R1's reference rows reuse R2's A5000 features. The released reference scores 95.2 on the A5000 and 95.16 on the A6000.- **Only the AIGIBench "reproduced" depends on the augmentation.** r1e0 alone, which uses only the paper's settings, already reproduces AIGCDetect, SynthWildX and WildRF.- **r1e0 is the result that uses only the paper's stated settings** (sha256 60346a37...).All checkpoints were scored with the official rows' exact protocol: `bench_eval --ckpt`, `--bs 16`, the same data, AIGIBench `--select` of the paper's 20 subsets on full data, no `--limit`. Tags: `cure_trained_<bench>` (original), `cure_trained_r1e0_*`, `cure_trained_r2_*`, `cure_trained_r2e1_*`, `cure_trained_r3e0_*`. Every JSON was checked against its log's RESULT line.Each cell is acc / AUROC. R means reproduced (acc >= paper - 2.0, and AUROC >= paper - 2.5 where the paper reports one); x(d) gives the accuracy gap to the paper. Trained weights are never uploaded.| Benchmark | Paper | Official adapter | Original (last epoch) | R1 e0 (pre-registered) | R2 final | R2 e1 (post-hoc, diagnostic) | **R3 e0 (pre-registered, main)** ||---|---|---|---|---|---|---|---|| AIGIBench-20 | 92.8/97.5 | 92.85/97.48 | 85.05/91.84 x(-7.8) | 88.85/95.86 x(-4.0) | 87.10/93.73 x(-5.7) | 88.81/95.78 x(-4.0) | **91.12/97.10 R** || AIGCDetect | 89.3 | 89.30/98.02 | 81.55/92.22 x(-7.8) | 92.25/98.47 R | 82.29/94.40 x(-7.0) | 88.20/97.84 R | **92.01/98.38 R** || EvalGEN | 98.1 | 98.14/99.66 | 90.65/95.96 x(-7.4) | 91.57/98.63 x(-6.5) | 92.45/97.90 x(-5.6) | 93.98/99.17 x(-4.1) | 93.32/98.85 x(-4.8) || SynthWildX | 92.7/96.6 | 92.69/96.50 | 76.11/86.84 x(-16.6) | 90.99/96.85 R | 81.56/91.85 x(-11.1) | 88.65/95.90 x(-4.0) | **91.76/97.09 R** || WildRF | 95.8/99.1 | 95.89/99.14 | 85.80/94.59 x(-10.0) | 95.23/99.06 R | 90.24/96.19 x(-5.6) | 93.91/98.43 R | **95.58/99.25 R** || BFree-Online (807 images) | 90.9 | 91.64/98.08 | 66.64/85.77 x(-24.3) | 72.30/81.80 x(-18.6) | 69.52/81.51 x(-21.4) | 74.54/89.90 x(-16.4) | 71.19/79.51 x(-19.7) || RRDataset | 81.5 | 82.04/88.88 | 66.36/76.87 x(-15.1) | 72.62/85.25 x(-8.9) | 68.01/78.57 x(-13.5) | 72.65/84.82 x(-8.8) | 73.46/85.32 x(-8.0) || RealChain | 79.7 | 79.69/85.47 | 63.33/76.50 x(-16.4) | 70.34/84.87 x(-9.4) | 67.49/82.20 x(-12.2) | 72.28/85.02 x(-7.4) | 72.75/84.70 x(-7.0) || UFD-8 (reference) | - | 93.94/98.98 | 82.69/93.85 | 93.99/98.87 | 83.81/94.91 | 92.14/98.52 | 93.89/98.31 || ForenSynths-13 (reference) | - | 81.95/95.02 | 75.83/93.56 | 89.79/97.15 | 74.35/95.40 | 84.26/96.16 | 89.36/96.58 || GenImage-8 (reference) | - | 85.18/97.00 | 77.70/87.88 | 86.05/97.36 | 79.89/89.99 | 83.48/96.54 | 86.22/97.59 || **Mean acc / AUROC, 8 comparable** | 90.10 | 90.28/95.40 | 76.94/87.57 | 84.27/92.60 | 79.83/89.54 | 84.13/93.36 | **85.15/92.53** || **Reproduced** | | | 0/8 | 3/8 | 0/8 | 2/8 | **4/8** |### What remains, stated plainly (r3e0)- **Mean accuracy:** 5 points below the paper (85.15 vs 90.10).- **BFree-Online:** -19.7 accuracy, with AUROC 79.5 against the official adapter's 98.1.- This is a **ranking failure**, not a threshold problem.- No variant fixes it; the best is R2 e1 at AUROC 89.9.- **RRDataset:** -8.0. AUROC is 85.3 vs 88.9, so the gap is partly ranking and partly calibration.- **RealChain:** -7.0. AUROC is 84.7, about the official adapter's 85.5, so the gap is **threshold calibration** on degraded images. Fake recall is 51% at 0.5.- **EvalGEN:** -4.8. AUROC is 98.85 vs 99.66, so the gap is **mostly the threshold** (fake recall 87.5%).- **Real/fake balance:** on the wild sets r3e0 is no longer the conservative detector the original checkpoint was. Real / fake accuracy is 93.0 / 90.5 on SynthWildX and 95.9 / 95.3 on WildRF.- **Single seed:** every run is one seed; the paper's seed spread is 0.3-0.7 on AIGIBench.- Differences of about 1 point (r1e0 vs r3e0 on RRDataset and BFree-Online) are within plausible seed noise.- The AIGIBench gain from augmentation (+2.3 accuracy) and the RealChain gain (+2.4) are larger than that.### The over-training finding and the pre-registered early-stopping rule- **The original checkpoint over-adapts to SD v1.4 in stage 1.** Diagnostics: `repro/cure_stage1/feature_analysis.py`, IVI job 284084.- Its LoRA update is 1.71x the released adapter's (Frobenius norm of 2·B·A over all 48 adapted projections). The released adapter starts from the same standard init.- It fits the SD v1.4 mixing ratio about 3x better than the released encoder: excess BCE of a fresh linear head 0.0072 vs 0.0220.- It encodes JPEG quality more strongly: a q95-vs-q50 probe gives 90.2 bacc vs the release's 83.4.- A linear probe fitted on SD v1.4 features transfers worse than the **frozen** base: on Synthbuster fakes, 81.0 vs 92.5, against 95.0 for the released encoder. These are balanced accuracies 80.95 / 92.53 / 95.03 from `repro/cure_stage1/results/epoch_select_r1.json` (rows orig / base / released).- **Ruled out by direct tests:** the stage-2 mixing position (released mu matches mixing after q70: 0.59% vs 3.59% before), the stage-2 solver, the head trainer and the protocol.- **Selection rule.** It was committed before any epoch was scored (`repro/cure_stage1/epoch_select.py`, commit d73d102), and no CuRe paper benchmark is used.- **Data:** 1287 Synthbuster fakes (143 per generator; Synthbuster is not a CuRe benchmark) against 2000 SD v1.4 test reals.- **Score:** the mean of two balanced accuracies on that set: the stage-1 ratio head used directly at 0.5, and a logistic probe fitted on SD v1.4 train features.- **Choice:** the highest-scoring epoch, with ties within 0.5 going to the earlier epoch.- **Also logged for every epoch, not used by the rule:** the LoRA update norm against the release's, the SD v1.4 mixing fit, and WildRF as a diagnostic.Per-epoch selection score (update norm as a multiple of the released adapter's in brackets; full numbers in `repro/cure_stage1/results/epoch_select_{r1,r2,r3}.json`):| Run | epoch 0 | epoch 1 | epoch 2 | epoch 3 | epoch 4 ||---|---|---|---|---|---|| R1 (192) | **92.84** (0.66x) | 89.63 (1.23x) | 84.72 (1.53x) | 82.34 (1.67x) | 83.06 (1.71x) || R2 (512) | 86.73 (0.37x) | 93.34 (0.94x) | 90.74 (1.26x) | 86.40 (1.38x) | 86.86 (1.42x, used) || R3 (192 + augmentation) | **94.31** (0.67x) | 92.55 (1.26x) | 86.10 (1.57x) | 85.26 (1.70x) | 84.51 (1.75x) |References on the same score: released adapter 95.2, frozen PE-Core 89.5, original run 82.9. In-distribution accuracy is high at every epoch except R2's warmup epoch 0 (SD v1.4 test 98.9-99.9; R2 epoch 0 82.2), so a held-out split of the training distribution cannot detect the over-adaptation.**Interpretation**- The epoch curve and the R1/R2 comparison show that the paper's numbers are consistent with stopping after about one epoch's worth of updates, which the "model-selection protocol" the paper mentions may have done.- The 8-GPU reading alone (R2 final) does not get there.- Matching the release's update size (R2 e1) is not sufficient either: R2 e1 ≈ r1e0.### Engineering notes- **Batch-size-dependent fp16 kernels on RTX 6000 Ada.**- On the RTX 6000 Ada (IVI cn032), PE-Core fp16 features depend on the batch size: 0.29 max |diff| between batches of 64 and 128 (|z| up to 82). Logits differ by 1.7-2.3e-2.- At equal batch size the results are bit-identical. On Ampere GPUs (A6000, A5000) the same comparison gives 3.6e-6 to 9.5e-6.- The stage-3 export check therefore compares at the batch size the features were encoded with (`--encode-batch`, tolerance unchanged), and logs the 64-image difference as information only.- Benchmark scores can move at the ~1e-2-logit level with batch size on Ada GPUs (`bench_eval` uses `--bs 16`). All trained-checkpoint benchmark numbers above were computed on A6000s.- **Multi-encoder stages 2/3.** `repro/cure_stage1/multi_stage23.py` runs stages 2/3 for several encoders in one pass over the images, then calls the unchanged `train_stages.py`. Checks:- Stage-2 trajectories: bit-identical to the single-encoder path (all fields max |diff| 0).- Stage-3 features: bit-identical at batch 128.- Exported adapters for R2 e4 / R2 e1: sha256 equal to a full single-path `--recompute`.### Earlier diagnostics of the original checkpoint**Stage-2 parity check on the full data (review item M2).** Stage 2 run with the **released** encoder (`cure.pth` LoRA), 20,000 pairs per trajectory type on all 162k + 162k training images, once with the recipe's endpoint preprocessing and once with ONE control (the final JPEG q70 pass removed; same seed, same pairs). DAS6 job 66720 (`repro/logs/curepar_std_das6_66720.full.log`, `curepar_noq70_das6_66720.full.log`):| | recipe preprocessing | control (no q70) | random ||---|---|---|---|| overlap of the solved W with the released W | 0.892 | 0.864 | 0.125 || cosine of mu to the released mu | 0.999998 | 0.982 | || relative distance of mu | 0.19 % | 19.2 % | || off-diagonal ratio of the released `W^T C_F W` | 0.016 | 0.276 | || fitted (lambda_s, lambda_m, eps) / residual | 0.96, 1.02, 1.0e-3 / 0.036 | 1.03, 0.80, 1.06e-3 / 0.103 | |The subspace overlap barely separates the two pipelines (0.89 vs 0.86, both far above random), so an overlap alone does **not** identify the release's preprocessing. The mu distance (100x) and the off-diagonal ratio (17x) do, and the recipe's pipeline is the one that matches: this is the evidence that the released stage 2 used the endpoint preprocessing assumed here (the earlier subset claim was too strong). Mixing before the q70 step was not tested. With the fitted values the lambdas are 1, 1 and eps 1e-3 as assumed. Even with the released encoder the full-data W overlaps the released one at 0.89, not 1.0: the pair sampling and other unstated details of stage 2 are not pinned down. For the trained encoder stage 2 gave overlap 0.685 with the released W, mu cosine 0.696, and one dominant generalised eigenvalue (2.856, then 0.017) in `curetrain_das6_66658.out`; the released encoder's own spectrum is 2.157, then 0.039.**Where the shortfall comes from (diagnostics, same protocol, `bench_eval --ckpt`).** The three parts of the adapter (LoRA, subspace `W` / `mu`, head) are only meaningful together, so swapping parts between the released and the trained adapter is a sanity check, not a decomposition:| checkpoint | BFree-Online acc / AUROC | SynthWildX | WildRF | RRDataset | job ||---|---|---|---|---|---|| official adapter | 91.64 / 98.08 | 92.69 / 96.50 | 95.89 / 99.14 | 82.04 / 88.88 | (existing rows) || **trained** (our stage 1, 2, 3) | 66.64 / 85.77 | 76.11 / 86.84 | 85.80 / 94.59 | 66.36 / 76.87 | 66721 || A: trained LoRA + released mu / W / head | 48.61 / 38.67 | 35.00 / 16.34 | 35.05 / 11.72 | 33.17 / 25.55 | 66725 || B: released LoRA + trained mu / W / head | 43.68 / 6.53 | 38.44 / 5.17 | 40.50 / 3.35 | 43.15 / 12.87 | 66725 || **D: released LoRA + OUR stage 2 + OUR stage 3** | **91.08 / 98.25** | **92.65 / 96.32** | **95.45 / 98.99** | **81.04 / 86.84** | 66726 |- A and B collapse (AUROC far below 50, the score is anti-correlated): the released `W` / `mu` / head live in the released encoder's feature space and the trained ones in the trained encoder's, so mixed adapters are meaningless. They cannot localise the problem.- **D is the informative one.** Run through SynthScope's stage 2 (the parity run, 20,000 pairs per type, `par_std/subspace.pt`) and stage 3 (head on all 324k clean images, 5 epochs), the *released* encoder reproduces the paper and the official adapter: BFree-Online 91.08 (paper 90.9), SynthWildX 92.65 (92.7), WildRF 95.45 (95.8), RRDataset 81.04 (81.5), all within the repo tolerance and within 1.0 pt of the official adapter. So **our stage-2 solver and stage-3 head trainer are sound, and the evaluation protocol is not the cause; the shortfall of the trained checkpoint comes from stage 1** (the LoRA we trained: ratio regression, 5 epochs, last epoch). Its stage-1 validation loss looks fine (0.5099 against a floor of 0.5), so the loss value does not reveal it.- What stage 1 was missing was then investigated (sections above): mainly over-adaptation (the last epoch), with an early-stopping rule fixed in advance recovering more than half of the gap; augmentation adds a little; the remaining gap (BFree-Online ranking, RealChain / RRDataset / EvalGEN calibration) is not explained.## Usage```bash
14 unmodified lines1516171819202122232 unmodified lines262728293031323 unmodified lines36373839404125 unmodified lines6768697071723 unmodified lines76777879808182838439 unmodified lines12412512612712812913014 unmodified linesInput contract: ``forward`` takes the tensor produced by ``CuReTransform`` (``[B, 3, 336, 336]``,mean=std=0.5 normalized, after the official PNG->JPEG96 / 390-crop / JPEG70 pipeline).Training: the paper's two-stage mixing-ratio-regression recipe is NOT in the official release, so``compute_loss`` is plain cross-entropy on the 2-way head (LoRA + subspace + head trainable). Itexists to satisfy SynthScope's trainer interface; it does not reproduce the paper's training."""import osfrom pathlib import Path2 unmodified linesimport torchimport torch.nn as nnfrom huggingface_hub import hf_hub_downloadfrom omegaconf import DictConfigfrom .official_arch import PECore3 unmodified linesFEATURE_DIM = 1024SUBSPACE_DIM = 128_VISUAL_PREFIX = "visual."def resolve_base_checkpoint(path=None, repo_id: str = BASE_REPO_ID, filename: str = BASE_FILENAME) -> Path:25 unmodified linesself.register_buffer("mu", torch.zeros(FEATURE_DIM))self.register_buffer("W", torch.zeros(FEATURE_DIM, SUBSPACE_DIM))self.head = nn.Linear(SUBSPACE_DIM, 2)if bool(mc.get("load_base_backbone", True)):self._load_base(resolve_base_checkpoint(mc.get("base_checkpoint", None),3 unmodified linesself._init_random_backbone() # architecture-only mode (tests): official params are torch.emptyself._init_trainable()# Everything frozen except the LoRA tensors and the head (the adapter's trainable set).for name, param in self.named_parameters():param.requires_grad = "lora_" in name or name.startswith("head.")# The frozen PE-Core base is loaded above from its own release (``_load_base``), so the released adapter# (LoRA + subspace + head only) does not contain it: the engine accepts exactly these keys as missing.self.pretrained_prefixes = tuple(n for n, p in self.named_parameters() if not p.requires_grad)39 unmodified linesfeatures = self.backbone(images)return self.head((features - self.mu) @ self.W)def compute_loss(self, batch):images, labels, _folder_ids = batchoutputs = self.forward(images)return {"loss": self.criterion(outputs, labels), "outputs": outputs}14 unmodified lines15161718192021222324252627282930313233342 unmodified lines3738394041424344453 unmodified lines495051525354555625 unmodified lines8283848586878889909192939495963 unmodified lines10010110210310410510610710810911039 unmodified lines15015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121214 unmodified linesInput contract: ``forward`` takes the tensor produced by ``CuReTransform`` (``[B, 3, 336, 336]``,mean=std=0.5 normalized, after the official PNG->JPEG96 / 390-crop / JPEG70 pipeline).Training: the official release has no training code. SynthScope implements the paper's recipe(Sec. 3, 4.1-4.2, Appendix A; see README "Training recipe"):* Stage 1 (``ModelConfig.training_stage: ratio``, run through SynthScope's trainer): a linear ratiohead ``ratio_head`` (1024 -> 1, sigmoid) on the adapted features of real/generated pixel mixturesx_a = (1 - a) x_r + a x_g, trained with BCE against the soft target a; only the LoRA tensors and theratio head are trainable, with their own weight decays (``optimizer_param_groups``). Optionalgradient checkpointing per transformer block (``grad_checkpointing``) for the per-GPU batch of 64.* Stages 2 and 3 (``train_stages.py``): the source-response subspace (``mu``, ``W``) from the frozenstage-1 encoder (``subspace.py``) and the 128 -> 2 head; ``adapter_state_dict`` exports the resultwith exactly the released adapter's 100 keys.Without ``training_stage`` ``compute_loss`` is plain cross-entropy on the 2-way head (LoRA + headtrainable); it only satisfies the trainer interface and is not the paper's training."""import osfrom pathlib import Path2 unmodified linesimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom huggingface_hub import hf_hub_downloadfrom torch.utils.checkpoint import checkpointfrom omegaconf import DictConfigfrom .official_arch import PECore3 unmodified linesFEATURE_DIM = 1024SUBSPACE_DIM = 128_VISUAL_PREFIX = "visual."# The released adapter's tensors (cure_adapter.pt): 24 layers x (lora_A_q, lora_B_q, lora_A_v, lora_B_v), mu, W, head.ADAPTER_BUFFERS = ("mu", "W", "head.weight", "head.bias")def resolve_base_checkpoint(path=None, repo_id: str = BASE_REPO_ID, filename: str = BASE_FILENAME) -> Path:25 unmodified linesself.register_buffer("mu", torch.zeros(FEATURE_DIM))self.register_buffer("W", torch.zeros(FEATURE_DIM, SUBSPACE_DIM))self.head = nn.Linear(SUBSPACE_DIM, 2)# Stage 1 of the paper's recipe: mixing-ratio regression with a linear ratio head (Appendix A).self.training_stage = mc.get("training_stage", None)if self.training_stage not in (None, "ratio"):raise ValueError(f"CuRe training_stage must be null or 'ratio', got {self.training_stage!r}")self.grad_checkpointing = bool(mc.get("grad_checkpointing", False))self.lora_weight_decay = float(mc.get("lora_weight_decay", 0.1))self.head_weight_decay = float(mc.get("head_weight_decay", 0.01))if self.training_stage == "ratio":self.ratio_head = nn.Linear(FEATURE_DIM, 1) # PyTorch default init; discarded after stage 1if bool(mc.get("load_base_backbone", True)):self._load_base(resolve_base_checkpoint(mc.get("base_checkpoint", None),3 unmodified linesself._init_random_backbone() # architecture-only mode (tests): official params are torch.emptyself._init_trainable()# Everything frozen except the LoRA tensors and the head (the adapter's trainable set); in stage 1 the ratio# head replaces the 2-way head (which is trained later, on the frozen subspace, by train_stages.py).head_prefix = "ratio_head." if self.training_stage == "ratio" else "head."for name, param in self.named_parameters():param.requires_grad = "lora_" in name or name.startswith(head_prefix)# The frozen PE-Core base is loaded above from its own release (``_load_base``), so the released adapter# (LoRA + subspace + head only) does not contain it: the engine accepts exactly these keys as missing.self.pretrained_prefixes = tuple(n for n, p in self.named_parameters() if not p.requires_grad)39 unmodified linesfeatures = self.backbone(images)return self.head((features - self.mu) @ self.W)def features(self, images: torch.Tensor) -> torch.Tensor:"""Adapted PE Core features ``[B, 1024]`` (fp16 autocast on CUDA, as ``forward``). With ``grad_checkpointing`` intraining each transformer block is recomputed in the backward pass (same values, less activation memory)."""with torch.amp.autocast("cuda", enabled=images.is_cuda):if self.grad_checkpointing and self.training and torch.is_grad_enabled():return self._checkpointed_backbone(images)return self.backbone(images)def _checkpointed_backbone(self, images: torch.Tensor) -> torch.Tensor:"""``PECore.forward`` (official_arch.py) step for step, with ``torch.utils.checkpoint`` around every block."""bb = self.backboneif images.ndim != 4 or tuple(images.shape[1:]) != (3, 336, 336):raise ValueError("Expected image tensors with shape [N, 3, 336, 336]")batch = images.shape[0]x = bb.conv1(images).permute(0, 2, 3, 1).reshape(batch, 576, 1024)cls = bb.class_embedding.view(1, 1, -1).expand(batch, -1, -1)x = torch.cat([cls, x], dim=1)x = x + bb.positional_embedding[None]x = bb.ln_pre(x)for block in bb.transformer.resblocks:x = checkpoint(block, x, use_reentrant=False)return bb.ln_post(x)[:, 1:].mean(dim=1).float()def optimizer_param_groups(self):"""Stage 1: AdamW groups with the paper's weight decays (0.1 on the LoRA tensors, 0.01 on the ratio head, all ofits parameters); used by the trainer instead of its single group. ``None`` otherwise (the trainer's default)."""if self.training_stage != "ratio":return Nonenamed = [(n, p) for n, p in self.named_parameters() if p.requires_grad]return [{"params": [p for n, p in named if "lora_" in n], "weight_decay": self.lora_weight_decay},{"params": [p for n, p in named if "lora_" not in n], "weight_decay": self.head_weight_decay}]@staticmethoddef _require_grad_scaler(images: torch.Tensor) -> None:"""``features`` always runs fp16 autocast on CUDA, so CUDA training needs a gradient scaler; ``accelerate launch--mixed_precision fp16`` (exported as ACCELERATE_MIXED_PRECISION, which the trainer's Accelerator reads) provides it.Without it the fp16 gradients would underflow silently, so fail loudly instead."""if images.is_cuda and torch.is_grad_enabled() and os.environ.get("ACCELERATE_MIXED_PRECISION", "no") != "fp16":raise RuntimeError("CuRe stage 1 runs the backbone in fp16 autocast and needs a gradient scaler: launch with ""`accelerate launch --mixed_precision fp16` (experiments/image/cure.sh does)")def compute_loss(self, batch):images, targets, _folder_ids = batchif self.training_stage == "ratio":# Eq. 3-4: sigmoid ratio head, BCE with the mixing ratio as the soft target (targets = alpha in [0, 1]).self._require_grad_scaler(images)logits = self.ratio_head(self.features(images)).squeeze(-1).float()loss = F.binary_cross_entropy_with_logits(logits, targets.float())return {"loss": loss, "outputs": torch.sigmoid(logits)}outputs = self.forward(images)return {"loss": self.criterion(outputs, targets), "outputs": outputs}def adapter_state_dict(self) -> dict:"""The trained parameters in the released adapter's format: exactly its 100 keys (96 LoRA tensors, ``mu``,``W`` [1024, 128], ``head.weight``, ``head.bias``), fp32, so the file loads like ``cure_adapter.pt``."""state = self.state_dict()out = {k: v.detach().float().cpu().contiguous() for k, v in state.items()if "lora_" in k or k in ADAPTER_BUFFERS}assert len(out) == 100, f"expected the adapter's 100 tensors, got {len(out)}"return out
36 unmodified lines3738394041424313 unmodified lines5758596061626336 unmodified linesclass CuReTransform:"""PIL image -> normalized float32 tensor ``[3, 336, 336]`` (picklable, stateless)."""def __call__(self, img: Image.Image) -> torch.Tensor:source_format = img.info.get(SRC_FORMAT_KEY) or img.format13 unmodified linesleft = (arr.shape[1] - RESIZE_SIZE) // 2arr = np.ascontiguousarray(arr[top:top + RESIZE_SIZE, left:left + RESIZE_SIZE])arr = _cubic_resize(arr, INPUT_SIZE, INPUT_SIZE)_, encoded = cv2.imencode(".jpg", arr, (int(cv2.IMWRITE_JPEG_QUALITY), EVAL_JPEG_QUALITY))arr = cv2.imdecode(encoded, cv2.IMREAD_UNCHANGED)arr = (arr.astype(np.float32) - 127.5) / 127.5return torch.from_numpy(arr).permute(2, 0, 1).contiguous()36 unmodified lines3738394041424344454647484913 unmodified lines636465666768697036 unmodified linesclass CuReTransform:"""PIL image -> normalized float32 tensor ``[3, 336, 336]`` (picklable, stateless).``eval_jpeg_quality`` is the final JPEG pass (official: 70); ``None`` skips it. Only the stage-2 parity control of thetraining recipe (``train_stages.py --control no_q70``) changes it; every registered pipeline uses the default."""def __init__(self, eval_jpeg_quality: int | None = EVAL_JPEG_QUALITY):self.eval_jpeg_quality = eval_jpeg_qualitydef __call__(self, img: Image.Image) -> torch.Tensor:source_format = img.info.get(SRC_FORMAT_KEY) or img.format13 unmodified linesleft = (arr.shape[1] - RESIZE_SIZE) // 2arr = np.ascontiguousarray(arr[top:top + RESIZE_SIZE, left:left + RESIZE_SIZE])arr = _cubic_resize(arr, INPUT_SIZE, INPUT_SIZE)if self.eval_jpeg_quality is not None:_, encoded = cv2.imencode(".jpg", arr, (int(cv2.IMWRITE_JPEG_QUALITY), self.eval_jpeg_quality))arr = cv2.imdecode(encoded, cv2.IMREAD_UNCHANGED)arr = (arr.astype(np.float32) - 127.5) / 127.5return torch.from_numpy(arr).permute(2, 0, 1).contiguous()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100"""CuRe stage 2: the interference-suppressed source-response subspace (arXiv 2609.14316, Sec. 3.2, Eq. 5-11).
The official release has no training code; this follows the paper's equations. For trajectories T in {RF, RR, FF}(real->generated, real->real, generated->generated) with features z_{i,a} of the mixtures on the gridA = {0, .2, .4, .6, .8, 1}:
b_i^T = sum_a (a - a_bar)(z_{i,a} - z_bar_i) / sum_a (a - a_bar)^2 (Eq. 6, the per-trajectory slope) C_F = E_i[b_i^RF b_i^RF^T] (Eq. 7) C_M = E_i[b_i^RR b_i^RR^T] + E_i[b_i^FF b_i^FF^T] (Eq. 8) C_S = Cov_i(z_bar_i^RF) (Eq. 9)
each divided by its trace, then the generalised eigenproblem
C_F w = g (lambda_s C_S + lambda_m C_M + eps I) w (Eq. 10)
whose k = 128 leading eigenvectors are W [1024, 128] (Eq. 11); mu is the mean RF trajectory feature (Sec. 3.3).
Unspecified in the paper (documented assumptions, see the README "Training recipe"): lambda_s, lambda_m, eps (defaultsbelow: 1, 1, 1e-3; with the released encoder our statistics make the released W B-orthonormal for about lambda_s 0.9,lambda_m 1.0, eps 1.05e-3, job 283104); the scale of the eigenvectors (here B-orthonormal, W^T B W = I, the convention of LAPACK's / scipy's generalisedsymmetric solver; the released W is not unit-norm, its columns have norms 6.8-8.8); C_S uses the 1/N covariance (the tracenormalisation removes the factor). Everything is computed in float64."""from __future__ import annotations
import torch
GRID = (0.0, 0.2, 0.4, 0.6, 0.8, 1.0)DEFAULT_LAMBDA_S = 1.0DEFAULT_LAMBDA_M = 1.0DEFAULT_EPS = 1e-3
def slope_weights(grid=GRID) -> torch.Tensor: """``c_a = (a - a_bar) / sum (a - a_bar)^2`` so that Eq. 6 is ``b_i = sum_a c_a z_{i,a}`` (the ``z_bar`` term vanishes because ``sum_a (a - a_bar) = 0``).""" a = torch.tensor(grid, dtype=torch.float64) centered = a - a.mean() return centered / (centered ** 2).sum()
def trajectory_summary(z: torch.Tensor, grid=GRID) -> tuple[torch.Tensor, torch.Tensor]: """``z`` [N, len(grid), D] trajectory features -> (slopes b [N, D] (Eq. 6), means z_bar [N, D]), float64.""" z = z.double() c = slope_weights(grid).to(z.device) return torch.einsum("a,nad->nd", c, z), z.mean(dim=1)
def second_moment(b: torch.Tensor) -> torch.Tensor: """``E_i[b_i b_i^T]`` (uncentred), float64.""" b = b.double() return b.T @ b / b.shape[0]
def covariance(x: torch.Tensor) -> torch.Tensor: """``Cov_i(x_i)`` with the 1/N normalisation, float64.""" x = x.double() x = x - x.mean(dim=0, keepdim=True) return x.T @ x / x.shape[0]
def trace_normalised(c: torch.Tensor) -> torch.Tensor: return c / torch.trace(c)
def statistics(b_rf, b_rr, b_ff, zbar_rf) -> dict: """Eq. 7-9, each normalised by its trace, plus mu (the mean RF trajectory feature = the mean of the z_bar^RF).""" return { "C_F": trace_normalised(second_moment(b_rf)), "C_M": trace_normalised(second_moment(b_rr) + second_moment(b_ff)), "C_S": trace_normalised(covariance(zbar_rf)), "mu": zbar_rf.double().mean(dim=0), }
def solve(c_f, c_m, c_s, k=128, lambda_s=DEFAULT_LAMBDA_S, lambda_m=DEFAULT_LAMBDA_M, eps=DEFAULT_EPS): """Eq. 10-11: the ``k`` largest generalised eigenpairs of ``C_F w = g B w``, ``B = lambda_s C_S + lambda_m C_M + eps I``. Cholesky-whitened symmetric problem: ``B = L L^T``, ``M = L^-1 C_F L^-T = V G V^T``, ``w = L^-T v`` (so ``W^T B W = I``). Returns ``(W [D, k], gammas [k])``, eigenvalues in descending order, float64.""" c_f, c_m, c_s = c_f.double(), c_m.double(), c_s.double() d = c_f.shape[0] b = lambda_s * c_s + lambda_m * c_m + eps * torch.eye(d, dtype=torch.float64, device=c_f.device) b = (b + b.T) / 2 chol = torch.linalg.cholesky(b) eye = torch.eye(d, dtype=torch.float64, device=c_f.device) l_inv = torch.linalg.solve_triangular(chol, eye, upper=False) m = l_inv @ ((c_f + c_f.T) / 2) @ l_inv.T gammas, v = torch.linalg.eigh((m + m.T) / 2) # ascending order = torch.argsort(gammas, descending=True)[:k] w = l_inv.T @ v[:, order] return w, gammas[order]
def subspace_overlap(w_a: torch.Tensor, w_b: torch.Tensor) -> float: """Mean squared cosine of the principal angles between span(w_a) and span(w_b) (1 = same subspace; two random k-dim subspaces of R^D give about k / D).""" qa, _ = torch.linalg.qr(w_a.double()) qb, _ = torch.linalg.qr(w_b.double()) s = torch.linalg.svdvals(qa.T @ qb) return float((s ** 2).mean())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""CuRe stage-1 investigation, R3: DDA-style training augmentation for the stage-1 endpoints (an ASSUMPTION under test, notpart of the paper's stated recipe: CuRe, arXiv 2609.14316, Sec. 4.1, follows "the setting of DDA" for format alignment andstates no augmentation).
Per endpoint (a real or a generated image), in this order: 1. format alignment, as the eval pipeline: a PNG source is re-encoded as JPEG q96 (CuRe Appendix A) 2. DDA's training augmentations, exactly DDA's ``create_train_transforms`` list (vendored in ``models/image/dda/official_train_data.py``) without its last three steps: RandomJPEG q55-100 p 0.15, horizontal and vertical flips p 0.5, Gaussian noise (std 55) p 0.1, pepper noise p 0.1, one of {Gaussian blur k3, k5, median 3, motion 5} p 0.2, sharpen p 0.1, colour jitter (0.4, 0.4, 0.4, 0.175) p 0.2, grayscale p 0.1 3. CuRe's fixed geometry with DDA's random crop in place of the centre crop: SmallestMaxSize(390, cubic) -> RandomCrop(390) (replaces CenterCrop(390); DDA's ``PadRandomCrop`` never pads here because the short side is 390) -> Resize(336, cubic) -> JPEG q70 -> mean = std = 0.5Steps 2-3 draw from one seed per (pair, epoch) that is SHARED by the two endpoints of a pair, as DDA's``ComposedTransforms`` replays one RNG state for the real and the fake of a pair: both endpoints get the same decisions(whether each step applies, flips, blur kind, jitter factors, grayscale, JPEG quality, relative crop position), so theaugmentation cannot vary with the mixing ratio. Unlike DDA's pairs (a real and its same-size reconstruction) CuRe'sendpoints differ in size, so the global RNGs are re-seeded before every step (size-dependent draws such as the noise fieldwould otherwise desynchronise the later decisions); only the noise / pepper realisations differ between the endpoints. Not used: DDA's extra re-scaledcopies (``build_item``'s 0.2-1.0 / 1.0-3.5 resized samples) and its pixel / frequency blending of reconstructions, which areseparate DDA-specific samples rather than per-image augmentations. Validation, stage 2 and stage 3 stay un-augmented.With ``augment=False`` the output equals the eval pipeline ``CuReTransform`` bit for bit (tests/test_cure_recipe.py)."""import ioimport random
import cv2import numpy as npimport torchfrom PIL import Image
from models.image.dda.official_train_data import create_train_transformsfrom .preprocess import EVAL_JPEG_QUALITY, INPUT_SIZE, PNG_REENCODE_QUALITY, RESIZE_SIZE, SRC_FORMAT_KEY
def _dda_augmentations(): """DDA's train transform list without PadRandomCrop / ToTensor / Normalize (parameters unchanged).""" steps = create_train_transforms(size=RESIZE_SIZE).transforms names = [type(t).__name__ for t in steps[-3:]] assert names == ["PadRandomCrop", "ToTensor", "Normalize"], names return steps[:-3]
class CuReDDAEndpoint: """PIL image (+ source-format hint) and a seed -> normalized float32 tensor [3, 336, 336]."""
def __init__(self, augment: bool = True): self.augment = augment self.steps = _dda_augmentations() if augment else []
def __call__(self, img: Image.Image, seed: int | None = None) -> torch.Tensor: source_format = img.info.get(SRC_FORMAT_KEY) or img.format image = img.convert("RGB") if source_format == "PNG": buf = io.BytesIO() image.save(buf, format="JPEG", quality=PNG_REENCODE_QUALITY) buf.seek(0) with Image.open(buf) as dec: image = dec.convert("RGB") image.load() crop_rng = None if self.augment: # replay one RNG state per pair (DDA's ComposedTransforms); restore the caller's global (CPU) states afterwards; # the CUDA generators are never touched states = (random.getstate(), np.random.get_state(), torch.get_rng_state()) try: # re-seed before EVERY step: the two endpoints differ in size, so size-dependent draws (noise, pepper # coordinates) would otherwise desynchronise all later decisions; per-step seeding keeps every decision # (apply?, which blur, jitter factors, flips, JPEG quality, ...) identical for the pair for k, step in enumerate(self.steps): s = (seed * 1_000_003 + k) % 2 ** 31 # torch: the CPU default generator only (torch.manual_seed would also re-seed every CUDA device) random.seed(s); np.random.seed(s); torch.default_generator.manual_seed(s) image = step(image) image = image.convert("RGB") finally: random.setstate(states[0]); np.random.set_state(states[1]); torch.set_rng_state(states[2]) crop_rng = random.Random(seed + 1) arr = np.asarray(image) h, w = arr.shape[:2] s = RESIZE_SIZE / min(h, w) nh, nw = max(1, round(h * s)), max(1, round(w * s)) if (nh, nw) != (h, w): arr = cv2.resize(arr, (nw, nh), interpolation=cv2.INTER_CUBIC) if crop_rng is None: top, left = (arr.shape[0] - RESIZE_SIZE) // 2, (arr.shape[1] - RESIZE_SIZE) // 2 else: # the same RELATIVE crop position for both endpoints (their sizes differ) fy, fx = crop_rng.random(), crop_rng.random() top, left = round(fy * (arr.shape[0] - RESIZE_SIZE)), round(fx * (arr.shape[1] - RESIZE_SIZE)) arr = np.ascontiguousarray(arr[top:top + RESIZE_SIZE, left:left + RESIZE_SIZE]) if arr.shape[:2] != (INPUT_SIZE, INPUT_SIZE): arr = cv2.resize(arr, (INPUT_SIZE, INPUT_SIZE), interpolation=cv2.INTER_CUBIC) _, enc = cv2.imencode(".jpg", arr, (int(cv2.IMWRITE_JPEG_QUALITY), EVAL_JPEG_QUALITY)) arr = cv2.imdecode(enc, cv2.IMREAD_UNCHANGED) return torch.from_numpy((arr.astype(np.float32) - 127.5) / 127.5).permute(2, 0, 1).contiguous()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369"""CuRe stages 2 and 3 (arXiv 2609.14316, Sec. 3.2-3.3, Appendix A), after stage 1 (experiments/image/cure.sh).
python -m models.image.cure.train_stages stage2 --lora <stage-1 model_last.pth> --data <GenImage SD v1.4> --out <dir> python -m models.image.cure.train_stages stage3 --lora <stage-1 model_last.pth> --data <GenImage SD v1.4> --out <dir>
stage2 freezes the stage-1 encoder, draws ``--pairs`` (20,000) endpoint pairs per trajectory type (RF real->generated, RR real->real, FF generated->generated; independent random endpoints, a same-class pair never uses one image twice), encodes the six mixtures of each on the grid {0, .2, .4, .6, .8, 1}, keeps the per-trajectory slope and mean (Eq. 6) in ``<out>/trajectories.pt`` and solves Eq. 7-11 (``subspace.py``) into ``<out>/subspace.pt`` (W [1024, 128], mu, the generalised eigenvalues). A rerun with other ``--lambda-s/--lambda-m/--eps`` reuses the cached trajectories. ``--reference-adapter`` (the released cure_adapter.pt) prints the overlap of the solved subspace with the released W, the distance of mu to the released mu, and the (lambda_s, lambda_m, eps) for which the released W is B-orthonormal under our C_S / C_M (a least-squares fit; a check of the unspecified choices).stage3 encodes the training images once (``<out>/head_features.pt``; all 162k + 162k by default, clean endpoints with the same preprocessing), projects them, ``u = W^T (z - mu)``, and trains only Linear(128, 2) with dropout 0.05 on u: cross-entropy, AdamW lr 2e-4, weight decay 0.1, batch 256, 5 epochs (constant lr: the paper names no schedule). The result is written as ``<out>/cure_trained.pth`` with exactly the released adapter's 100 keys (96 LoRA tensors, mu, W, head), loadable as ``cure.pth`` (``bench_eval --model cure --ckpt``); the export is checked by reloading it into a fresh model and comparing its logits with the trained head's on cached features.
Both stages run on one GPU (fp16 autocast inside the model, as the released inference). ``--lora`` takes any state dictholding the 96 LoRA tensors (a stage-1 trainer checkpoint, or the released adapter for the parity check)."""from __future__ import annotations
import argparseimport jsonimport sysimport timefrom pathlib import Path
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom omegaconf import OmegaConffrom torch.utils.data import DataLoader, Dataset
from dataset import CuReEndpoints, cure_mixfrom transformations import AIGITransformationsfrom .preprocess import CuReTransformfrom .cure import FEATURE_DIM, SUBSPACE_DIM, SynthScopeCuReModelfrom . import subspace as S
ROOT = Path(__file__).resolve().parents[3]MODEL_YAML = ROOT / "conf" / "model" / "image" / "cure.yaml"TYPES = ("RF", "RR", "FF")
def build_model(lora_path: str | None, device: str) -> SynthScopeCuReModel: """The frozen CuRe encoder (PE Core base + the LoRA tensors of ``lora_path``), eval mode on ``device``.""" cfg = OmegaConf.create({"ModelConfig": OmegaConf.load(MODEL_YAML), "TrainerConfig": {}}) model = SynthScopeCuReModel(cfg) if lora_path: state = torch.load(lora_path, map_location="cpu", weights_only=True, mmap=True) state = state.get("model", state) if isinstance(state, dict) else state lora = {k: v for k, v in state.items() if "lora_" in k} if len(lora) != 96: raise RuntimeError(f"{lora_path}: expected 96 LoRA tensors, found {len(lora)}") missing, unexpected = model.load_state_dict(lora, strict=False) if unexpected or any("lora_" in k for k in missing): raise RuntimeError(f"LoRA load mismatch: unexpected={unexpected[:4]}") model.requires_grad_(False) return model.to(device).eval()
def endpoint_transform(control: str = "none"): """The stage-1 endpoint preprocessing (the model config's eval list), see ``dataset.CuReEndpoints``. ``control="no_q70"`` drops the final JPEG q70 pass: a deliberately different pipeline, used only to show whether the parity check against the released W / mu discriminates preprocessing choices (``--control``).""" if control == "no_q70": return CuReTransform(eval_jpeg_quality=None) if control != "none": raise ValueError(f"unknown control {control!r}") return AIGITransformations(list(OmegaConf.load(MODEL_YAML).eval_transform_list))
def _draw_indices(n: int, n_pairs: int, gen: torch.Generator) -> torch.Tensor: """``n_pairs`` indices into ``n`` images: without replacement while ``n`` is large enough, else with replacement.""" return torch.randperm(n, generator=gen)[:n_pairs] if n_pairs <= n else torch.randint(n, (n_pairs,), generator=gen)
def draw_pairs(n_pairs: int, n_a: int, n_b: int, same_class: bool, gen: torch.Generator) -> torch.Tensor: """``[n_pairs, 2]`` endpoint indices: independent uniform draws (without replacement while the class is large enough); for a same-class pair the second index is uniform over the other images of the class.""" first = _draw_indices(n_a, n_pairs, gen) if same_class: second = (first + 1 + torch.randint(n_a - 1, (n_pairs,), generator=gen)) % n_a else: second = _draw_indices(n_b, n_pairs, gen) return torch.stack([first, second], dim=1)
class TrajectoryPairs(Dataset): """Endpoint pairs ``(x_0, x_1, type index, pair index)``; the mixtures are formed on the GPU."""
def __init__(self, ep: CuReEndpoints, pairs: dict[str, torch.Tensor]): self.ep = ep self.items = [(t, i, int(a), int(b)) for t in TYPES for i, (a, b) in enumerate(pairs[t].tolist())]
def __len__(self): return len(self.items)
def __getitem__(self, idx): t, i, a, b = self.items[idx] lists = {"RF": (self.ep.reals, self.ep.fakes), "RR": (self.ep.reals, self.ep.reals), "FF": (self.ep.fakes, self.ep.fakes)}[t] g = torch.Generator().manual_seed(idx) x0 = self.ep.load_any(lists[0], a, lambda: int(torch.randint(len(lists[0]), (), generator=g))) x1 = self.ep.load_any(lists[1], b, lambda: int(torch.randint(len(lists[1]), (), generator=g))) return x0, x1, TYPES.index(t), i
class LabelledImages(Dataset): """All (or the first ``max_images``) training images with labels 0 = real, 1 = generated."""
def __init__(self, ep: CuReEndpoints): self.ep = ep self.items = [(p, 0) for p in ep.reals] + [(p, 1) for p in ep.fakes]
def __len__(self): return len(self.items)
def __getitem__(self, idx): paths = self.ep.reals if self.items[idx][1] == 0 else self.ep.fakes offset = 0 if self.items[idx][1] == 0 else len(self.ep.reals) g = torch.Generator().manual_seed(idx) return self.ep.load_any(paths, idx - offset, lambda: int(torch.randint(len(paths), (), generator=g))), self.items[idx][1]
def encode_trajectories(model, loader, n_pairs: int, device: str) -> dict: """Slopes and means of every trajectory: ``{"b_RF": [N, D], "zbar_RF": [N, D], ...}`` (float32).""" grid = torch.tensor(S.GRID, device=device).view(1, -1, 1, 1, 1) out = {f"{k}_{t}": torch.zeros(n_pairs, FEATURE_DIM) for t in TYPES for k in ("b", "zbar")} done, start = 0, time.time() with torch.no_grad(): for step, (x0, x1, types, idx) in enumerate(loader): x0, x1 = x0.to(device, non_blocking=True), x1.to(device, non_blocking=True) mixed = cure_mix(x0.unsqueeze(1), x1.unsqueeze(1), grid) # [P, 6, 3, 336, 336] z = model.features(mixed.flatten(0, 1)).view(x0.shape[0], len(S.GRID), FEATURE_DIM) b, zbar = S.trajectory_summary(z) for j in range(x0.shape[0]): t = TYPES[int(types[j])] out[f"b_{t}"][int(idx[j])] = b[j].float().cpu() out[f"zbar_{t}"][int(idx[j])] = zbar[j].float().cpu() done += x0.shape[0] if (step + 1) % 50 == 0: rate = done / (time.time() - start) print(f" trajectories {done}/{3 * n_pairs} ({rate:.1f} pairs/s, {6 * rate:.0f} images/s)", flush=True) return out
def fit_normalisation(w_ref: torch.Tensor, c_s: torch.Tensor, c_m: torch.Tensor) -> dict: """Least squares (lambda_s, lambda_m, eps) with ``W_ref^T (lambda_s C_S + lambda_m C_M + eps I) W_ref = I`` over all entries: if the released W is B-orthonormal (our solver's convention) under statistics like ours, this recovers its B. ``rel_residual`` = ||fit - I||_F / ||I||_F.""" w = w_ref.double() blocks = [w.T @ c_s.double() @ w, w.T @ c_m.double() @ w, w.T @ w] a = torch.stack([blk.flatten() for blk in blocks], dim=1) target = torch.eye(w.shape[1], dtype=torch.float64).flatten() coef = torch.linalg.lstsq(a, target.unsqueeze(1)).solution.squeeze(1) resid = (a @ coef - target).norm() / target.norm() return {"lambda_s": float(coef[0]), "lambda_m": float(coef[1]), "eps": float(coef[2]), "rel_residual": float(resid)}
def reference_report(stats: dict, w: torch.Tensor, adapter_path: str) -> dict: ref = torch.load(adapter_path, map_location="cpu", weights_only=True) w_ref, mu_ref = ref["W"].double(), ref["mu"].double() mu = stats["mu"] g = w_ref.T @ stats["C_F"] @ w_ref report = { "overlap_with_released_W": S.subspace_overlap(w, w_ref), "overlap_random_baseline": SUBSPACE_DIM / FEATURE_DIM, "mu_cosine": float(F.cosine_similarity(mu, mu_ref, dim=0)), "mu_rel_dist": float((mu - mu_ref).norm() / mu_ref.norm()), "released_W_col_norms": [float(x) for x in w_ref.norm(dim=0)[:4]], "solved_W_col_norms": [float(x) for x in w.norm(dim=0)[:4]], # released W against our C_F: a generalised eigenbasis makes W^T C_F W diagonal "released_WtCfW_offdiag_ratio": float((g - torch.diag(torch.diag(g))).norm() / torch.diag(g).norm()), "normalisation_fit": fit_normalisation(w_ref, stats["C_S"], stats["C_M"]), } return report
def stage2(args) -> None: out = Path(args.out); out.mkdir(parents=True, exist_ok=True) traj_path = out / "trajectories.pt" if traj_path.exists() and not args.recompute: print(f"[stage2] reusing {traj_path}", flush=True) traj = torch.load(traj_path, map_location="cpu", weights_only=True) else: ep = CuReEndpoints(args.data, "train", endpoint_transform(args.control), args.max_images) gen = torch.Generator().manual_seed(args.seed) n_r, n_f = len(ep.reals), len(ep.fakes) pairs = {"RF": draw_pairs(args.pairs, n_r, n_f, False, gen), "RR": draw_pairs(args.pairs, n_r, n_r, True, gen), "FF": draw_pairs(args.pairs, n_f, n_f, True, gen)} print(f"[stage2] {n_r} real / {n_f} generated images, {args.pairs} pairs per type x 6 ratios " f"= {18 * args.pairs} forwards", flush=True) model = build_model(args.lora, args.device) loader = DataLoader(TrajectoryPairs(ep, pairs), batch_size=args.batch_pairs, shuffle=False, num_workers=args.workers, pin_memory=True) traj = encode_trajectories(model, loader, args.pairs, args.device) traj["pairs"] = pairs traj["meta"] = json.dumps({"lora": args.lora, "data": args.data, "pairs": args.pairs, "seed": args.seed, "max_images": args.max_images, "control": args.control}) torch.save(traj, traj_path) del model stats = S.statistics(traj["b_RF"], traj["b_RR"], traj["b_FF"], traj["zbar_RF"]) w, gammas = S.solve(stats["C_F"], stats["C_M"], stats["C_S"], k=args.k, lambda_s=args.lambda_s, lambda_m=args.lambda_m, eps=args.eps) result = {"W": w.float(), "mu": stats["mu"].float(), "gammas": gammas, "config": {"k": args.k, "lambda_s": args.lambda_s, "lambda_m": args.lambda_m, "eps": args.eps}} print(f"[stage2] solved: k={args.k}, lambda_s={args.lambda_s}, lambda_m={args.lambda_m}, eps={args.eps}; " f"top eigenvalues {[round(float(x), 3) for x in gammas[:5]]}, k-th {float(gammas[-1]):.4f}", flush=True) if args.reference_adapter: report = reference_report(stats, w, args.reference_adapter) result["reference_report"] = report print("[stage2] vs released adapter: " + json.dumps(report), flush=True) torch.save(result, out / args.subspace_name) print(f"[stage2] wrote {out / args.subspace_name}", flush=True)
def encode_images(model, loader, device: str) -> tuple[torch.Tensor, torch.Tensor]: feats, labels, start = [], [], time.time() with torch.no_grad(): for i, (x, y) in enumerate(loader): feats.append(model.features(x.to(device, non_blocking=True)).float().cpu()) labels.append(y) if (i + 1) % 100 == 0: n = sum(len(f) for f in feats) print(f" head features {n}/{len(loader.dataset)} ({n / (time.time() - start):.0f} images/s)", flush=True) return torch.cat(feats), torch.cat(labels)
def train_head(u: torch.Tensor, y: torch.Tensor, args) -> nn.Linear: """Linear(128, 2) on ``u`` with dropout on its input: CE, AdamW, constant lr, shuffled mini-batches.""" torch.manual_seed(args.seed) head = nn.Linear(SUBSPACE_DIM, 2).to(u.device) drop = nn.Dropout(args.dropout) opt = torch.optim.AdamW(head.parameters(), lr=args.lr, weight_decay=args.weight_decay) gen = torch.Generator().manual_seed(args.seed) for epoch in range(args.epochs): head.train(); drop.train() order = torch.randperm(len(y), generator=gen).to(u.device) total, correct = 0.0, 0 for start in range(0, len(y), args.batch): idx = order[start:start + args.batch] logits = head(drop(u[idx])) loss = F.cross_entropy(logits, y[idx]) opt.zero_grad(); loss.backward(); opt.step() total += loss.item() * len(idx) correct += int((logits.argmax(1) == y[idx]).sum()) head.eval() with torch.no_grad(): pred = head(u).argmax(1) real_acc = float((pred[y == 0] == 0).float().mean()) fake_acc = float((pred[y == 1] == 1).float().mean()) print(f"[stage3] epoch {epoch}: train loss {total / len(y):.4f} (dropout on), train acc {correct / len(y):.4f}; " f"eval-mode acc real {real_acc:.4f} / fake {fake_acc:.4f}, lr {opt.param_groups[0]['lr']:.1e}", flush=True) return head.eval()
def stage3(args) -> None: out = Path(args.out); out.mkdir(parents=True, exist_ok=True) sub = torch.load(args.subspace or out / "subspace.pt", map_location="cpu", weights_only=True) w, mu = sub["W"].float(), sub["mu"].float() feat_path = out / "head_features.pt" ep = CuReEndpoints(args.data, "train", endpoint_transform(), args.max_images) model = build_model(args.lora, args.device) if feat_path.exists() and not args.recompute: print(f"[stage3] reusing {feat_path}", flush=True) cache = torch.load(feat_path, map_location="cpu", weights_only=True) z, y = cache["z"], cache["y"] encode_batch = int(cache["encode_batch"]) if "encode_batch" in cache else None else: print(f"[stage3] encoding {len(ep.reals)} real + {len(ep.fakes)} generated images", flush=True) loader = DataLoader(LabelledImages(ep), batch_size=args.encode_batch, shuffle=False, num_workers=args.workers, pin_memory=True) z, y = encode_images(model, loader, args.device) encode_batch = args.encode_batch torch.save({"z": z, "y": y, "encode_batch": encode_batch}, feat_path) # the export check matches this batch size dev = args.device u = ((z.to(dev) - mu.to(dev)) @ w.to(dev)).float() head = train_head(u, y.to(dev), args)
# export in the released adapter's format and check it reproduces the trained head on real inputs with torch.no_grad(): model.mu.copy_(mu.to(dev)); model.W.copy_(w.to(dev)) model.head.weight.copy_(head.weight); model.head.bias.copy_(head.bias) adapter = model.adapter_state_dict() torch.save(adapter, out / "cure_trained.pth") print(f"[stage3] wrote {out / 'cure_trained.pth'} ({len(adapter)} tensors)", flush=True) check = build_model(None, dev) missing, unexpected = check.load_state_dict(torch.load(out / "cure_trained.pth", map_location="cpu", weights_only=True), strict=False) stray = [k for k in missing if "lora_" in k or k in ("mu", "W", "head.weight", "head.bias")] # The reloaded model runs at the SAME batch size and precision (fp16 autocast) the cached features were encoded with # (--encode-batch): fp16 kernels can give batch-size-dependent results (measured on an RTX 6000 Ada, job 285054: # max |feature diff| 0.29 at |z| <= 82 between batches of 64 and 128, bit-identical at equal batch size), which is a # GPU property, not an export error. One batch of reals and one of generated images; the tolerance is unchanged. if encode_batch is None: print(f"[stage3] WARNING: {feat_path} records no encode batch size; assuming --encode-batch {args.encode_batch}", flush=True) encode_batch = args.encode_batch elif encode_batch != args.encode_batch: print(f"[stage3] WARNING: cached features were encoded in batches of {encode_batch}, not --encode-batch " f"{args.encode_batch}; the export check uses {encode_batch}", flush=True) n_r = len(ep.reals) nb = max(1, min(encode_batch, n_r, len(ep.fakes))) logits_export, idx = [], [] with torch.no_grad(): for blk in (list(range(nb)), [n_r + i for i in range(nb)]): xs = torch.stack([ep.load(ep.reals[i]) if i < n_r else ep.load(ep.fakes[i - n_r]) for i in blk]).to(dev) logits_export.append(check(xs).float().cpu()) idx += blk logits_export = torch.cat(logits_export) logits_cached = head(u[torch.tensor(idx).to(dev)]).float().cpu() diff = float((logits_export - logits_cached).abs().max()) print(f"[stage3] export check: missing adapter keys {stray}, unexpected {unexpected}; reloaded-model logits vs trained " f"head on cached features, max |diff| {diff:.2e} over {len(idx)} images (batches of {nb}, as encoded)", flush=True) # informational only, not a gate: the same comparison with one batch of 32 + 32 images (the check's former batch) n = min(64, 2 * nb) probe = [ep.load(ep.reals[i]) for i in range(n // 2)] + [ep.load(ep.fakes[i]) for i in range(n - n // 2)] pidx = torch.tensor(list(range(n // 2)) + [n_r + i for i in range(n - n // 2)]) with torch.no_grad(): alt = float((check(torch.stack(probe).to(dev)).float().cpu() - head(u[pidx.to(dev)]).float().cpu()).abs().max()) print(f"[stage3] batch-size sensitivity on this GPU (informational, not a gate): reloaded-model logits in one batch of " f"{n} vs cached features encoded in batches of {encode_batch}: max |diff| {alt:.2e}", flush=True) if stray or unexpected or diff > 1e-2: raise RuntimeError("exported adapter does not reproduce the trained head")
def main(argv=None) -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = ap.add_subparsers(dest="stage", required=True) for name in ("stage2", "stage3"): p = sub.add_parser(name) p.add_argument("--lora", required=True, help="state dict with the 96 stage-1 LoRA tensors (trainer model_last.pth)") p.add_argument("--data", required=True, help="GenImage SD v1.4 root (train/real, train/fake)") p.add_argument("--out", required=True) p.add_argument("--max-images", type=int, default=None, help="first N reals and N fakes of the split (smoke runs)") p.add_argument("--workers", type=int, default=8) p.add_argument("--seed", type=int, default=0) p.add_argument("--device", default="cuda") p.add_argument("--recompute", action="store_true", help="re-encode even if the cached features exist") p2 = sub.choices["stage2"] p2.add_argument("--pairs", type=int, default=20000, help="endpoint pairs per trajectory type (paper: 20,000)") p2.add_argument("--batch-pairs", type=int, default=16, help="pairs per forward (x 6 mixtures)") p2.add_argument("--k", type=int, default=SUBSPACE_DIM) p2.add_argument("--lambda-s", type=float, default=S.DEFAULT_LAMBDA_S) p2.add_argument("--lambda-m", type=float, default=S.DEFAULT_LAMBDA_M) p2.add_argument("--eps", type=float, default=S.DEFAULT_EPS) p2.add_argument("--reference-adapter", default=None, help="released cure_adapter.pt: compare W / mu with it") p2.add_argument("--control", choices=["none", "no_q70"], default="none", help="parity control only: preprocess the endpoints without the final JPEG q70 pass") p2.add_argument("--subspace-name", default="subspace.pt") p3 = sub.choices["stage3"] p3.add_argument("--subspace", default=None, help="default <out>/subspace.pt") p3.add_argument("--epochs", type=int, default=5) p3.add_argument("--lr", type=float, default=2e-4) p3.add_argument("--weight-decay", type=float, default=0.1) p3.add_argument("--dropout", type=float, default=0.05) p3.add_argument("--batch", type=int, default=256) p3.add_argument("--encode-batch", type=int, default=128) args = ap.parse_args(argv) print(f"[{args.stage}] args: {vars(args)}", flush=True) {"stage2": stage2, "stage3": stage3}[args.stage](args)
if __name__ == "__main__": sys.exit(main())15 unmodified lines1617181920212215 unmodified linesdef __init__(self, config: DictConfig):super().__init__()mc = config.ModelConfigvision = CLIPVisionModel.from_pretrained(mc.get("clip_name", "openai/clip-vit-large-patch14")).vision_modelself.backbone = apply_svd_residual_to_self_attn(vision, r=int(mc.get("svd_rank", 1023)))self.head = nn.Linear(1024, 2)# Training recipe only (conf/model/image/effort_ufd.yaml): the official UniversalFakeDetect trainer re-draws the15 unmodified lines1617181920212223242515 unmodified linesdef __init__(self, config: DictConfig):super().__init__()mc = config.ModelConfigclip_vision = CLIPVisionModel.from_pretrained(mc.get("clip_name", "openai/clip-vit-large-patch14"))# transformers <= 5.5.4 wraps the tower as ``.vision_model``; 5.22.2 made CLIPVisionModel the tower itself (the# tensor names under it, and the pooled output, are the same either way).vision = getattr(clip_vision, "vision_model", clip_vision)self.backbone = apply_svd_residual_to_self_attn(vision, r=int(mc.get("svd_rank", 1023)))self.head = nn.Linear(1024, 2)# Training recipe only (conf/model/image/effort_ufd.yaml): the official UniversalFakeDetect trainer re-draws the
38 unmodified lines3940414243444546474838 unmodified lineslogger = logging.getLogger(__name__)_RESIDUAL_DIM = 256# LoRA targets for a Hugging Face DINOv2 ViT (attention q/k/v + output dense + MLP fc1/fc2)._DEFAULT_LORA_TARGETS = ["attention.attention.query", "attention.attention.key", "attention.attention.value","attention.output.dense", "mlp.fc1", "mlp.fc2",]_IMAGENET_MEAN = (0.485, 0.456, 0.406)_IMAGENET_STD = (0.229, 0.224, 0.225)38 unmodified lines3940414243444546474849505138 unmodified lineslogger = logging.getLogger(__name__)_RESIDUAL_DIM = 256# LoRA targets for a Hugging Face DINOv2 ViT (attention q/k/v + output dense + MLP fc1/fc2); attention modules are# named attention.attention.{query,key,value} / attention.output.dense up to transformers 5.5.x and# attention.{q,k,v,o}_proj in later releases (5.22), so both spellings are listed (each matches only on its own release)._DEFAULT_LORA_TARGETS = ["attention.attention.query", "attention.attention.key", "attention.attention.value","attention.output.dense", "attention.q_proj", "attention.k_proj", "attention.v_proj", "attention.o_proj","mlp.fc1", "mlp.fc2",]_IMAGENET_MEAN = (0.485, 0.456, 0.406)_IMAGENET_STD = (0.229, 0.224, 0.225)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283# PROBE (`probe`, `probe_resnet`)
**Where Detectors Fail: Probing Generative Space for Generalizable AI-Generated Image Detection** (ICML 2026) —[paper (arXiv 2605.24906)](https://arxiv.org/abs/2605.24906) ·[official code](https://github.com/Amamiya-C/PROBE-AIGI-Detection) ·[checkpoints](https://modelscope.cn/models/shuinishaojiu/PROBE-AIGI-Detection)
PROBE (Probing Robustness via Boundary Exploration) is a way to train a detector, not a new architecture. Detectorsfail on generators they have not seen because the training data covers only a small part of what generators canproduce. PROBE uses the detector as a critic: it steers an image generator through small edits of its internalrepresentations ("manifold-level modifications") towards realistic images that the detector misclassifies, and thenrefines the detector on those hard samples. The released detectors are therefore plain classifiers with one logit:
* **PROBE-DINOv2** (`probe`): DINOv2 ViT-L/14 with registers, fine-tuned, with a linear head on the CLS token; trained on the paper's *Reconstruction Training Set* (real images reconstructed with SD 2.1) plus PROBE samples. README: 93.9 average balanced accuracy over 7 benchmarks.* **PROBE-ResNet50** (`probe_resnet`): a ResNet-50 with a linear head, trained on GenImage SD v1.4 plus PROBE samples (78.1 average). Both are rows of the paper's Table 1, so both are registered.
## Pipeline (official, reproduced exactly)
```image ─ Image.open(path).convert('RGB') ─ pad_image to the crop size S, only if a side is shorter than S: probe: S = 336, mode 'repeat' (tile the image with copies of itself until both sides reach 336) probe_resnet: S = 224, mode 'pad' (paste it centered on a black 224×224 square; a longer side is cut) ─ ToTensor → ImageNet normalization (on the whole image) ─ non-overlapping S×S patches, row-major (unfold, stride S); the strip at the right / bottom that is narrower than S is not used → [N, 3, S, S], N depends on the size → each patch: DINOv2-reg ViT-L/14 → CLS → Linear(1024, 1) | ResNet-50 → avgpool → Linear(2048, 1) → mean of the N patch logits → P(fake) = sigmoid(mean) (official evaluate_dino.py / evaluate_resnet.py)```
The crop sizes are the official README commands (`evaluate_dino.py --crop_size 336`, `evaluate_resnet.py --crop_size224`); the pad modes are the scripts' `data_augment_params['pad_mode']`. Every test-time perturbation of the official`data_augment` (blur, JPEG, noise, resize, cutout) has probability 0 in the README commands, so it is the identity.
Weights: `DINOv2_best_model_step_34999.pth` (1.22 GB, sha256 `c8caa9ba…450156`) holds the full model (all 440 backbonetensors + the head) and loads key-for-key as `probe.pth`, so the backbone download (`facebook/dinov2-with-registers-large`) is not needed for inference; `ResNet50_best_model_step_19343.pth` (94 MB, sha256 `71ef257e…20f0507c`) loadskey-for-key as `probe_resnet.pth`. Both are `{"model_state_dict": ...}` (ModelScope`shuinishaojiu/PROBE-AIGI-Detection`). Place them under `$SYNTHSCOPE_CKPT_DIR` with those names.
## SynthScope adaptations
| choice | reason ||---|---|| `official/dino_classifier.py` and `official/resnet50.py` = the official model files | `SynthScopePROBEModel` subclasses the official `dino_classifier`, `SynthScopePROBEResNetModel` the official `ResNet` (as `resnet50(num_classes=1, classifier_type='linear')`), so the checkpoints load strictly (`ckpt_kind="official_probe"`); attribution and licence status in the headers. `resnet50.py` is unchanged. || DINOv2 backbone built from its config (`DINOV2_REG_LARGE`), not `AutoModel.from_pretrained(model_name)` | the checkpoint already holds the backbone weights; `backbone_path` still loads a pretrained HF-format backbone (for training). Both give the same `Dinov2WithRegistersModel` with the default (sdpa) attention. || transform steps `probe_pad_repeat_336` / `probe_pad_224` (the official `pad_image`, vendored unchanged in `preprocess.py`), `to_dtype`, `normalize_imagenet`, `sliding_patches_336` / `sliding_patches_224` (the official `generate_sliding_patches`) | the official per-image preprocessing as eval-list steps; the transform returns the image's patch bag `[N, 3, S, S]`. || the mean over patches is in `forward` (`[B, N, 3, S, S]` → `[B, 1]`); `native_res=True` scores one image at a time | the official `evaluate` averages the patch logits of each image; N varies with the image size, so bags cannot be stacked across images. || patches go through the network in chunks of `patch_chunk_size: 32` | bounds memory on very large images; the official code runs all patches of a batch of images in one forward. Chunking does not change the scores here (max \|diff\| 0.0 against the official batch-1 run, including a 40-patch image). `patch_chunk_size: 0` runs all patches at once. || `remap_probe` unwraps `model_state_dict` | the official `checkpoint['model_state_dict']` load (no key renaming). || an unreadable image is skipped by `bench_eval` (with a "bad image" print) | the official loader scores it as P(fake) = 0.5 (logit 0); no effect on readable data. || image files of every format PIL reads | the official loader lists `.jpg`, `.jpeg`, `.png` only; the pixels of those formats are the same. || `compute_loss` = BCE with logits on one patch per image, `outputs` = `[-logit, logit]` | the official fine-tuning and boundary-exploration code is not released (README TODO), so there is no training recipe; this is the repo convention for single-logit detectors. |
## Fidelity check
The official code (`probe_ref` at commit b145f71, unmodified, in a separate process: `evaluate_dino.EvaluateDataset`/ `evaluate_resnet.EvaluateDataset`, `collate_fn` and `evaluate`, with the README settings, `fake_equal_real=False` soevery file is scored, the backbone path pointed at a local copy of `facebook/dinov2-with-registers-large` @ e4c89a4,CPU) against SynthScope's full pipeline: raw file → `bench_eval._open_rgb` → registry transform → engine-built modelwith the checkpoint loaded by the engine (`_load_checkpoint`, strict) → `engine._fake_prob`, through `bench_eval.score`.
Images: 34 files (16 real, 18 fake; PNG and JPEG incl. one RGBA PNG and one grayscale JPEG; 128×128 to 3000×1999; sidesbelow, at and just under the crop size, e.g. 335×700 and 336×500): 1 to 40 patches per image for `probe` (179 inall), 1 to 104 for `probe_resnet` (389).
Results (CPU, torch 2.11, transformers 5.5.4; logs `repro/logs/probepar_cpu_{official_dino,official_resnet}_bs{1,8}.log`and `probepar_cpu_ours_{dino,resnet}.log`):
| | `probe` (DINOv2, 336) | `probe_resnet` (ResNet-50, 224) ||---|---|---|| state dict (strict engine load) | 442/442 tensors identical to the checkpoint and to the official model (sha256 of the bytes); missing 0, unexpected 0 | 320/320 identical; missing 0, unexpected 0 || model inputs (patch bags) | 34/34 identical to the official tensors (sha256) | 34/34 identical || P(fake), mean logit vs official batch 1 | **max \|diff\| 0.0 / 0.0**, 0 flips | **max \|diff\| 0.0 / 0.0**, 0 flips || P(fake), mean logit vs official batch 8 (README) | 2.6e-8 / 1.9e-6, 0 flips | 1.8e-7 / 5.7e-6, 0 flips |
The batch-8 differences are the official code's own batch-size effect (it runs the patches of 8 images in oneforward), not a SynthScope difference. A checkpoint with one tensor removed or one extra key makes the engine raise.The code tested is commit f01b3ee; `patch_chunk_size` 32 and 0 (all patches at once) give identical scores.
Memory and speed (CPU, fp32, 16 threads on a shared login node, the 34 parity images scored one at a time as theengine does, second pass timed; logs `repro/logs/probepar_cpu_speed_{probe,probe_resnet,probe_chunk0}.log`):
| | `probe` | `probe_resnet` ||---|---|---|| model time per patch | 507 ms (336×336) | 28 ms (224×224) || one-patch image (e.g. 500×375) | 0.90 s | 0.13 s || largest image (3000×1999) | 40 patches, 16.5 s | 104 patches, 2.0 s || mean per image (incl. preprocessing) | 2.68 s | 0.32 s || peak RSS (load + inference) | 2.98 GiB (3.19 GiB with `patch_chunk_size: 0`) | 1.24 GiB |
The cost grows with the image area: an image is scored on all its patches.
## Results
**Verdict: faithful port (SynthScope equals the official code on every file compared: the 34 parity images, WildRF andSynthWildX); the released checkpoints reproduce thepaper's Table 1 on four of the five benchmarks we can run (GenImage, SynthWildX, WildRF, AIGI-Bench) to within 0.9points per benchmark; Synthbuster uses different reals and is not a like-for-like comparison. Chameleon andAIGI-Quality-Paradox were not run (no loader), so the paper's 7-benchmark averages (93.9 / 78.1) are not comparablewith the means below.**
Paper = Table 1 of arXiv 2605.24906 (balanced accuracy, %, threshold 0.5, positive = fake; per-benchmark Avg = unweightedmean of the per-subset bAcc of its Tables 2-4). SynthScope_official = the released checkpoint run through SynthScope(`benchmark/bench_eval.py --model probe` / `--model probe_resnet`); its `means.acc` is the same quantity (the mean oversubsets of (real accuracy + fake accuracy) / 2). SynthScope_train = "—": the training code (generator probing andfine-tuning) is not released, so there is no SynthScope-trained model.
| Benchmark | Paper PROBE-DINOv2 | SynthScope_official `probe` | Paper PROBE-ResNet50 | SynthScope_official `probe_resnet` | SynthScope_train ||---|---:|---:|---:|---:|:-:|| GenImage (val100k, fakes JPEG q96) | 96.8 | **97.47** (+0.67) | 78.4 | **78.38** (-0.02) | — || Synthbuster (**different reals**: 5000 MSCOCO, not RAISE-1k) | 97.5 | 98.20 (not like-for-like) | 79.1 | 83.75 (not like-for-like) | — || SynthWildX | 96.4 | **97.30** (+0.90) | 75.6 | **75.20** (-0.40) | — || WildRF | 96.9 | **96.92** (+0.02) | 81.3 | **81.63** (+0.33) | — || AIGI-Bench (CommunityAI + SocialRF) | 89.9 | **89.88** (-0.02) | 70.4 | **70.44** (+0.04) | — || Chameleon | 86.6 | — (no loader; by request only) | 74.0 | — (no loader) | — || AIGI-Quality-Paradox | 92.9 | — (no loader) | 87.7 | — (no loader) | — || Mean of the 5 benchmarks we ran | 95.50 | 95.95 | 76.96 | 77.88 | — || Mean of the 4 like-for-like benchmarks (no Synthbuster) | 95.00 | 95.39 | 76.43 | 76.41 | — || Paper's Avg. over all 7 | 93.9 | not comparable | 78.1 | not comparable | — |
The SynthScope columns are `means.acc` of `repro/bench_results/probe_<benchmark>.json` and`probe_resnet_<benchmark>.json` (tags below). Their mean AP / AUROC (the paper does not report them in Table 1): GenImage99.77 / 99.80 (DINOv2), 86.69 / 84.81 (ResNet-50); Synthbuster 99.64 / 99.93, 85.23 / 95.88; SynthWildX 98.80 / 99.18,83.88 / 82.80; WildRF 99.36 / 99.26, 89.45 / 85.76; AIGI-Bench 96.46 / 95.88, 79.80 / 77.55.
### Protocol
* **Metric**: balanced accuracy at threshold 0.5 (mean of real and fake accuracy), positive class = fake; the per-benchmark value is the unweighted mean over the paper's subsets. The paper checks out against itself: the mean of its eight GenImage DINOv2 values is 96.76 (Table 1: 96.8), of its nine Synthbuster values 97.52 (97.5), of its WildRF values 96.93 (96.9).* **Inference**: the SynthScope registry transform of Task 1 (exact parity with the official code), batch size 1 (native resolution), fp32, one RTX A6000 per job.* **GenImage**: the official val split, 100,000 images, 8 generators, **all fakes JPEG-compressed at quality 96, reals untouched** (`--jpeg-fakes 96`, the same PIL round trip as the official `util.jpeg_compress`), as the paper does to remove GenImage's compression bias. These numbers are for that compressed protocol; they are not comparable with GenImage numbers measured on the uncompressed split. The folders hold 6000 real + 6000 fake images per generator except SD v1.5 with 8000 + 8000 (the paper's Table 12 lists 48k / 48k).* **Synthbuster**: 9 generators, 1000 fakes each, paired with **5000 MSCOCO val2017 reals** (the `EvalGEN/Flux/0_real` folder, the same reals as the MIRROR and B-Free Synthbuster runs). The paper pairs them with the **1000 RAISE-1k reals** (its Table 12); RAISE is distributed through a personal registration form that was not filled in, so it is not in SynthScope. These rows are therefore a *different-reals* comparison and are not presented as reproducing the paper.* **SynthWildX**: dalle3 / firefly / midjourney_v5, 413 reals and 392 / 473 / 435 fakes (1713 unique images: 413 reals scored against each of the 3 fake subsets; the paper's Table 12 lists 0.5k reals and 1.5k fakes: our copy is the part still online).* **WildRF**: facebook / reddit / twitter, 2503 files (160 + 160, 750 + 750, 341 + 342); the paper lists 1.25k + 1.25k.* **AIGI-Bench**: only the two subsets the paper evaluates, **CommunityAI** (6000 real + 6000 fake) and **SocialRF** (3000 real + 3000 fake), 18,000 files (the paper's 9k / 9k), staged as `aigibench/{CommunityAI,SocialRF}/{0_real,1_fake}`; the other subsets of the AIGIBench release (about 330 GB) were not scored.* **Not run**: Chameleon (available by request only) and AIGI-Quality-Paradox have no loader in SynthScope.* No JPEG alignment on any benchmark other than GenImage (the paper applies it to GenImage only).
### Per-subset results
balanced accuracy, % (real accuracy / fake accuracy in brackets); `Paper` = Tables 2-4, `Avg` row = Table 1 for thepaper and `means.acc` for SynthScope.
**GenImage (val100k, fakes JPEG q96)**
| subset | Paper DINOv2 | SynthScope_official `probe` (real / fake acc) | Paper ResNet-50 | SynthScope_official `probe_resnet` (real / fake acc) ||---|---:|---:|---:|---:|| midjourney | 98.8 | 98.73 (98.57 / 98.9) | 90.7 | 90.73 (98.67 / 82.8) || sdv1.4 | 99.4 | 99.41 (98.85 / 99.97) | 99.4 | 99.36 (98.72 / 100.0) || sdv1.5 | 99.4 | 99.39 (98.9 / 99.87) | 99.2 | 99.24 (98.6 / 99.89) || adm | 91.0 | 93.22 (98.55 / 87.88) | 60.0 | 58.94 (98.52 / 19.37) || glide | 92.1 | 93.86 (99.07 / 88.65) | 63.0 | 63.01 (98.78 / 27.23) || wukong | 99.5 | 99.33 (98.68 / 99.97) | 99.4 | 99.41 (98.87 / 99.95) || vqdm | 98.9 | 98.76 (98.62 / 98.9) | 66.9 | 66.90 (98.72 / 35.08) || biggan | 95.0 | 97.07 (98.75 / 95.38) | 49.4 | 49.41 (98.82 / 0.0) || **Avg** | **96.8** | **97.47** | **78.4** | **78.38** |
**Synthbuster (5000 MSCOCO reals, not the paper's RAISE-1k)**
| subset | Paper DINOv2 | SynthScope_official `probe` (real / fake acc) | Paper ResNet-50 | SynthScope_official `probe_resnet` (real / fake acc) ||---|---:|---:|---:|---:|| dalle2 | 94.6 | 93.47 (99.54 / 87.4) | 48.3 | 52.97 (99.14 / 6.8) || dalle3 | 99.4 | 99.57 (99.54 / 99.6) | 90.2 | 94.82 (99.14 / 90.5) || firefly | 99.5 | 99.77 (99.54 / 100.0) | 46.9 | 51.57 (99.14 / 4.0) || glide | 86.7 | 92.22 (99.54 / 84.9) | 57.4 | 62.07 (99.14 / 25.0) || midjourney-v5 | 99.5 | 99.77 (99.54 / 100.0) | 93.2 | 97.82 (99.14 / 96.5) || stable-diffusion-1-3 | 99.5 | 99.72 (99.54 / 99.9) | 94.9 | 99.57 (99.14 / 100.0) || stable-diffusion-1-4 | 99.5 | 99.77 (99.54 / 100.0) | 94.9 | 99.57 (99.14 / 100.0) || stable-diffusion-2 | 99.5 | 99.77 (99.54 / 100.0) | 93.1 | 97.72 (99.14 / 96.3) || stable-diffusion-xl | 99.5 | 99.72 (99.54 / 99.9) | 93.0 | 97.67 (99.14 / 96.2) || **Avg** | **97.5** | **98.20** | **79.1** | **83.75** |
**SynthWildX**
| subset | Paper DINOv2 | SynthScope_official `probe` (real / fake acc) | Paper ResNet-50 | SynthScope_official `probe_resnet` (real / fake acc) ||---|---:|---:|---:|---:|| dalle3 | 96.5 | 97.44 (95.64 / 99.23) | 90.3 | 89.71 (89.1 / 90.31) || firefly | 96.4 | 96.98 (95.64 / 98.31) | 56.7 | 56.29 (89.1 / 23.47) || midjourney_v5 | 96.5 | 97.48 (95.64 / 99.31) | 79.7 | 79.61 (89.1 / 70.11) || **Avg** | **96.4** | **97.30** | **75.6** | **75.20** |
**WildRF**
| subset | Paper DINOv2 | SynthScope_official `probe` (real / fake acc) | Paper ResNet-50 | SynthScope_official `probe_resnet` (real / fake acc) ||---|---:|---:|---:|---:|| facebook | 98.4 | 98.75 (98.12 / 99.37) | 87.8 | 87.81 (82.5 / 93.12) || reddit | 93.4 | 93.33 (94.4 / 92.27) | 72.9 | 72.87 (89.6 / 56.13) || twitter | 99.0 | 98.68 (99.12 / 98.25) | 83.3 | 84.20 (89.74 / 78.65) || **Avg** | **96.9** | **96.92** | **81.3** | **81.63** |
**AIGI-Bench (CommunityAI + SocialRF)**
| subset | Paper DINOv2 | SynthScope_official `probe` (real / fake acc) | Paper ResNet-50 | SynthScope_official `probe_resnet` (real / fake acc) ||---|---:|---:|---:|---:|| CommunityAI | 89.8 | 90.38 (97.17 / 83.6) | 71.0 | 70.99 (87.1 / 54.88) || SocialRF | 89.9 | 89.38 (89.87 / 88.9) | 69.9 | 69.88 (84.2 / 55.57) || **Avg** | **89.9** | **89.88** | **70.4** | **70.44** |
Reading the tables:
* **ResNet-50 reproduces the paper** on GenImage (7 of 8 generators within 0.1, ADM 58.94 vs 60.0; average 78.38 vs 78.4), SynthWildX, WildRF and AIGI-Bench (every subset within 0.9, the largest being WildRF twitter 84.2 vs 83.3). Its weakness is real: it detects almost nothing from ADM, GLIDE, VQDM and BigGAN (fake accuracy 0 - 35 %) because it is trained on SD v1.4 only.* **DINOv2**: Stable Diffusion, Wukong, VQDM and Midjourney are within 0.2 of the paper. **ADM, GLIDE and BigGAN are about 2 points above it** (+2.2, +1.8, +2.1), which makes the GenImage average 97.47 vs 96.8. SynthScope equals the official code wherever we compared the two (the 34 parity images of the fidelity check, and every WildRF and SynthWildX file, next section), and the official code was not run on GenImage itself. Since the pipeline is identical, the difference points to the data or preprocessing on the paper's side (the exact JPEG-q96 implementation and the exact val subset are not specified); we cannot determine it.* **Synthbuster**: the real-class accuracy is fixed by the reals, so swapping RAISE for MSCOCO moves every subset by the same real-accuracy term. Inferred, not measured: for ResNet-50 the paper's bAcc of SD 1.3 / 1.4 (94.9), DALL-E 2 (48.3) and DALL-E 3 (90.2) is reproduced from our fake accuracies (100.0, 6.8, 90.5) if the RAISE real accuracy is about 89.8 (ours on MSCOCO: 99.14); for DINOv2 the same reading gives about 99.0 (ours 99.54), and the per-subset differences are small except GLIDE (+5.5) and DALL-E 2 (-1.1). This is why 98.20 and 83.75 must not be quoted as "reproducing 97.5 and 79.1".
### Official code on our data
To separate port from data, the **unmodified official** `evaluate_dino.py` / `evaluate_resnet.py` code path(`EvaluateDataset`, `collate_fn`, `evaluate`, README settings, batch size 4; `repro/probe_task2/probe_official_eval.py`)was run on the same files as SynthScope for WildRF and SynthWildX (job 66753). Per file: **0 flips at 0.5 on everycommon file in all four runs; max |dP| = 4.8e-6 (DINOv2) and 1.3e-3 (ResNet-50, GPU convolution algorithms / TF32 atbatch 4 vs 1)**.
| run | SynthScope `means.acc` | official, bAcc on all files it reads | official "Overall Accuracy" (seed-42 class-balanced subsample) | Paper ||---|---:|---:|---:|---:|| `probe` WildRF | 96.92 | 96.88 | 96.78 | 96.9 || `probe` SynthWildX | 97.30 | 97.30 | 97.42 | 96.4 || `probe_resnet` WildRF | 81.63 | 81.65 | 80.99 | 81.3 || `probe_resnet` SynthWildX | 75.20 | 75.20 | 75.09 | 75.6 |
* The official script's default `fake_equal_real=True` subsamples the larger class to the smaller one (seed 42) and reports pooled accuracy on that sample; it equals bAcc up to sampling noise (at most 2.0 per subset, ResNet-50 on the unbalanced WildRF twitter subset: 82.29 vs 84.27; at most 0.66 per benchmark, ResNet-50 WildRF: 80.99 vs 81.65). `means.acc` is the paper's metric.* **The official file lister keeps `.jpg` / `.jpeg` / `.png` only**, so it silently drops the 262 `.jfif` files of WildRF twitter (683 files in SynthScope, 421 in the official run). SynthScope scores all of them. On the 421 common files both give the same number (DINOv2 98.57, ResNet-50 84.27); on all 683 SynthScope gives 98.68 / 84.20. Every other subset is identical to two decimals.* An unreadable image is scored P(fake) = 0.5 by the official code and skipped by `bench_eval`; no file in these benchmarks was unreadable.
Raw comparison: `repro/probe_task2/official_vs_synthscope.json`, `official_runs_summary.json`,`paper_vs_synthscope.json`; scripts `repro/probe_task2/`.
### Tags and jobs
DAS6, one RTX A6000 per job, code at commit a6ba2c5 (clean checkout in every job; the checkpoints were verified against`SHA256SUMS` in every job). Logs: `repro/logs/probebench_das6_<job>.out`; every `repro/bench_results/probe_*.json` matchesits `=== RESULT <tag>` log line and its `repro/MASTER_RESULTS.jsonl` line.
| tags (`probe_<x>`, `probe_resnet_<x>`) | benchmark | job ||---|---|---|| `genimage_val100k` | GenImage val100k, fakes JPEG q96 | 66753 (node409) || `synthbuster_coco` | Synthbuster vs 5000 MSCOCO reals | 66755 (node412) || `synthwildx`, `wildrf` | SynthWildX, WildRF (+ the official-code runs above) | 66753 || `aigibench` | CommunityAI + SocialRF | 66790 (node409) |
(Jobs 66754, 66757 and the IVI job 284282 were cancelled and produced no result used here.)
## Licence
The official repository has no LICENSE file and states no licence, and the ModelScope model page has an empty licencefield: the licence is **unclear**. The weights are not redistributed (not in the SynthScope model zoo or on theSpace); download them from ModelScope. See [LICENSES.md](../../../LICENSES.md).1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677# Vendored from github.com/Amamiya-C/PROBE-AIGI-Detection (commit b145f71), file Detector/model/dino_classifier.py.# Licence UNCLEAR: the repository has no LICENSE file and states no licence; see LICENSES.md.## The `dino_classifier` below is the official class, so the released DINOv2_best_model_step_34999.pth loads key-for-key# with strict=True. One forced change, which does not alter the computation:# 1. The backbone can be built from its config (`DINOV2_REG_LARGE`, the config.json of# facebook/dinov2-with-registers-large) instead of `AutoModel.from_pretrained(model_name)`: the checkpoint holds# the full backbone, so inference needs no backbone download. A directory path or hub id (the official# `model_name`) still uses from_pretrained. Both build the same Dinov2WithRegistersModel with the transformers# default attention (sdpa).from collections.abc import Mapping
import torchfrom transformers import AutoModel, Dinov2WithRegistersConfig, Dinov2WithRegistersModel
# config.json of facebook/dinov2-with-registers-large (revision e4c89a4e05589de9b3e188688a303d0f3c04d0f3), the backbone# of the official `model_name` ('.../dinov2-l-register'; the commented-out default is the hub id).DINOV2_REG_LARGE = dict( apply_layernorm=True, attention_probs_dropout_prob=0.0, drop_path_rate=0.0, hidden_act="gelu", hidden_dropout_prob=0.0, hidden_size=1024, image_size=518, initializer_range=0.02, interpolate_antialias=True, interpolate_offset=0.0, layer_norm_eps=1e-06, layerscale_value=1.0, mlp_ratio=4, num_attention_heads=16, num_channels=3, num_hidden_layers=24, num_register_tokens=4, patch_size=14, qkv_bias=True, use_swiglu_ffn=False,)
def _load_backbone(source): """`AutoModel.from_pretrained(source)` for a directory / hub id; a config dict builds the same model untrained.""" if isinstance(source, Mapping): return Dinov2WithRegistersModel(Dinov2WithRegistersConfig(**source)) return AutoModel.from_pretrained(source)
# --- official Detector/model/dino_classifier.py (unchanged except for the marked line) --------------------------------class dino_classifier(torch.nn.Module): def __init__(self, # model_name="facebook/dinov2-with-registers-large", model_name='/data_center/data2/dataset/czj/detector/model/dinov2-l-register', classifier_type='linear', mlp_hidden_size=512 ): super(dino_classifier, self).__init__() self.backbone = _load_backbone(model_name) # changed (1) if classifier_type == 'linear': self.fc = torch.nn.Linear(self.backbone.config.hidden_size, 1) elif classifier_type == 'mlp': self.fc = torch.nn.Sequential( torch.nn.Linear(self.backbone.config.hidden_size, mlp_hidden_size), torch.nn.ReLU(inplace=False), torch.nn.Dropout(0.5), torch.nn.Linear(mlp_hidden_size, 1) ) else: raise ValueError(f"Unknown classifier_type: {classifier_type}")
# Freeze backbone # for param in self.vision_model.parameters(): # param.requires_grad = False
def extract_feature(self, input): outputs = self.backbone(input) sequence_output = outputs[0] # batch_size, sequence_length, hidden_size cls_token = sequence_output[:, 0] return cls_token
def forward(self, input, return_feature=False): outputs = self.backbone(input) sequence_output = outputs[0] # batch_size, sequence_length, hidden_size cls_token = sequence_output[:, 0] feature = cls_token # patch_tokens = sequence_output[:, 1:] # linear_input = torch.cat([cls_token, patch_tokens.mean(dim=1)], dim=1) logits = self.fc(cls_token) if return_feature: return logits, feature else: return logits
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256# Vendored from github.com/Amamiya-C/PROBE-AIGI-Detection (commit b145f71), file Detector/model/resnet50.py. Licence# UNCLEAR: the repository has no LICENSE file and states no licence; see LICENSES.md.# Unchanged below this header, so the released ResNet50_best_model_step_19343.pth loads key-for-key with strict=True.import torch.nn as nnimport torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101','resnet152']
model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',}
def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class BasicBlock(nn.Module): expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=False) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.downsample = downsample self.stride = stride
def forward(self, x): identity = x
out = self.conv1(x) out = self.bn1(out) out = self.relu(out)
out = self.conv2(out) out = self.bn2(out)
if self.downsample is not None: identity = self.downsample(x)
out += identity out = self.relu(out)
return out
class Bottleneck(nn.Module): expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = conv1x1(inplanes, planes) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = conv3x3(planes, planes, stride) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = conv1x1(planes, planes * self.expansion) self.bn3 = nn.BatchNorm2d(planes * self.expansion) self.relu = nn.ReLU(inplace=False) self.downsample = downsample self.stride = stride
def forward(self, x): identity = x
out = self.conv1(x) out = self.bn1(out) out = self.relu(out)
out = self.conv2(out) out = self.bn2(out) out = self.relu(out)
out = self.conv3(out) out = self.bn3(out)
if self.downsample is not None: identity = self.downsample(x)
out += identity out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, classifier_type='linear', mlp_hidden_size=512): super(ResNet, self).__init__() self.inplanes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) # self.relu = nn.ReLU(inplace=True) self.relu = nn.ReLU(inplace=False) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) # self.fc = nn.Linear(512 * block.expansion, num_classes) if classifier_type == 'linear': self.fc = nn.Linear(512 * block.expansion, num_classes) elif classifier_type == 'mlp': self.fc = nn.Sequential( nn.Linear(512 * block.expansion, mlp_hidden_size), nn.ReLU(inplace=False), nn.Dropout(0.5), nn.Linear(mlp_hidden_size, num_classes) ) else: raise ValueError(f"Unknown classifier_type: {classifier_type}") # print(num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0)
# Zero-initialize the last BN in each residual branch, # so that the residual branch starts with zeros, and each residual block behaves like an identity. # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 if zero_init_residual: for m in self.modules(): if isinstance(m, Bottleneck): nn.init.constant_(m.bn3.weight, 0) elif isinstance(m, BasicBlock): nn.init.constant_(m.bn2.weight, 0)
def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( conv1x1(self.inplanes, planes * block.expansion, stride), nn.BatchNorm2d(planes * block.expansion), )
layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for _ in range(1, blocks): layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers) def extract_feature(self, x): # print("1"+str(x.size())) x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x)
x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x)
x = self.avgpool(x) x = x.view(x.size(0), -1) # print("2"+str(x.size())) return x
def forward(self, x, return_feature=False): # print("1"+str(x.size())) x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x)
x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x)
x = self.avgpool(x) feature = x.view(x.size(0), -1) # print("2"+str(x.size())) x = self.fc(feature) # print("3"+str(x.size())) if return_feature is True: return x, feature else: return x
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model
def resnet34(pretrained=False, **kwargs): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) return model
def resnet50(pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model
def resnet101(pretrained=False, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) return model
def resnet152(pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) return model1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""PROBE's test-time preprocessing; ``pad_image`` is vendored unchanged and ``sliding_patches`` is the``EvaluateDataset.generate_sliding_patches`` of github.com/Amamiya-C/PROBE-AIGI-Detection (commit b145f71,``Detector/util.py`` and ``Detector/evaluate_dino.py`` / ``evaluate_resnet.py``; licence unclear: no LICENSE file -see LICENSES.md).
The official evaluation (``EvaluateDataset.__getitem__`` + ``evaluate``), per image: 1. ``Image.open(path).convert('RGB')``, 2. ``data_augment(image, params, mode='fix', crop_size)``: every perturbation probability is 0 at test time (the README commands set none), so this is ``Image.fromarray(np.array(image))`` (an identity) followed by ``pad_image(image, size=crop_size, mode=pad_mode)``: an image with a side under ``crop_size`` is tiled with copies of itself (``'repeat'``, the DINOv2 script) or pasted on a black ``crop_size`` square (``'pad'``, the ResNet-50 script; a side longer than ``crop_size`` is then cut, offset ``(crop_size - side) // 2``), 3. ``ToTensor`` + ImageNet ``Normalize`` on the whole image, 4. non-overlapping ``crop_size`` patches (``unfold`` with stride = size; pixels past the last full patch on the right / bottom are dropped) -> ``[N, 3, crop_size, crop_size]``, 5. the model scores every patch; the image's logit is the mean of its patch logits, P(fake) = sigmoid(mean).
Steps 2 and 4 are the transform steps ``probe_pad_repeat_336`` / ``probe_pad_224`` and ``sliding_patches_336`` /``sliding_patches_224`` (``transformations.py``); 3 is ``to_dtype`` + ``normalize_imagenet``; 5 is in the model's``forward``. The patch count depends on the image size, so images are scored one at a time (``native_res``)."""from __future__ import annotations
import torchfrom PIL import Image
# --- official Detector/util.py, unchanged ----------------------------------------------------------------------------def pad_image(img, size=224, mode='pad'): width, height = img.size
if width>=size and height>=size: return img
if mode == 'repeat': repeat_times_width = max(1, (size + width - 1) // width) repeat_times_height = max(1, (size + height - 1) // height) new_width = width * repeat_times_width new_height = height * repeat_times_height new_img = Image.new('RGB', (new_width, new_height))
for i in range(repeat_times_height): for j in range(repeat_times_width): new_img.paste(img, (j * width, i * height)) return new_img if mode == 'pad': new_img = Image.new('RGB', (size, size), (0,0,0)) paste_x = (size - width) // 2 paste_y = (size - height) // 2 new_img.paste(img, (paste_x, paste_y)) return new_img# ----------------------------------------------------------------------------------------------------------------------
def sliding_patches(img_tensor: torch.Tensor, ps: int) -> torch.Tensor: """The official ``generate_sliding_patches`` after its ``self.transform``: [3, H, W] -> [N, 3, ps, ps], row-major non-overlapping patches (an image smaller than ``ps`` gives N = 0, as the official code; ``pad_image`` runs first, so that does not happen in the pipeline).""" C, H, W = img_tensor.shape stride = ps
if H < ps or W < ps: return torch.zeros(0, 3, ps, ps)
# unfold on tensor (much faster than PIL crop) patches = img_tensor.unfold(1, ps, stride).unfold(2, ps, stride) patches = patches.permute(1, 2, 0, 3, 4).contiguous() patches = patches.view(-1, C, ps, ps)
return patches
class ProbePad: """``probe_pad_repeat_<n>`` / ``probe_pad_<n>``: the official ``pad_image`` on an RGB PIL image (PIL out)."""
def __init__(self, size: int, mode: str): if mode not in ("repeat", "pad"): raise ValueError(f"pad mode must be 'repeat' or 'pad', not {mode!r}") self.size, self.mode = size, mode
def __call__(self, image: Image.Image) -> Image.Image: return pad_image(image.convert("RGB"), size=self.size, mode=self.mode)
def __repr__(self) -> str: return f"ProbePad({self.size}, {self.mode!r})"
class SlidingPatches: """``sliding_patches_<n>``: a normalized [3, H, W] tensor -> its non-overlapping [N, 3, n, n] patches."""
def __init__(self, size: int): self.size = size
def __call__(self, image: torch.Tensor) -> torch.Tensor: return sliding_patches(torch.as_tensor(image), self.size)
def __repr__(self) -> str: return f"SlidingPatches({self.size})"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""PROBE (Where Detectors Fail: Probing Generative Space for Generalizable AI-Generated Image Detection, ICML 2026,arXiv 2605.24906).
Official repo: github.com/Amamiya-C/PROBE-AIGI-Detection (licence unclear: no LICENSE file). PROBE is a trainingmethod: the detector steers a generator through manifold-level edits to find realistic samples it misclassifies, andis then refined on them. The released detectors are plain classifiers with one logit:
PROBE-DINOv2 = DINOv2 ViT-L/14 with registers (facebook/dinov2-with-registers-large) -> CLS -> Linear(1024, 1) PROBE-ResNet50 = ResNet-50 -> global average pool -> Linear(2048, 1)
and the official evaluation scores an image as the mean logit of its non-overlapping crop_size patches at nativeresolution (336 for DINOv2, 224 for ResNet-50; ``preprocess.py``), P(fake) = sigmoid(mean logit).
``SynthScopePROBEModel`` *is* the official ``dino_classifier`` and ``SynthScopePROBEResNetModel`` the official``resnet50(num_classes=1, classifier_type='linear')`` (vendored in ``official/``); the released``DINOv2_best_model_step_34999.pth`` / ``ResNet50_best_model_step_19343.pth`` ({"model_state_dict": ...}) loadkey-for-key as ``probe.pth`` / ``probe_resnet.pth``. The DINOv2 backbone is built from its config, so inference needsno backbone download.
Input contract: ``forward`` takes the patch bag of one image per sample, [B, N, 3, S, S] from the eval transform(``probe_pad_*``, ``to_dtype``, ``normalize_imagenet``, ``sliding_patches_*``), and returns the mean patch logit [B, 1],as the official ``evaluate``; a [B, 3, S, S] batch is one patch per sample. Patches go through the network in chunksof ``patch_chunk_size`` (0 = all at once, as the official code does per batch) to bound memory on large images.
Training: the official fine-tuning and boundary-exploration code is not released (README TODO), so no recipe isreproduced; ``compute_loss`` is BCE with logits on one patch per image, outputs [-logit, logit] (the repo conventionfor single-logit detectors)."""import torchimport torch.nn.functional as Ffrom omegaconf import DictConfig
from .official.dino_classifier import DINOV2_REG_LARGE, dino_classifierfrom .official.resnet50 import Bottleneck, ResNet
def mean_patch_logits(net_forward, images: torch.Tensor, chunk: int) -> torch.Tensor: """[B, N, 3, S, S] (or [B, 3, S, S] = one patch each) -> the mean logit over each sample's patches, [B, 1].""" if images.dim() == 4: images = images.unsqueeze(1) b, n = images.shape[:2] patches = images.flatten(0, 1) step = chunk if chunk > 0 else len(patches) logits = torch.cat([net_forward(patches[i:i + step]) for i in range(0, len(patches), step)]) # [B*N, 1] return logits.view(b, n, -1).mean(dim=1)
def bce_loss(model, batch): images, labels = batch[0], batch[1] logits = model.forward(images)[:, 0] loss = F.binary_cross_entropy_with_logits(logits, labels.to(logits.dtype)) # Two-column [-logit, logit] so the trainer's metrics (argmax / softmax[:, 1]) read the single logit right. return {"loss": loss, "outputs": torch.stack([-logits, logits], dim=1)}
class SynthScopePROBEModel(dino_classifier): """PROBE-DINOv2: the official ``dino_classifier``, configured from SynthScope's ModelConfig."""
def __init__(self, config: DictConfig): mc = config.ModelConfig # backbone_path null: build DINOv2-reg ViT-L/14 from its config (the weights come from probe.pth); a HF-format # directory or hub id loads pretrained weights, as the official model_name. backbone_path = mc.get("backbone_path") # backbone_config: overrides of the ViT-L config fields (e.g. a tiny backbone for the smoke test). backbone_config = dict(DINOV2_REG_LARGE, **dict(mc.get("backbone_config") or {})) super().__init__(model_name=str(backbone_path) if backbone_path else backbone_config, classifier_type=mc.get("classifier_type", "linear")) self.patch_chunk_size = int(mc.get("patch_chunk_size", 0) or 0)
def forward(self, images): """[B, N, 3, S, S] normalized patches (or [B, 3, S, S]) -> mean patch logit [B, 1].""" return mean_patch_logits(super().forward, images, self.patch_chunk_size)
def compute_loss(self, batch): return bce_loss(self, batch)
class SynthScopePROBEResNetModel(ResNet): """PROBE-ResNet50: the official ``resnet50(num_classes=1, classifier_type='linear')``."""
def __init__(self, config: DictConfig): mc = config.ModelConfig super().__init__(Bottleneck, [3, 4, 6, 3], num_classes=1, classifier_type=mc.get("classifier_type", "linear")) self.patch_chunk_size = int(mc.get("patch_chunk_size", 0) or 0)
def forward(self, images): """[B, N, 3, S, S] normalized patches (or [B, 3, S, S]) -> mean patch logit [B, 1].""" return mean_patch_logits(super().forward, images, self.patch_chunk_size)
def compute_loss(self, batch): return bce_loss(self, batch)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266# WaveRep (`waverep`, `waverep_g4`)
**Seeing What Matters: Generalizable AI-generated Video Detection with Forensic-Oriented Augmentation** (Corvi,Cozzolino, Prashnani, De Mello, Nagano, Verdoliva; NeurIPS 2025) —[paper (arXiv 2506.16802)](https://arxiv.org/abs/2506.16802) ·[official code](https://github.com/grip-unina/WaveRep-SyntheticVideoDetection) ·[project page](https://grip-unina.github.io/WaveRep-SyntheticVideoDetection/)
A video detector built from an image backbone. A DINOv2 ViT-B/14 with registers is fine-tuned end to end on singlevideo frames. The method's contribution is the training data and an augmentation, not the architecture: in a waveletdecomposition, a fake frame's low-pass and horizontal / vertical bands are replaced by those of a real frame, which steersthe detector towards the diagonal mid-high frequencies that generators leave behind and that survive compression. Thepaper trains on ONE generator (Pyramid Flow) and tests on 15 unseen ones.
Two released checkpoints, both registered:
| key | checkpoint | trained on ||---|---|---|| `waverep` | `weights_dinov2_G1.ckpt` (`waverep.pth`) | "a single generator" (official demo README); we infer Pyramid Flow, the paper's detector in Tables 1-2 || `waverep_g4` | `weights_dinov2_G4.ckpt` (`waverep_g4.pth`) | "four generators" (official demo README; the demo's default); we infer Pyramid Flow, CogVideoX 1.5, Allegro and Open-Sora Plan, the Table 5 set |
## Pipeline (official, reproduced exactly)
```video ─ OpenCV VideoCapture, every frame in order, BGR -> RGB (official demo/utils.py ReadVideoIteratorCV) → the first 64 frames (paper, App. D; the demo's --limit 64) → per frame: CenterCrop(504) on the PIL frame (no resize; a smaller frame is zero-padded), ToTensor, ImageNet norm → DINOv2 ViT-B/14 + 4 registers (timm vit_base_patch14_reg4_dinov2, img_size 504) → one logit per frame → video logit = mean of the frame logits; P(fake) = sigmoid(logit) (logit > 0: synthetic)```
Weights: `weights_dinov2_G{1,4}.ckpt` from grip.unina.it (md5 `bc9852a7…` / `8bf19e6f…`, as listed in the demoREADME; sha256 `1c7566b2…a897` / `50d63904…5d53`). Each is a flat timm state dict of the full model, loaded strictly.
## SynthScope adaptations
| choice | reason ||---|---|| `SynthScopeWaveRepModel` holds the timm model as `self.model`; `registry.remap_waverep` prefixes the checkpoint keys with `model.` | The official `create_model` builds exactly this timm model and loads the checkpoint into it strictly. The remap also accepts the Lightning `{"state_dict": {"model.*"}}` form the official loader handles. || `pretrained_backbone: false` | The official code first downloads the timm DINOv2 weights, then overwrites every one of them with the checkpoint; building the model empty gives the same tensors without the download. || `official_utils.py` = the official `demo/utils.py`, verbatim | Reference for the tests and the parity check (GRIP license: nonprofit use; notices kept). SynthScope's reader `media.cv2_frames` is the same loop as `ReadVideoIteratorCV`, written out so that the package does not import pandas. || video sampler `cv2_frames`, `num_frames=64` | The paper scores the first 64 frames (App. D, Fig. 9). The demo scores every frame unless `--limit` is given; `dataclasses.replace(spec, num_frames=0)` reproduces that default. || frames scored `frame_batch` (16) at a time; the mean is taken in float64 | The demo scores one frame at a time and averages the float32 logits with pandas (float64). Batching changes the CPU logits by at most ~1e-5 (measured below) and bounds memory on long videos (`Engine.video_frame_logits` streams). || new transform step `center_crop_504` | torchvision `CenterCrop(504)` on the PIL frame: bit-exact with the official `CenterCrop((504, 504))`, zero padding included. || `compute_loss` = BCE with logits on single frames | The training code is not released (only the augmentation); no training recipe is reproduced. |
## Fidelity check (identical to the official model)
The unmodified official demo (`demo/main_avideo.py` @ `0fd6010`, CPU) against SynthScope's full pipeline (raw file ->`media.cv2_frames` -> registry transform -> engine-built model, strict load -> `Engine.video_frame_logits` /`predict_video_clip`), both checkpoints, same environment (torch 2.11, timm 1.0.27, OpenCV 4.13), on 15 videos:GenVideo-Val (MSR-VTT reals 298×224, Sora 1280×720 × 600 frames, WildScrape `.mov` 2160×544 and `.gif`), EvalCrafter(Hot Shot 672×384 × 8, MoonValley 1184×672 at 50 fps), VideoPhy (Dream Machine 1360×752 × 121), VidProM (ModelScope256×256 MPEG-4 part 2, Text2Video-Zero 512×512), the demo's own two videos, and three re-encodes (VP9 `.webm`, MJPEG`.avi`, HEVC `.mkv`); codecs H.264, MPEG-4 part 2, GIF, VP9, MJPEG, HEVC; 8 to 600 frames.
| check | result ||---|---|| state dict | 177/177 tensors identical (sha256), 0 missing / 0 unexpected, no transformers key translation (timm model), both checkpoints || model inputs (every frame of every video) | bit-exact: same frame count, every 504×504 input tensor identical (max abs diff 0.0) || per-frame logits, every frame (demo default) | max abs diff 4.8e-6 (frames batched 16 at a time; the demo runs one at a time) || video logit / P(fake), every frame | max abs diff 6.0e-7 / 2.8e-8 || served protocol (first 64 frames) vs the demo with `--limit 64` | max abs logit diff 2.7e-7 || `frame_batch=1` (the demo's batch) vs the demo | per-frame max abs diff 1.8e-15: identical; the 4.8e-6 above is CPU batching only |
Gate check on the demo's own videos (official demo output, logit > 0 = synthetic): `opensoraplan_-J24pksGK64_2.mp4`4.80 (G1) / 9.33 (G4), `real_-D8sIkdnSkM_0.mp4` -9.03 / -8.49.
**Frame decoder.** SynthScope reads frames with OpenCV exactly as the demo, so there is no decoder difference. Measuredfor reference (first 64 frames, both checkpoints): the demo's alternative PyAV reader (`ReadVideoIteratorAV`) gives thesame logits on all 15 videos (diff 0.0); decord (SynthScope's sampler for image detectors on video) gives the samelogits on 13, fails on the GIF, and on the WildScrape `.mov` returns 58 frames where OpenCV and PyAV decode 52 (OpenCVreports 58 in its header but stops reading after 52), which moves the G4 logit by 0.26 (P(fake) by 0.064). Protocolmatters too: on the 600-frame Sora clip the G4 logit is -2.61 over the first 64 frames and -1.20 over every frame.
## Results
**Verdict: faithful port (exact parity with the official demo, below); the paper's own benchmark is not held, so the onlypaper-comparable numbers are the paper's 8 GenVideo columns, a PARTIAL comparison. `waverep` (G1, the paper's model)reproduces 5 of those 8 cells to within about 2 points and does NOT reproduce HotShot (60.1 vs 81.4 bAcc), Show-1 (79.7vs 92.1) or LaVie (92.1 vs 95.5). Every other row is a zero-shot reference on a SynthScope benchmark, not a paperreproduction.**
Metrics: balanced accuracy at threshold 0.5 (logit 0; mean of real and fake accuracy) and AUC, the paper's metrics(Tables 1-2: bAcc, Table 7: AUC). Protocol for every number below: the official OpenCV reader, the first 64 frames(paper App. D), 504 centre crop, mean frame logit, fp32 (no TF32), `benchmark/bench_eval_video.py --model waverep|waverep_g4`.SynthScope_train is "-": the paper's training code is not released (only the augmentation), so there is no SynthScope-trained model.
### What is and is not the paper's benchmark
| | status ||---|---|| The paper's own test set: 7 generators (Allegro, CogVideoX 1.5, Open-Sora Plan, Mochi-1, NOVA, Sora, FLUX), 300 prompts each (2,100 fakes), against 300 Panda-70M YouTube clips | **NOT HELD.** The fakes are downloadable from grip.unina.it, but the reals are YouTube videos that need the authors' downloader script (`yt-dlp`, cookies); we did not scrape YouTube. Without the reals there is no bAcc or AUC, so a fakes-only run would not be the paper's benchmark. || The 8 GenVideo generators among the paper's columns in Tables 1-2 and 7 (Crafter, Gen2, HotShot, LaVie, ModelScope, MorphStudio, Show-1, MoonValley) | **PARTIAL comparison**, below. The paper says it uses "the publicly available GenVideo dataset" and does not say which real videos it paired with each generator; SynthScope scores every generator against GenVideo-Val's own 10,000 MSR-VTT reals. || GenVideo-Val extras (Sora, WildScrape), VideoPhy, VidProM, EvalCrafter | zero-shot references; the paper reports none of them (its "Sora" column is its own web set, not GenVideo's) |
### Partial comparison: the paper's 8 GenVideo generators (GenVideo-Val, full data)
Full GenVideo-Val per generator (10,000 reals + all fakes of that generator), 64 frames. Paper = "Ours" in Table 1 (bAcc) andTable 7 (AUC), the paper's single-generator detector (Pyramid Flow) = `waverep` (G1; the release says only "a single generator", so this identity is our inference). **G4 has no paper cell in these columns**(Table 5 trains it on four generators and reports other test sets); its columns are for reference only, and G4 is trained on fourgenerators, so its numbers are not single-generator generalization.
| Generator (n fake) | paper bAcc | G1 bAcc | G4 bAcc | paper AUC | G1 AUC | G4 AUC ||---|---:|---:|---:|---:|---:|---:|| Crafter (1398) | 98.3 | 98.99 | 98.90 | 99.8 | 99.90 | 99.98 || Gen2 (1380) | 98.8 | 99.49 | 98.90 | 100.0 | 99.99 | 99.99 || HotShot (700) | 81.4 | 60.10 | 83.40 | 91.0 | 75.60 | 94.15 || LaVie (1400) | 95.5 | 92.06 | 97.33 | 97.7 | 97.03 | 99.26 || ModelScope (700) | 97.1 | 95.24 | 97.54 | 99.4 | 99.31 | 99.69 || MorphStudio (700) | 97.0 | 97.74 | 98.61 | 99.3 | 99.74 | 99.94 || Show-1 (700) | 92.1 | 79.67 | 96.83 | 97.1 | 94.27 | 99.43 || MoonValley (626) | 98.4 | 99.12 | 98.89 | 99.9 | 99.97 | 99.98 || **8-generator mean** | **94.83** | **90.30** | 96.30 | **98.03** | **95.73** | 99.05 |
Source: `repro/bench_results/waverep_genvideo_full.json` and `waverep_g4_genvideo_full.json` (`per_generator` `acc` = balanced accuracyat 0.5, `auroc`); the paper's means are the means of its printed values.
* **Reproduced (within about 2 points of the paper, G1):** Crafter, Gen2, MorphStudio, MoonValley (within 0.75 bAcc and 0.5 AUC), ModelScope (-1.86 bAcc, -0.09 AUC).* **Not reproduced (G1):** HotShot -21.3 bAcc / -15.4 AUC, Show-1 -12.4 / -2.8, LaVie -3.4 / -0.7. HotShot: real accuracy 99.2, but only 21.0% of the fakes are called fake at P >= 0.5 (Show-1: 60.1%, LaVie: 84.9%), and the AUC drops too (75.6 vs 91.0), so it is not a threshold or calibration offset. **The cause is untested.** A different real pool or fake subset in the paper (unstated) is a possible cause; we cannot check it. SynthScope equals the official demo on every file compared (below), so it is not the code path.* G4 is above the paper's G1 on all 8 columns in bAcc (+0.1 to +4.7; Show-1 96.83, HotShot 83.4) and above or equal in AUC except Gen2 (99.99 vs 100.0).* Sora (56 fakes; G1 67.46 bAcc / 68.54 AUC, G4 76.65 / 83.61) and WildScrape (924; G1 78.87 / 86.92, G4 85.77 / 90.83) are GenVideo-Val extras with no paper cell.
### Zero-shot reference rows (NOT paper reproductions)
Benchmarks the paper does not report. Both keys are zero-shot on these sets, but G4 was trained on four generators (Table 5); do notread the G4 rows as the paper's single-generator generalization. mAP (fake as positive) on full GenVideo-Val is low only because of the10,000 : 56-1400 class imbalance; AUROC and mAP (real as positive) are not affected the same way. Means over the generators of each set.
| Set (protocol) | gens | key | bAcc@0.5 | mAP (fake +) | mAP (real +) | mAUROC ||---|---:|---|---:|---:|---:|---:|| GenVideo-Val full (10,000 reals + all fakes) | 10 | `waverep` | 86.87 | 79.85 | 99.24 | 92.13 || | | `waverep_g4` | 93.28 | 88.88 | 99.69 | 96.69 || GenVideo-Val `--limit 1000` | 10 | `waverep` | 86.62 | 89.81 | 93.96 | 92.09 || | | `waverep_g4` | 92.65 | 94.47 | 97.33 | 96.53 || VideoPhy `--limit 1000` | 8 | `waverep` | 90.00 | 93.21 | 98.44 | 96.54 || | | `waverep_g4` | 95.73 | 98.20 | 99.74 | 99.29 || VidProM `--limit 1000` | 4 | `waverep` | 89.85 | 98.11 | 97.94 | 98.06 || | | `waverep_g4` | 95.80 | 99.29 | 99.19 | 99.25 || EvalCrafter (fakes vs the first 1000 GenVideo-Val MSR-VTT reals) | 14 | `waverep` | 92.84 | 96.93 | 97.39 | 97.17 || | | `waverep_g4` | 96.55 | 99.19 | 99.35 | 99.29 |
Caveats:
* `--limit 1000`: the first 1000 clips per class per generator (the D3 protocol), so exactly 1000 reals and up to 1000 fakes; the full-data GenVideo-Val row has 10,000 reals.* **EvalCrafter has no reals of its own.** Its fakes (up to 700 per generator, 14 generators) are scored against the first 1000 GenVideo-Val MSR-VTT reals, the same for every generator; its HotShot, ModelScope, Show-1, MorphStudio and MoonValley cells equal the GenVideo `--limit 1000` cells (same videos).* VideoPhy: 8 of its 10 generators are online (dead links skipped). VidProM: ModelScope, Pika, Text2Video-Zero and VideoCrafter2 (the first 1000 clips each; the full set is terabytes); non-commercial licence.* **2 empty VidProM fakes are excluded** (Pika `00642_pika-9e93dcfc...`, `00891_pika-e025f9ee...`: 0-byte files in our VidProM copy, so OpenCV decodes no frame; the official demo would write NaN for them), so Pika has 998 fakes. All other sets: 0 decode failures. Per key the four per-set caches hold 37,859 entries (GenVideo-Val 18,584, VideoPhy 3,674, VidProM 5,000, EvalCrafter 10,601), i.e. 37,857 scored videos plus the 2 undecodable ones; this is a sum over sets, not a unique count (the 1000 EvalCrafter reals are the first 1000 GenVideo-Val reals).* Weakest cells (G1): VideoPhy OpenSora 62.15 and ZeroScope 63.75 bAcc, VidProM ModelScope 71.55, GenVideo HotShot 60.10 and Sora 67.46. G4 is better on every one of these.
Per generator (bAcc at 0.5 with real / fake accuracy in brackets; AUC):
**GenVideo-Val full (10,000 reals + all fakes)**
| Generator | n real / n fake | G1 bAcc (real / fake acc) | G1 AUC | G4 bAcc (real / fake acc) | G4 AUC ||---|---|---:|---:|---:|---:|| Crafter | 10000 / 1398 | 98.99 (99.2 / 98.8) | 99.90 | 98.90 (97.9 / 99.9) | 99.98 || Gen2 | 10000 / 1380 | 99.49 (99.2 / 99.8) | 99.99 | 98.90 (97.9 / 99.9) | 99.99 || HotShot | 10000 / 700 | 60.10 (99.2 / 21.0) | 75.60 | 83.40 (97.9 / 68.9) | 94.15 || LaVie | 10000 / 1400 | 92.06 (99.2 / 84.9) | 97.03 | 97.33 (97.9 / 96.7) | 99.26 || ModelScope | 10000 / 700 | 95.24 (99.2 / 91.3) | 99.31 | 97.54 (97.9 / 97.1) | 99.69 || MoonValley | 10000 / 626 | 99.12 (99.2 / 99.0) | 99.97 | 98.89 (97.9 / 99.8) | 99.98 || MorphStudio | 10000 / 700 | 97.74 (99.2 / 96.3) | 99.74 | 98.61 (97.9 / 99.3) | 99.94 || Show-1 | 10000 / 700 | 79.67 (99.2 / 60.1) | 94.27 | 96.83 (97.9 / 95.7) | 99.43 || Sora | 10000 / 56 | 67.46 (99.2 / 35.7) | 68.54 | 76.65 (97.9 / 55.4) | 83.61 || WildScrape | 10000 / 924 | 78.87 (99.2 / 58.5) | 86.92 | 85.77 (97.9 / 73.6) | 90.83 || **mean** | | **86.87** | 92.13 | **93.28** | 96.69 |
**VideoPhy `--limit 1000`**
| Generator | n real / n fake | G1 bAcc (real / fake acc) | G1 AUC | G4 bAcc (real / fake acc) | G4 AUC ||---|---|---:|---:|---:|---:|| Dream-Machine | 1000 / 339 | 99.50 (99.3 / 99.7) | 99.98 | 98.40 (96.8 / 100.0) | 100.00 || Gen-2 | 1000 / 312 | 99.65 (99.3 / 100.0) | 99.99 | 98.40 (96.8 / 100.0) | 100.00 || LaVie | 1000 / 343 | 98.48 (99.3 / 97.7) | 99.88 | 98.40 (96.8 / 100.0) | 99.96 || OpenSora | 1000 / 344 | 62.15 (99.3 / 25.0) | 88.55 | 83.43 (96.8 / 70.1) | 96.20 || Pika | 1000 / 304 | 99.32 (99.3 / 99.3) | 99.94 | 98.40 (96.8 / 100.0) | 99.99 || SVD | 1000 / 344 | 98.34 (99.3 / 97.4) | 99.67 | 98.40 (96.8 / 100.0) | 99.99 || VideoCrafter2 | 1000 / 344 | 98.78 (99.3 / 98.3) | 99.91 | 98.25 (96.8 / 99.7) | 99.96 || ZeroScope | 1000 / 344 | 63.75 (99.3 / 28.2) | 84.42 | 92.15 (96.8 / 87.5) | 98.22 || **mean** | | **90.00** | 96.54 | **95.73** | 99.29 |
**VidProM `--limit 1000`**
| Generator | n real / n fake | G1 bAcc (real / fake acc) | G1 AUC | G4 bAcc (real / fake acc) | G4 AUC ||---|---|---:|---:|---:|---:|| ModelScope | 1000 / 1000 | 71.55 (99.3 / 43.8) | 94.52 | 89.40 (96.8 / 82.0) | 97.59 || Pika | 1000 / 998 | 99.35 (99.3 / 99.4) | 99.97 | 98.35 (96.8 / 99.9) | 99.98 || Text2Video-Zero | 1000 / 1000 | 91.55 (99.3 / 83.8) | 98.10 | 97.35 (96.8 / 97.9) | 99.53 || VideoCrafter2 | 1000 / 1000 | 96.95 (99.3 / 94.6) | 99.66 | 98.10 (96.8 / 99.4) | 99.91 || **mean** | | **89.85** | 98.06 | **95.80** | 99.25 |
**EvalCrafter (reals: the first 1000 GenVideo-Val MSR-VTT)**
| Generator | n real / n fake | G1 bAcc (real / fake acc) | G1 AUC | G4 bAcc (real / fake acc) | G4 AUC ||---|---|---:|---:|---:|---:|| MoonValley | 1000 / 626 | 99.17 (99.3 / 99.0) | 99.97 | 98.32 (96.8 / 99.8) | 99.98 || floor33 | 1000 / 700 | 97.79 (99.3 / 96.3) | 99.74 | 98.04 (96.8 / 99.3) | 99.93 || gen2 | 1000 / 681 | 99.50 (99.3 / 99.7) | 99.99 | 98.25 (96.8 / 99.7) | 99.99 || gen2_december | 1000 / 699 | 99.58 (99.3 / 99.9) | 99.99 | 98.40 (96.8 / 100.0) | 100.00 || hotshot | 1000 / 700 | 60.15 (99.3 / 21.0) | 75.95 | 82.83 (96.8 / 68.9) | 93.75 || lavie-base | 1000 / 700 | 98.58 (99.3 / 97.9) | 99.83 | 98.26 (96.8 / 99.7) | 99.94 || lavie-interpolation | 1000 / 700 | 85.65 (99.3 / 72.0) | 94.30 | 95.26 (96.8 / 93.7) | 98.46 || mix-sr | 1000 / 700 | 99.58 (99.3 / 99.9) | 99.99 | 98.40 (96.8 / 100.0) | 100.00 || modelscope | 1000 / 700 | 95.29 (99.3 / 91.3) | 99.31 | 96.97 (96.8 / 97.1) | 99.61 || pika | 1000 / 697 | 96.57 (99.3 / 93.8) | 99.11 | 97.97 (96.8 / 99.1) | 99.92 || pika_v1_december_1 | 1000 / 700 | 97.58 (99.3 / 95.9) | 99.42 | 98.19 (96.8 / 99.6) | 99.91 || show_1 | 1000 / 700 | 79.72 (99.3 / 60.1) | 94.35 | 96.26 (96.8 / 95.7) | 99.35 || videocrafter-v1.0 | 1000 / 700 | 98.51 (99.3 / 97.7) | 99.81 | 98.26 (96.8 / 99.7) | 99.96 || zeroscope | 1000 / 598 | 92.12 (99.3 / 85.0) | 98.68 | 96.31 (96.8 / 95.8) | 99.32 || **mean** | | **92.84** | 97.17 | **96.55** | 99.29 |
The `--limit 1000` GenVideo-Val per-generator values are in `repro/bench_results/waverep_genvideo.json` / `waverep_g4_genvideo.json`.
### Official-demo parity on benchmark files
The unmodified official `demo/main_directory.py` (`--limit 64`, GPU) against the SynthScope scores of the benchmark run, bothcheckpoints, 180 GenVideo-Val files (the first 60 Crafter reals and the first 12 fakes of each of the 10 generators). Ours = the cachedscores of the benchmark run (RTX A5000 / RTX 6000, rounded to 6 decimals); official = DAS6 A6000. The differences are cross-devicefp32 noise, not a protocol difference. File: `repro/waverep_official_parity_genvideo180.json`.
| checkpoint | files compared | NaN | max abs logit diff | mean abs logit diff | max abs P(fake) diff | sign agreement ||---|---:|---:|---:|---:|---:|---:|| G1 | 180/180 | 0 | 1.02e-05 | 1.7e-06 | 2.1e-06 | 180/180 || G4 | 180/180 | 0 | 1.05e-05 | 1.4e-06 | 1.0e-06 | 180/180 |
Together with the 15-video, 6-codec check above (model inputs bit-exact, video logit max diff 6.0e-7), SynthScope's scores are theofficial demo's scores, so a difference from the paper is not a difference of this port; its cause (the unstated real pairing, thefake subset, or the paper's evaluation details) is untested.
### Jobs and files
Scores come from a resumable per-video cache (`bench_eval_video.py --cache-dir`, with `cache_meta.json` recording the checkpointsha256 `1c7566b2...a897` (G1) / `50d63904...5d53` (G4) and the preprocessing; the cache refuses a run whose setup differs). Foursets x two keys, scored in shards: IVI 285376_0 (cn027), 285390_3 and 285390_4 (cn031), 285389_2 and its remainder 285886_2, DAS667328 and its remainder 67404 (node409); full GenVideo-Val took about a day over three IVI GPUs and one DAS6 node. Aggregation: IVI286053, re-run as 286059 after the cache-identity fix with identical means (CPU, `--cache-only`). Official-demo parity: DAS6 67291.Task 1 parity: IVI 285339 (official side) and 285342. Logs: `repro/logs/waverep_*`. Result JSONs: `repro/bench_results/waverep[_g4]_{genvideo_full,genvideo,videophy,vidprom,evalcrafter}.json`;website data: `repro/benchmark_specs/waverep.json`, `waverep_g4.json`.
## Availability
Space: pending user approval. It requires uploading `weights_dinov2_G{1,4}.ckpt` to the hub repo (a decision for the maintainer,under the GRIP non-profit licence below), and a clip costs about 30 s on the Space's CPU (up to 64 ViT-B/14 forwards at 504 px).For that reason the keys are not in `deploy/hf-space/fetch_weights.py`.Not in the model zoo: place the checkpoints under `$SYNTHSCOPE_CKPT_DIR` as `waverep.pth` / `waverep_g4.pth`.
## License
GRIP-UNINA license (`LICENSE.md` of the official repository): free for informational and nonprofit purposes only,original notices kept, and the authors credited whenever results are made public. The checkpoints (distributed by GRIPalongside the code) are treated as covered by the same terms, as for B-Free. Citation (official, from the project page):
```@InProceedings{corvi2025seeing, title = {Seeing What Matters: Generalizable AI-generated Video Detection with Forensic-Oriented Augmentation}, author = {Riccardo Corvi and Davide Cozzolino and Ekta Prashnani and Shalini De Mello and Koki Nagano and Luisa Verdoliva}, booktitle = {The Thirty-ninth Annual Conference on Neural Information Processing Systems}, year = {2025}, url = {https://openreview.net/forum?id=dOGXKBL7IE}}```LEADERBOARD.md+1-1
LICENSES.md+7
benchmark/bench_eval.py+1-2
benchmark/bench_eval_video.py+261-41
benchmark/evaluate.py+2
benchmark/seed_reference_results.py+2-2
benchmark/submissions/co_spy_official.json+24-24
conf/dataset/image/cure_train.yamlAdded+18
conf/model/image/aide.yaml+11-7
conf/model/image/cure.yaml+8
conf/model/image/probe.yamlAdded+20
conf/model/image/probe_resnet.yamlAdded+18
conf/model/video/waverep.yamlAdded+18
conf/trainer/image/aide.yaml+22-4
conf/trainer/image/cure.yamlAdded+30
dataset.py+131
docs/ADD_DETECTOR.md+6-2
docs/CAPABILITIES.md+8-4
experiments/image/aide.sh+43-11
experiments/image/cure.shAdded+97
interface/README.md+6-3
interface/backend/build_repro_full.py+54-14
interface/backend/engine.py+78-5
interface/backend/hf_compat.pyAdded+67
interface/backend/media.py+42-4
interface/backend/registry.py+105-3
interface/backend/repro_full.json+318-40
interface/scripts/collect_checkpoints.py+25-4
interface/scripts/verify_model.py+3-2
interface/static/index.html+1-1
models/image/aide/README.md+28-4
models/image/aide/official_arch.py+7-2
models/image/co_spy/README.md+2
models/image/cure/README.md+188-15
models/image/cure/cure.py+89-7
models/image/cure/preprocess.py+10-3
models/image/cure/subspace.pyAdded+100
models/image/cure/train_augment.pyAdded+96
models/image/cure/train_stages.pyAdded+369
models/image/effort/effort.py+4-1
models/image/pgc/pgc.py+5-2
models/image/probe/README.mdAdded+283
models/image/probe/__init__.pyAdded
models/image/probe/official/__init__.pyAdded
models/image/probe/official/dino_classifier.pyAdded+77
models/image/probe/official/resnet50.pyAdded+256
models/image/probe/preprocess.pyAdded+98
models/image/probe/probe.pyAdded+92
models/video/waverep/README.mdAdded+266
models/video/waverep/__init__.pyAdded