Image Classification
Transformers
ONNX
Safetensors
Transformers.js
vit
ai-image-detection
deepfake-detection
image-forensics
agent-forensics
Run this model with HF Jobs
Run Tamarillo/ai-image-forensics-guard-tiny on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Tamarillo/ai-image-forensics-guard-tiny. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Tamarillo/ai-image-forensics-guard-tiny on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Tamarillo/ai-image-forensics-guard-tiny with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tamarillo/ai-image-forensics-guard-tiny with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-classification", model="Tamarillo/ai-image-forensics-guard-tiny") pipe("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/parrots.png")# pip install -U transformers accelerate # Load model directly from transformers import AutoImageProcessor, AutoModelForImageClassification processor = AutoImageProcessor.from_pretrained("Tamarillo/ai-image-forensics-guard-tiny") model = AutoModelForImageClassification.from_pretrained("Tamarillo/ai-image-forensics-guard-tiny", device_map="auto") - Transformers.js
How to use Tamarillo/ai-image-forensics-guard-tiny with Transformers.js:
// npm i @huggingface/transformers import { pipeline } from '@huggingface/transformers'; // Allocate pipeline const pipe = await pipeline('image-classification', 'Tamarillo/ai-image-forensics-guard-tiny'); - Notebooks
- Google Colab
- Kaggle
Release Tamarillo/ai-image-forensics-guard-tiny v2 (Apache-2.0, Stage-2 PASS, FLUX.1+DiT full-diffusion & FP16 ONNX)
Browse filesFiles changed (15)
- README.md+102-111
- assets/pareto.svg
- calibration.json+6-6
- config.json+1-2
- model.safetensors+1-1
- onnx/model.onnx+2-2
- onnx/model_fp16.onnxAdded+3
- onnx_bench.jsonAdded+42
- scripts/build_base_cache_v2.pyAdded+276
- scripts/eval_image_suite.py+14-1
- scripts/export_image_onnx.py+47-7
- scripts/prepare_v2_manifests.pyAdded+140
- scripts/synth_bfree_flux_v2.pyAdded+494
- scripts/train_image_v2.pyAdded+435
- train_summary.jsonAdded+13
3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940414243444546474849501 unmodified line5253545556575825 unmodified lines848586878889909192939495969715 unmodified lines1131141151161171181191201211221231241251269 unmodified lines1361371381391401411422 unmodified lines1451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692703 unmodified linespipeline_tag: image-classificationlibrary_name: transformersdatasets:- srishti-kaushik/COCO-2017- finedet/openimages- OwensLab/CommunityForensicstags:- ai-image-detection- deepfake-detection- image-forensics- agent-forensics- dinov2- onnx- transformers.js- ai-image-detector- ai-detector- synthetic-image-detection---# Tamarillo/ai-image-forensics-guard-tiny> **Family Tiers:** [`ai-image-forensics-guard-tiny`](https://huggingface.co/Tamarillo/ai-image-forensics-guard-tiny) *(this model)* · [`ai-image-forensics-guard-small`](https://huggingface.co/Tamarillo/ai-image-forensics-guard-small) · [`ai-image-forensics-guard-base`](https://huggingface.co/Tamarillo/ai-image-forensics-guard-base)> **Interactive Browser Demo (100% Client-Side WASM):** [`Tamarillo/ai-image-forensics-guard-demo`](https://huggingface.co/spaces/Tamarillo/ai-image-forensics-guard-demo)**Ultra-Fast Edge CPU & Browser WASM Tier (22.1M, DINOv2-Small, 224px)** — an **Apache-2.0**, social-media-recompression-hardened AI-generated image forensics detector (native `AutoModelForImageClassification`, zero `trust_remote_code`) designed as a **1-line drop-in replacement** (`id2label = {0: "artificial", 1: "human"}`) for `umm-maybe/AI-image-detector` and `Organika/sdxl-detector` in Hugging Face `image-classification` pipelines, edge CPU sidecars, and client-side browser WASM (`Transformers.js`).### Key Highlights- **Fastest evaluated model on 4-thread x86 CPU (`82.3 ms`, `88.5 MB` exact-parity FP32 ONNX)** — `1.71×` faster and `4.0×` smaller than `umm-maybe/AI-image-detector` (`140.9 ms`, `353.7 MB`) and faster than `CommunityForensics-ViT` (`94.0 ms`) and `Ateeqq` (`101.2 ms`).- **Outperforms `4×` larger `umm-maybe` & `Organika`:** Achieves **`28.52%`** 3-Corpus Unique Zero-Touch EER (`0.7862` AUC) and **`30.82%`** 4-Suite Zero-Touch EER vs. `umm-maybe` (`37.56%`) and non-commercial `Organika` (`36.27%`), while ranking **#3 overall on `Synthbuster` (`19.05%` EER / `0.899` AUC; at `0.50`: `42.9%` fake recall, `1.5%` real-photo FPR)**.- **Honest Tradeoff:** Larger/higher-resolution tiers (`Tamarillo small` `26.90%`, `Tamarillo base` `19.98%` 5-suite EER) and `haywoodsloan` (`20.68%`) / `CommunityForensics-ViT` (`25.45%`) / `Ateeqq` (`27.50%`) achieve lower overall EER than `tiny` (`30.53%`); choose `tiny` when `<85 ms` CPU or client-side browser WASM footprint is the primary constraint.---## Model Family & Recommended TierInteractive 100% client-side in-browser image-drop & WhatsApp/X recompression stress demo (running `tiny` `88.5 MB` exact-parity FP32 ONNX locally): Hugging Face Space [`Tamarillo/ai-image-forensics-guard-demo`](https://huggingface.co/spaces/Tamarillo/ai-image-forensics-guard-demo) (published alongside this model family).| Model | Backbone | Params | Input Res | Social-Recomp EER ↓ | Synthbuster EER ↓ | 3-Corpus Unique Zero-Touch (EER ↓ / AUC ↑) | 5-Suite Public Mean (EER ↓ / AUC ↑) | CPU FP32 ONNX | ONNX Size || :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: || `Tamarillo/ai-image-forensics-guard-tiny` *(this repo)* | `facebook/dinov2-small` | 22.1M | 224×224 | 37.71% | 19.05% | 28.52% / 0.7862 | 30.53% / 0.7652 | 82.3 ms | 88.5 MB || `Tamarillo/ai-image-forensics-guard-small` | `facebook/convnextv2-tiny-22k-384` | 27.9M | 384×384 | 30.59% | 9.45% | 26.65% / 0.7908 | 26.90% / 0.8015 | 136.8 ms | 111.6 MB || `Tamarillo/ai-image-forensics-guard-base` | `google/siglip2-base-patch16-384` | 93.2M | 384×384 | 20.12% | 10.00% | 20.73% / 0.8573 | 19.98% / 0.8709 | 312.7 ms | 344.6 MB |---1 unmodified lineRequires `transformers>=4.40` (zero `trust_remote_code`).> **Operating-Point Note:** At default `0.50` argmax, `Tamarillo/ai-image-forensics-guard-tiny` achieves `41.3%` fake recall / `14.8%` real-photo FPR on clean `OpenFake Core`, `42.9%` fake recall / `1.5%` real-photo FPR on `Synthbuster`, and `55.9%` fake recall / `31.0%` real FPR under heavy `Social-Media Recompressed` stress (`512px` JPEG Q45 + WebP Q55). Note that `pipeline()` outputs uncalibrated softmax probabilities (identical `0.50` argmax, whereas raw probability values differ from `calibration.json` temperature-scaled probabilities `T = 1.3757`).```bashpip install "transformers>=4.40" torch pillow25 unmodified linesprocessor = AutoImageProcessor.from_pretrained(repo_id)model = AutoModelForImageClassification.from_pretrained(repo_id).eval()# Wiring smoke test (replace with: img = Image.open("photo.jpg").convert("RGB"))img = Image.new("RGB", (512, 512), color=(128, 128, 128))inputs = processor(images=img, return_tensors="pt")with torch.no_grad():logits = model(**inputs).logits[0]raw_probs = torch.softmax(logits, dim=-1)# Optional temperature scaling from calibration.json (T=1.3757)cal_probs = torch.softmax(logits / 1.3757, dim=-1)p_art = float(cal_probs[0])verdict = "ARTIFICIAL" if p_art >= 0.50 else "HUMAN"15 unmodified linesrepo_id = "Tamarillo/ai-image-forensics-guard-tiny"processor = AutoImageProcessor.from_pretrained(repo_id)onnx_path = hf_hub_download(repo_id=repo_id, filename="onnx/model.onnx") # 88.5 MB FP32 (82.3 ms 4-thread CPU)sess = ort.InferenceSession(onnx_path, providers=["CPUExecutionProvider"])# Wiring smoke test (replace with: img = Image.open("photo.jpg").convert("RGB"))img = Image.new("RGB", (512, 512), color=(128, 128, 128))pixel_values = processor(images=img, return_tensors="np")["pixel_values"].astype(np.float32)logits = sess.run(None, {"pixel_values": pixel_values})[0][0]scaled = logits / 1.3757 # temperature T from calibration.jsonex = np.exp(scaled - scaled.max())probs = ex / ex.sum()print(f"cal P(artificial)={probs[0]:.4f} | cal P(human)={probs[1]:.4f}")9 unmodified linesimport { pipeline, RawImage } from "@huggingface/transformers";const detector = await pipeline("image-classification", "Tamarillo/ai-image-forensics-guard-tiny", {dtype: "fp32", // loads exact-parity 88.5 MB onnx/model.onnx});// Self-contained 224x224 wiring smoke-test image (replace with an image URL, Blob, or file path)2 unmodified linesconsole.log(results); // [{ label: "artificial", score: ... }, { label: "human", score: ... }]```> Recommended tier for client-side browser WASM and `<85 ms` CPU sidecars. For stronger accuracy on 2026 generators and heavily recompressed social-media imagery, use `Tamarillo/ai-image-forensics-guard-small` (`27.9M`, `384px`) or `Tamarillo/ai-image-forensics-guard-base` (`93.2M`, `384px`).---## Label Schema & Calibration (`calibration.json`)| Class ID | Label | Meaning || :---: | :--- | :--- || `0` | `artificial` | AI-generated / synthetic image (diffusion, flow-matching DiT, GAN, or AI video frame). || `1` | `human` | Authentic human photograph. |- **Calibration ([`calibration.json`](calibration.json)):** Generator-disjoint validation EER = `4.16%`, validation ROC-AUC = `0.9928`, validation temperature `T = 1.3757`, calibrated ECE = `0.0249`. Reference validation operating cutoffs on temperature-scaled `P(artificial)`: 5% FPR at `τ = 0.2105`, 1% FPR at `τ = 0.7230`. Because in-domain validation separation is much tighter than unseen wild 2026 generators, treat validation `thr_val_5pct_fpr` as a lower bound and calibrate `τ` on a small target-domain sample (or start at `0.50`).---## Benchmarks (3 Unique Zero-Touch Corpora + Social-Media Compression Stress + Held-Out `CommunityForensics-Eval`)All 8 models were evaluated head-to-head on identical frozen RGB images with **zero evaluation images present in training**. Full reproducible synthesis, data, training, ONNX, and evaluation scripts are bundled in this repository: [`scripts/synth_2026_images.py`](scripts/synth_2026_images.py), [`scripts/build_image_data.py`](scripts/build_image_data.py), [`scripts/train_image_model.py`](scripts/train_image_model.py), [`scripts/eval_image_suite.py`](scripts/eval_image_suite.py), and [`scripts/export_image_onnx.py`](scripts/export_image_onnx.py). Bold marks the best value (or ties) in each column.### Evaluation Protocol & Subsampling Details- **Non-Double-Counted vs. Stress & Held-Out Averages:** Because `ood_social_recompressed` is a derived stress transform of `1,000` images from `ood_openfake_core` and `700` images from `ood_synthbuster` (and its compression chain resembles Tamarillo's training augmentations), we report **three explicit aggregates**:1. **3-Corpus Unique Zero-Touch Mean (`[U3]`):** Equal mean over the 3 strictly disjoint zero-touch corpora (`OpenFake Core`, `OpenFake Reddit`, `Synthbuster`) — **zero image overlap, zero real-source overlap, zero generator overlap**.2. **4-Suite Zero-Touch Mean (`[Z4]`):** Includes the `Social-Media Recompressed` stress suite alongside the 3 unique zero-touch corpora.3. **5-Suite Public Mean (`[5S]`):** Includes `CommunityForensics-Eval` (`CompEval`), which is a held-out CVPR 2025 benchmark whose parent corpus family (`Systematic+Manual`, strictly excluding `PublicEval` and `Commercial`) appeared in Tamarillo's training mix.- **Dataset Sizes & Sampling Seeds:**- `ood_openfake_core` (`ComplexDataLab/OpenFake` `core/test`, eval-only, **`n=2,000`: 1,000 real / 1,000 fake, `seed=201`**): 2025–2026 generators vs. `DOCCI` smartphone photos & `ImageNet`.- `ood_openfake_reddit` (`ComplexDataLab/OpenFake` `reddit/test`, eval-only, **`n=1,600`: 800 real / 800 fake, `seed=202`**): wild social-media compressed real vs. AI imagery & video frames.- `ood_synthbuster` (`marco-willi/synthbuster-plus` `test`, eval-only, **`n=1,200`: 200 real / 1,000 fake, `seed=203`** — all available real `RAISE` test photos + 1,000 fakes from `DALL-E 2/3`, `Midjourney v5`, `Adobe Firefly`, `SDXL`; EER and ROC-AUC are class-ratio invariant).- `ood_social_recompressed` (**`n=1,700`: 700 real / 1,000 fake, `seed=204`** — `500` real + `500` fake from `ood_openfake_core` plus `200` real + `500` fake from `ood_synthbuster`): every image deterministically passed through **Bilinear resize (`max_side=512`) → `JPEG Q45` → `WebP Q55`**.- `eval_commfor_comp` (`OwensLab/CommunityForensics-Eval` `CompEval`, eval-only, **`n=2,000`: 1,000 real / 1,000 fake, `seed=205`**).- **Incumbent Scoring Fairness:** Every Hugging Face incumbent (`umm-maybe`, `Organika`, `Ateeqq`, `haywoodsloan`) was evaluated with its native `AutoImageProcessor` and `id2label`. `buildborderless/CommunityForensics-DeepfakeDet-ViT` was evaluated using its official `CLIPImageProcessor` (`384px`) and its official FP32 ONNX artifact.### 1. Core 5-Suite Public Benchmark (EER % ↓ and ROC-AUC ↑)| Model | Params | Official ONNX | OpenFake Core [Z] | OpenFake Reddit [Z] | Synthbuster [Z] | Social-Recomp [Stress] | CommFor-Eval | 3-Corpus Unique [U3] | 4-Suite [Z4] | 5-Suite Mean [5S] || :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: || **Tamarillo `tiny` (DINOv2-S, 224px)** | 22.1M | Yes (FP32) | 35.90% (0.696) | 30.63% (0.764) | 19.05% (0.899) | 37.71% (0.684) | 29.35% (0.783) | 28.52% / 0.7862 | 30.82% / 0.7608 | 30.53% / 0.7652 || Tamarillo `small` (ConvNeXtV2-T, 384px) | 27.9M | Yes (FP32) | 36.70% (0.684) | 33.81% (0.716) | **9.45%** (0.973) | 30.59% (0.780) | 23.95% (0.856) | 26.65% / 0.7908 | 27.64% / 0.7880 | 26.90% / 0.8015 || Tamarillo `base` (SigLIP2-B, 384px) | 93.2M | Yes (FP32) | 25.50% (0.805) | 26.69% (0.808) | 10.00% (0.959) | **20.12%** (0.872) | 17.60% (0.911) | 20.73% / 0.8573 | 20.58% / 0.8610 | **19.98%** / **0.8709** || `haywoodsloan/ai-image-detector-deploy` | 195.2M | No | **13.20%** (0.931) | **21.56%** (0.882) | 19.95% (0.883) | 26.24% (0.813) | 22.45% (0.839) | **18.24%** / **0.8985** | **20.24%** / **0.8770** | 20.68% / 0.8693 || `buildborderless/CommunityForensics-DeepfakeDet-ViT` | 21.8M | Yes (FP32)* | 20.35% (0.877) | 33.50% (0.736) | 22.95% (0.835) | 41.12% (0.635) | **9.35%** (0.971) | 25.60% / 0.8158 | 29.48% / 0.7707 | 25.45% / 0.8108 || `Ateeqq/ai-vs-human-image-detector` | 92.9M | No | 17.15% (0.906) | 22.00% (0.858) | 28.00% (0.795) | 27.71% (0.810) | 42.65% (0.615) | 22.38% / 0.8528 | 23.71% / 0.8421 | 27.50% / 0.7966 || `Organika/sdxl-detector` (`CC-BY-NC-3.0`) | 86.8M | Yes (FP32) | 38.15% (0.656) | 38.88% (0.645) | 27.60% (0.793) | 40.46% (0.638) | 27.20% (0.800) | 34.88% / 0.6980 | 36.27% / 0.6829 | 34.46% / 0.7064 || `umm-maybe/AI-image-detector` | 86.8M | No | 41.70% (0.625) | 31.37% (0.744) | 39.50% (0.649) | 37.66% (0.670) | 43.25% (0.585) | 37.53% / 0.6724 | 37.56% / 0.6719 | 38.70% / 0.6546 |*`[Z]` marks the 3 unique strictly zero-touch OOD corpora; `Social-Recomp` is a compression stress transform of `OpenFake Core` + `Synthbuster`. \*Note: `CommunityForensics-DeepfakeDet-ViT`'s shipped INT8 ONNX variant fails to load in standard ORT CPU (`ConvInteger(10)` unimplemented); its official FP32 ONNX artifact was used.*### 2A. Per-2026-Generator ROC-AUC on `OpenFake Core` (All 10 Evaluated Generators)| Model | `illustrious` | `wan-2.5` | `midjourney-7` | `recraft-v3` | `veo-3` | `ernie-turbo` | `z-image-turbo` | `gpt-image-1.5` | `gpt-image-2` | `flux.2-klein-9b` || :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: || **Tamarillo `tiny` (DINOv2-S, 224px)** | 0.825 | 0.849 | 0.751 | 0.721 | 0.857 | 0.802 | 0.748 | 0.678 | 0.505 | 0.438 || Tamarillo `small` (ConvNeXtV2-T, 384px) | 0.864 | 0.916 | 0.814 | 0.742 | 0.740 | 0.794 | 0.742 | 0.685 | 0.643 | 0.324 || Tamarillo `base` (SigLIP2-B, 384px) | 0.963 | 0.958 | 0.891 | 0.884 | 0.883 | 0.868 | 0.867 | 0.852 | 0.680 | 0.474 || `haywoodsloan/ai-image-detector-deploy` | 0.995 | 0.996 | 0.991 | 0.982 | 0.988 | 0.998 | 0.947 | 0.988 | 0.963 | 0.751 || `buildborderless/CommunityForensics-DeepfakeDet-ViT` | 0.993 | 0.966 | 0.926 | 0.967 | 0.942 | 0.864 | 0.907 | 0.894 | 0.795 | 0.667 || `Ateeqq/ai-vs-human-image-detector` | 0.981 | 0.986 | 0.833 | 0.817 | 0.968 | 0.915 | 0.937 | 0.864 | 0.933 | 0.844 || `Organika/sdxl-detector` (`CC-BY-NC-3.0`) | 0.857 | 0.895 | 0.834 | 0.669 | 0.749 | 0.592 | 0.580 | 0.752 | 0.742 | 0.372 || `umm-maybe/AI-image-detector` | 0.377 | 0.581 | 0.501 | 0.617 | 0.686 | 0.634 | 0.746 | 0.749 | 0.576 | 0.614 |### 2B. Operating-Point Trade-off at Default `τ = 0.50` (Fake Recall / Real-Photo FPR)| Model | OpenFake Core @0.50 (Rec / Real FPR) | Synthbuster @0.50 (Rec / Real FPR) | Social-Recomp @0.50 (Rec / Real FPR) || :--- | :---: | :---: | :---: || **Tamarillo `tiny` (DINOv2-S, 224px)** | 41.3% / 14.8% | 42.9% / 1.5% | 55.9% / 31.0% || Tamarillo `small` (ConvNeXtV2-T, 384px) | 31.5% / 6.7% | 47.2% / 0.0% | 54.5% / 18.4% || Tamarillo `base` (SigLIP2-B, 384px) | 47.1% / 3.3% | 53.1% / 0.0% | 73.9% / 14.6% || `haywoodsloan/ai-image-detector-deploy` | 72.7% / 2.8% | 58.6% / 6.0% | 32.8% / 1.1% || `buildborderless/CommunityForensics-DeepfakeDet-ViT` | 26.3% / 0.0% | 55.4% / 1.5% | 8.9% / 1.9% || `Ateeqq/ai-vs-human-image-detector` | 83.4% / 17.6% | 47.8% / 9.5% | 73.2% / 28.7% || `Organika/sdxl-detector` (`CC-BY-NC-3.0`) | 49.8% / 22.6% | 52.1% / 13.0% | 34.0% / 16.6% || `umm-maybe/AI-image-detector` | 39.4% / 16.5% | 26.4% / 11.0% | 60.0% / 34.7% |---## ONNX Parity & Same-Machine 4-Thread x86 CPU Latency (`bs=1`)Hardware: GCP `g2-standard-8` (Intel Xeon Cascade Lake, 4 ORT intra-op threads, `bs=1`, median p50 ms over 25 timed runs after 5 warmups). For apples-to-apples CPU timing across the `22M–93M` drop-in tier, incumbents without official ONNX (`umm-maybe`, `Ateeqq`) were exported locally to FP32 ONNX on the exact same machine (heavyweight `195.2M` `haywoodsloan` was omitted from local CPU ONNX export, and GPU latency was not separately timed):- `umm-maybe/AI-image-detector` (`86.8M`, `224px`, `353.7 MB` FP32): **`140.92 ms`**- `Organika/sdxl-detector` (`86.8M`, `224px`, `353.7 MB` official FP32, `CC-BY-NC-3.0`): **`138.08 ms`**- `Ateeqq/ai-vs-human-image-detector` (`92.9M`, `224px`, `343.4 MB` FP32): **`101.23 ms`**- `buildborderless/CommunityForensics-DeepfakeDet-ViT` (`21.8M`, `384px`, `87.4 MB` official FP32): **`94.04 ms`** (its shipped INT8 ONNX variant errored on `ConvInteger(10)`)| Artifact | Input Res | File Size | Parity (`n=64` OpenFake Core: Argmax / Max Δp / Mean Δp) | 4-Thread CPU p50 | 4-Thread CPU p90 || :--- | :---: | :---: | :---: | :---: | :---: || `onnx/model.onnx` (FP32) | 224×224 | 88.5 MB | 100.0% / `0.00000` / `0.00000` | **82.35 ms** | 82.93 ms |- **Quantization Hygiene:** Dynamic INT8 (`max Δp = 0.376`, `mean Δp = 0.0395`, `93.8%` argmax) was automatically discarded by our parity gate (`mean Δp <= 0.015`, `argmax >= 98%`), and FP16 conversion was omitted due to ORT `Conv`/norm mixed-type mismatches. Accordingly, `Tamarillo/ai-image-forensics-guard-tiny` ships **exact-parity FP32 ONNX (`onnx/model.onnx`, `max Δp = 0.00000`, `100%` argmax agreement across `n=64` held-out `OpenFake Core` images)**.---## Training Recipe & Upstream-Audited Data ProvenanceTrained end-to-end with **symmetric social-media degradation augmentation** applied identically to both `artificial` and `human` images (random aspect-preserving crop, horizontal flip, Bilinear/Bicubic/Lanczos downscale `0.45×–0.88×`, mild Gaussian blur / UnsharpMask smartphone sharpening, subtle color jitter, and real `JPEG Q35–95` / `WebP Q40–95` / double-JPEG re-encoding) using focal cross-entropy (`gamma=1.0`, label smoothing `0.03`), differential LR (head `5×`), EMA (`0.996`), and validation-only EER selection on **`24,326` training images** (`12,567` human / `11,759` artificial) and **`2,066` generator-disjoint validation images** (`1,033` human / `1,033` artificial), upweighting 1:1 matched 2025–2026 DiT pairs `2.5×`. Every training source carries verified commercially permissive provenance (zero `NC`, zero `SA`, zero ImageNet):1. **Commercial MS-COCO 2017 (`train2017` ONLY, strictly filtered to `license ∈ {4, 7, 8}` = `CC-BY-2.0` / Public Domain; excluding all `NC`/`SA`/`ND` licenses and `val2017`)** (`srishti-kaushik/COCO-2017`): **`3,167` train / `433` val** (`3,600` total authentic photos).2. **Fresh 2025–2026 Apache-2.0 Flow-Matching DiT Pairs (Matched 1:1 on Captions & Aspect Ratios to Commercial COCO):** **`3,167` train / `433` val** (`3,600` total synthetic images) generated on A100 using **`Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers`** (`1,450` train / `150` val, DC-AE 32× 2-step consistency DiT, `Apache-2.0`), **`Efficient-Large-Model/SANA1.5_1.6B_1024px_diffusers`** (`1,050` train / `150` val, DC-AE 32× flow-matching DiT, `Apache-2.0`), and **`Alpha-VLLM/Lumina-Image-2.0`** (`667` train / `133` val, 16-ch Flow-Matching VAE Next-DiT, `Apache-2.0`) — 100% disjoint from `OpenFake` `core/test`.3. **Open Images V7** (`finedet/openimages`, `CC-BY-4.0` annotations / `CC-BY-2.0` Flickr photos): **`9,400` train / `600` val** (`10,000` total diverse real photos).4. **Community Forensics (`Systematic` + `Manual` ONLY, `nsfw_flag=False`, excluding `PublicEval` & `Commercial`)** (`OwensLab/CommunityForensics`, `CC-BY-4.0`): **`8,592` train (`5,105` `Systematic` + `3,487` `Manual`) / `600` unseen-generator val** (`808` surplus rows from held-out validation generator models were excluded from training to enforce strict generator disjointness).*Exact totals: Train = `3,167 + 3,167 + 9,400 + 8,592 = 24,326` (`12,567` human + `11,759` artificial); Val = `433 + 433 + 600 + 600 = 2,066` (`1,033` human + `1,033` artificial).*---## Honest Limitations & Where Baselines Win1. **Capacity & Unseen-Generator Gaps (`haywoodsloan`, `Ateeqq`, `CommunityForensics-ViT`, & Larger Tamarillo Tiers Win Overall):** At `22.1M` (`224px`), `Tamarillo/ai-image-forensics-guard-tiny` trails larger/higher-res baselines on 3-Corpus Unique Zero-Touch EER (`28.52%` vs. `haywoodsloan` `18.24%`, `Ateeqq` `22.38%`, `Tamarillo base` `20.73%`) and 5-Suite EER (`30.53%` vs. `CommunityForensics-ViT` `25.45%`). Because Tamarillo intentionally held out all FLUX and proprietary OpenAI generators from training, `Tamarillo/ai-image-forensics-guard-tiny` struggles severely on `flux.2-klein-9b` (`0.438` AUC vs. `Ateeqq` `0.844`) and `gpt-image-2` (`0.505` AUC vs. `haywoodsloan` `0.963`).2. **`CommunityForensics-Eval` Home-Benchmark Advantage:** `buildborderless/CommunityForensics-DeepfakeDet-ViT` (`9.35%` EER) significantly outperforms Tamarillo (`17.60%–29.35%` EER) on its own home `eval_commfor_comp` split (having trained on all 2.7M CommunityForensics images vs. Tamarillo's `8,592`-image subsample), while collapsing to `41.12%` EER (`8.9%` fake recall) under `Social-Media Recompressed` stress.3. **Operating-Point Tradeoffs & Forensic Edge Cases:** On clean `OpenFake Core`, default `0.50` is conservative (`41.3%` fake recall at `14.8%` real-photo FPR on `Tamarillo/ai-image-forensics-guard-tiny`), whereas heavy social-media recompression (`JPEG Q45 + WebP Q55 + 512px`) increases real-photo false positives (`31.0%` real FPR at `55.9%` fake recall). Additionally, binary whole-image detectors can struggle on **partial edits / localized AI inpainting**, **heavily retouched or filtered smartphone photos**, **UI screenshots**, and **3D CGI / digital illustrations**. Treat probabilities as one signal inside a layered verification workflow (C2PA content credentials, metadata/EXIF checks, and human review for high-stakes decisions).4. **FP32-Only ONNX Shipping:** Dynamic INT8 and FP16 ONNX exports did not clear our strict parity gate on forensic pixel features and were intentionally omitted; only exact-parity FP32 `onnx/model.onnx` is shipped.---## License, Attribution & CitationModel weights and code are released under the **Apache-2.0 License** by **Tamarillo**. Training data attributions: MS-COCO 2017 commercial subset (`CC-BY-2.0` / Public Domain), Open Images V7 (`CC-BY-2.0` / `CC-BY-4.0`), Community Forensics (`CC-BY-4.0`), SANA-Sprint & SANA-1.5 (`Apache-2.0`), and Lumina-Image-2.0 (`Apache-2.0`).```bibtex@misc{tamarillo_ai_image_forensics_guard_2026,title = {Tamarillo AI-Image Forensics Guard: Social-Media-Hardened Visual Deepfake Detectors},author = {Tamarillo Open-Model Lab},year = {2026},howpublished = {\url{https://huggingface.co/Tamarillo/ai-image-forensics-guard-tiny}},3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839404142434445461 unmodified line4849505152535425 unmodified lines80818283848586878889909115 unmodified lines1071081091101111121131141151161171181199 unmodified lines1291301311321331341352 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602613 unmodified linespipeline_tag: image-classificationlibrary_name: transformersdatasets:- Tamarillo/ai-image-forensics-bfree-2026- srishti-kaushik/COCO-2017- finedet/openimages- OwensLab/CommunityForensicstags:- ai-image-detection- deepfake-detection- image-forensics- agent-forensics- dinov2- onnx- transformers.js---# Tamarillo/ai-image-forensics-guard-tiny**v2 Ultra-Fast Edge CPU & 44 MB Browser WASM Tier (22.1M, DINOv2-Small, 224px)** — an **Apache-2.0**, social-media-recompression-hardened AI-generated image forensics detector (native `AutoModelForImageClassification`, zero `trust_remote_code`) designed as a **1-line drop-in replacement** (`id2label = {0: "artificial", 1: "human"}`) for `umm-maybe/AI-image-detector` and `Organika/sdxl-detector` in Hugging Face `image-classification` pipelines, edge CPU sidecars, and client-side browser WASM (`Transformers.js`).### v2 Key Highlights- **v2 Edge & Browser WASM Upgrade (`22.1M`, `224px`):** Improves EER on every aggregate over v1 — 3-Corpus Unique Zero-Touch `[U3]` `28.26%` -> **`27.53%`**, 4-Suite Zero-Touch `[Z4]` `30.79%` -> **`29.92%`**, and 5-Suite Public Mean `[5S]` `30.49%` -> **`29.28%`** (`[5S]` AUC `0.7655` -> **`0.7689`**, while `[U3]`/`[Z4]` AUC sit fractionally below v1: `0.7871` -> `0.7854` and `0.7612` -> `0.7571`), alongside major gains on `Synthbuster` (`18.05%` -> **`14.40%`**), `OpenFake Reddit` (`30.69%` -> **`28.88%`**), and `CommFor-Eval` (`29.30%` -> **`26.70%`**).- **Fastest Evaluated Model & Half-Size Browser WASM (`74.2 ms` CPU FP32; `44.4 MB` FP16 ONNX):** `1.88×` faster than `umm-maybe/AI-image-detector` (`139.5 ms`, `353.7 MB`) and faster than `CommunityForensics-ViT` (`91.7 ms`) and `Ateeqq` (`99.2 ms`), while cutting WASM download size in half (`88.5 MB -> 44.4 MB`, `100.0%` argmax parity, `max Δp=0.00249`).- **Honest Tradeoff:** While `tiny` v2 beats v1 on EER across all 3 aggregates, v1 `tiny` retains lower EER on clean `OpenFake Core` (`36.05%` vs. `39.30%`), and `SigLIP-2` tiers (`Tamarillo v2 small` `22.79%`, `base` `19.34%` `[Z4]` EER) achieve substantially lower EER; choose `tiny` when `<75 ms` CPU or `44 MB` browser WASM download size is the priority.---## Model Family & Recommended Tier (v2)- **Interactive Browser WASM Demo:** [`Tamarillo/ai-image-forensics-guard-demo`](https://huggingface.co/spaces/Tamarillo/ai-image-forensics-guard-demo) (runs `tiny` v2 `44.4 MB` `100.0%`-parity FP16 ONNX 100% locally in-browser).- **Companion Open Apache-2.0 Corpus:** [`Tamarillo/ai-image-forensics-bfree-2026`](https://huggingface.co/datasets/Tamarillo/ai-image-forensics-bfree-2026) (`14,800` train + `800` cross-generator `Shuttle-3` OOD test images).| Model (v2) | Backbone | Params | Input Res | Social-Recomp EER ↓ | Synthbuster EER ↓ | 3-Corpus Unique [U3] (EER ↓ / AUC ↑) | 4-Suite Zero-Touch [Z4] (EER ↓ / AUC ↑) | CPU FP32 ONNX | Shipped ONNX || :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: || [`Tamarillo/ai-image-forensics-guard-tiny`](https://huggingface.co/Tamarillo/ai-image-forensics-guard-tiny) *(this repo)* | `facebook/dinov2-small` | 22.1M | 224×224 | 37.12% | 14.40% | 27.53% / 0.7854 | 29.92% / 0.7571 | 74.2 ms | 44.4 MB (FP16) / 88.5 MB (FP32) || [`Tamarillo/ai-image-forensics-guard-small`](https://huggingface.co/Tamarillo/ai-image-forensics-guard-small) | `google/siglip2-base-patch16-224` | 92.9M | 224×224 | 26.17% | 10.70% | 21.66% / 0.8589 | 22.79% / 0.8497 | 98.3 ms | 171.8 MB (FP16) / 343.4 MB (FP32) || [`Tamarillo/ai-image-forensics-guard-base`](https://huggingface.co/Tamarillo/ai-image-forensics-guard-base) | `google/siglip2-base-patch16-384` | 93.2M | 384×384 | 20.29% | 9.55% | 19.02% / 0.8761 | 19.34% / 0.8760 | 304.5 ms | 172.4 MB (FP16) / 344.6 MB (FP32) |---1 unmodified lineRequires `transformers>=4.40` (zero `trust_remote_code`).> **Operating-Point Note:** At default `0.50` argmax, `Tamarillo/ai-image-forensics-guard-tiny` achieves `43.9%` fake recall / `20.2%` real-photo FPR on clean `OpenFake Core`, `59.4%` fake recall / `2.0%` real-photo FPR on `Synthbuster`, and `59.5%` fake recall / `33.9%` real FPR under heavy `Social-Media Recompressed` stress (`512px` JPEG Q45 + WebP Q55). `pipeline()` outputs uncalibrated softmax probabilities (identical `0.50` argmax; optional temperature `T = 1.0810` is stored in [`calibration.json`](calibration.json)).```bashpip install "transformers>=4.40" torch pillow25 unmodified linesprocessor = AutoImageProcessor.from_pretrained(repo_id)model = AutoModelForImageClassification.from_pretrained(repo_id).eval()img = Image.new("RGB", (512, 512), color=(128, 128, 128))inputs = processor(images=img, return_tensors="pt")with torch.no_grad():logits = model(**inputs).logits[0]raw_probs = torch.softmax(logits, dim=-1)cal_probs = torch.softmax(logits / 1.0810, dim=-1)p_art = float(cal_probs[0])verdict = "ARTIFICIAL" if p_art >= 0.50 else "HUMAN"15 unmodified linesrepo_id = "Tamarillo/ai-image-forensics-guard-tiny"processor = AutoImageProcessor.from_pretrained(repo_id)onnx_path = hf_hub_download(repo_id=repo_id, filename="onnx/model.onnx") # Fastest CPU: 74.2 ms (88.5 MB FP32); also onnx/model_fp16.onnx (44.4 MB)sess = ort.InferenceSession(onnx_path, providers=["CPUExecutionProvider"])img = Image.new("RGB", (512, 512), color=(128, 128, 128))pixel_values = processor(images=img, return_tensors="np")["pixel_values"].astype(np.float32)logits = sess.run(None, {"pixel_values": pixel_values})[0][0]scaled = logits / 1.0810ex = np.exp(scaled - scaled.max())probs = ex / ex.sum()print(f"cal P(artificial)={probs[0]:.4f} | cal P(human)={probs[1]:.4f}")9 unmodified linesimport { pipeline, RawImage } from "@huggingface/transformers";const detector = await pipeline("image-classification", "Tamarillo/ai-image-forensics-guard-tiny", {dtype: "fp16", // loads 100%-parity 44.4 MB onnx/model_fp16.onnx});// Self-contained 224x224 wiring smoke-test image (replace with an image URL, Blob, or file path)2 unmodified linesconsole.log(results); // [{ label: "artificial", score: ... }, { label: "human", score: ... }]```> Recommended tier for client-side browser WASM (`44.4 MB` FP16 download vs. `88.5 MB` FP32) and `<75 ms` x86 CPU sidecars. *(Note: CPU latency in the ONNX table is measured on 4-thread x86 Xeon where FP16 at `82.42 ms` is slower than FP32 at `74.21 ms` due to x86 FP16 emulation; client-side browser WASM runtime latency was not separately benchmarked.)* For stronger accuracy on 2026 generators, use `Tamarillo/ai-image-forensics-guard-small` (`92.9M`, `224px`, `<100 ms` CPU) or `Tamarillo/ai-image-forensics-guard-base` (`93.2M`, `384px`).---## Label Schema & Calibration ([`calibration.json`](calibration.json))| Class ID | Label | Meaning || :---: | :--- | :--- || `0` | `artificial` | AI-generated / synthetic image (diffusion, flow-matching DiT, GAN, or AI video frame). || `1` | `human` | Authentic human photograph. |- **Validation Calibration (`n=2,380` generator-disjoint val):** Val EER = `1.98%`, Val ROC-AUC = `0.9971`, temperature `T = 1.0810`, calibrated ECE = `0.0079`. Reference validation cutoffs (`5%` FPR at `τ = 0.2495`, `1%` FPR at `τ = 0.7655`) are tighter than unseen wild generators; start at `τ = 0.50` or tune on a small target-domain sample.---## Benchmarks (Identical NVIDIA A100-SXM4-40GB 11-Model Evaluation)All 11 models (3 Tamarillo v2 tiers, 3 Tamarillo v1 tiers, and 5 external Hugging Face incumbents) were evaluated head-to-head on identical frozen RGB images with **zero evaluation images present in training**. Full reproducible v2 scripts are bundled in this repository: [`scripts/synth_bfree_flux_v2.py`](scripts/synth_bfree_flux_v2.py), [`scripts/build_base_cache_v2.py`](scripts/build_base_cache_v2.py), [`scripts/prepare_v2_manifests.py`](scripts/prepare_v2_manifests.py), [`scripts/train_image_v2.py`](scripts/train_image_v2.py), [`scripts/eval_image_suite.py`](scripts/eval_image_suite.py), and [`scripts/export_image_onnx.py`](scripts/export_image_onnx.py). Bold marks the best value in each column.- **Three Explicit Aggregates:**1. **3-Corpus Unique Zero-Touch Mean (`[U3]`):** Equal mean over `ood_openfake_core` (`n=2,000`, `seed=201`), `ood_openfake_reddit` (`n=1,600`, `seed=202`), and `ood_synthbuster` (`n=1,200`, `seed=203`) — **100% disjoint images, real sources, and generators**.2. **4-Suite Zero-Touch Mean (`[Z4]`):** Adds `ood_social_recompressed` (`n=1,700`, `seed=204`: `512px` Bilinear → `JPEG Q45` → `WebP Q55` derived from `OpenFake Core` + `Synthbuster`).3. **5-Suite Public Mean (`[5S]`):** Adds held-out `eval_commfor_comp` (`n=2,000`, `seed=205`, CVPR 2025 `CommunityForensics-Eval`).- **Thresholding Protocol:** EER and ROC-AUC are threshold-free; Fake Recall / Real-Photo FPR in Table 2B use a **fixed `0.50` threshold** (no test-set threshold tuning).### 1. Core 5-Suite Public Benchmark (EER % ↓ and ROC-AUC ↑)| Model | Params | OpenFake Core [Z] | OpenFake Reddit [Z] | Synthbuster [Z] | Social-Recomp [Stress] | CommFor-Eval | 3-Corpus Unique [U3] | 4-Suite [Z4] | 5-Suite Mean [5S] || :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: || **Tamarillo v2 `tiny` (DINOv2-S, 224px)** | 22.1M | 39.30% (0.641) | 28.88% (0.790) | 14.40% (0.926) | 37.12% (0.672) | 26.70% (0.816) | 27.53% / 0.7854 | 29.92% / 0.7571 | 29.28% / 0.7689 || Tamarillo v2 `small` (SigLIP2-B, 224px) | 92.9M | 24.85% (0.831) | 29.44% (0.785) | 10.70% (0.962) | 26.17% (0.822) | 22.10% (0.877) | 21.66% / 0.8589 | 22.79% / 0.8497 | 22.65% / 0.8552 || Tamarillo v2 `base` (SigLIP2-B, 384px) | 93.2M | 21.00% (0.853) | 26.50% (0.802) | 9.55% (0.973) | **20.29%** (0.876) | 20.70% (0.889) | 19.02% / 0.8761 | **19.34%** / 0.8760 | **19.61%** / **0.8786** || Tamarillo v1 `tiny` | 22.1M | 36.05% (0.696) | 30.69% (0.763) | 18.05% (0.903) | 38.36% (0.684) | 29.30% (0.783) | 28.26% / 0.7871 | 30.79% / 0.7612 | 30.49% / 0.7655 || Tamarillo v1 `small` (ConvNeXtV2-T, 384px) | 27.9M | 36.25% (0.688) | 33.31% (0.716) | **9.10%** (0.971) | 30.71% (0.764) | 23.70% (0.857) | 26.22% / 0.7918 | 27.34% / 0.7847 | 26.61% / 0.7993 || Tamarillo v1 `base` | 93.2M | 25.55% (0.805) | 26.75% (0.807) | 9.55% (0.961) | 21.29% (0.867) | 17.60% (0.911) | 20.62% / 0.8580 | 20.79% / 0.8603 | 20.15% / 0.8704 || `haywoodsloan/ai-image-detector-deploy` | 195.2M | **13.15%** (0.931) | **21.56%** (0.882) | 19.05% (0.890) | 26.49% (0.823) | 22.50% (0.839) | **17.92%** / **0.9012** | 20.06% / **0.8815** | 20.55% / 0.8729 || `buildborderless/CommunityForensics-DeepfakeDet-ViT` | 21.8M | 20.55% (0.877) | 33.69% (0.733) | 24.95% (0.812) | 39.95% (0.643) | **9.35%** (0.971) | 26.40% / 0.8072 | 29.78% / 0.7662 | 25.70% / 0.8072 || `Ateeqq/ai-vs-human-image-detector` | 92.9M | 17.05% (0.906) | 21.88% (0.859) | 26.70% (0.812) | 27.29% (0.812) | 42.60% (0.615) | 21.88% / 0.8591 | 23.23% / 0.8475 | 27.10% / 0.8009 || `Organika/sdxl-detector` (`CC-BY-NC-3.0`) | 86.8M | 38.65% (0.653) | 38.62% (0.650) | 27.45% (0.795) | 41.83% (0.624) | 27.20% (0.800) | 34.91% / 0.6995 | 36.64% / 0.6805 | 34.75% / 0.7045 || `umm-maybe/AI-image-detector` | 86.8M | 41.40% (0.628) | 31.75% (0.740) | 38.75% (0.652) | 39.12% (0.649) | 43.20% (0.585) | 37.30% / 0.6733 | 37.76% / 0.6671 | 38.84% / 0.6508 |### 2A. Per-2026-Generator ROC-AUC on `OpenFake Core` (10 Major 2025–2026 Generators)| Model | `illustrious` | `wan-2.5` | `midjourney-7` | `recraft-v3` | `veo-3` | `ernie-turbo` | `z-image-turbo` | `gpt-image-1.5` | `gpt-image-2` | `flux.2-klein-9b` || :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: || **Tamarillo v2 `tiny` (DINOv2-S, 224px)** | 0.797 | 0.837 | 0.760 | 0.732 | 0.812 | 0.760 | 0.700 | 0.583 | 0.433 | 0.300 || Tamarillo v2 `small` (SigLIP2-B, 224px) | 0.929 | 0.952 | 0.877 | 0.868 | 0.879 | 0.888 | 0.897 | 0.811 | 0.706 | 0.615 || Tamarillo v2 `base` (SigLIP2-B, 384px) | 0.958 | 0.973 | 0.910 | 0.915 | 0.900 | 0.902 | 0.922 | 0.878 | 0.734 | 0.589 || Tamarillo v1 `tiny` | 0.825 | 0.847 | 0.748 | 0.719 | 0.851 | 0.800 | 0.746 | 0.676 | 0.504 | 0.439 || Tamarillo v1 `small` (ConvNeXtV2-T, 384px) | 0.868 | 0.919 | 0.826 | 0.747 | 0.739 | 0.793 | 0.745 | 0.681 | 0.642 | 0.330 || Tamarillo v1 `base` | 0.963 | 0.958 | 0.892 | 0.884 | 0.873 | 0.868 | 0.865 | 0.849 | 0.679 | 0.479 || `haywoodsloan/ai-image-detector-deploy` | 0.995 | 0.996 | 0.994 | 0.982 | 0.988 | 0.998 | 0.947 | 0.987 | 0.963 | 0.752 || `buildborderless/CommunityForensics-DeepfakeDet-ViT` | 0.993 | 0.965 | 0.926 | 0.967 | 0.940 | 0.863 | 0.903 | 0.891 | 0.794 | 0.667 || `Ateeqq/ai-vs-human-image-detector` | 0.981 | 0.986 | 0.834 | 0.817 | 0.967 | 0.916 | 0.936 | 0.862 | 0.934 | 0.845 || `Organika/sdxl-detector` (`CC-BY-NC-3.0`) | 0.856 | 0.895 | 0.833 | 0.669 | 0.748 | 0.593 | 0.574 | 0.751 | 0.741 | 0.377 || `umm-maybe/AI-image-detector` | 0.377 | 0.583 | 0.497 | 0.618 | 0.696 | 0.635 | 0.748 | 0.753 | 0.579 | 0.622 |### 2B. Fixed `τ = 0.50` Operating Point (Fake Recall / Real FPR) & Cross-Generator `Shuttle-3` OOD (`n=800`)| Model | OpenFake Core @0.50 (Rec / Real FPR) | Synthbuster @0.50 (Rec / Real FPR) | Social-Recomp @0.50 (Rec / Real FPR) | Shuttle-3 2026 OOD (EER ↓ / AUC ↑)* || :--- | :---: | :---: | :---: | :---: || **Tamarillo v2 `tiny` (DINOv2-S, 224px)** | 43.9% / 20.2% | 59.4% / 2.0% | 59.5% / 33.9% | 0.62% (0.9999) || Tamarillo v2 `small` (SigLIP2-B, 224px) | 59.3% / 8.3% | 62.3% / 0.0% | 71.2% / 23.0% | 1.12% (0.9997) || Tamarillo v2 `base` (SigLIP2-B, 384px) | 46.3% / 3.6% | 61.8% / 0.0% | 73.6% / 14.7% | 0.12% (1.0000) || Tamarillo v1 `tiny` | 41.1% / 15.1% | 44.0% / 1.5% | 56.2% / 30.7% | 2.00% (0.9982) || Tamarillo v1 `small` (ConvNeXtV2-T, 384px) | 32.7% / 6.7% | 49.2% / 0.0% | 53.5% / 19.0% | 1.25% (0.9995) || Tamarillo v1 `base` | 47.2% / 3.3% | 55.8% / 0.0% | 74.1% / 15.7% | 0.62% (0.9996) || `haywoodsloan/ai-image-detector-deploy` | 72.8% / 2.9% | 61.3% / 6.0% | 30.7% / 0.9% | 2.12% (0.9959) || `buildborderless/CommunityForensics-DeepfakeDet-ViT` | 26.2% / 0.0% | 53.0% / 1.5% | 8.1% / 1.1% | 2.75% (0.9980) || `Ateeqq/ai-vs-human-image-detector` | 83.5% / 17.6% | 51.8% / 9.5% | 72.5% / 27.1% | 5.25% (0.9841) || `Organika/sdxl-detector` (`CC-BY-NC-3.0`) | 49.5% / 22.9% | 52.2% / 13.0% | 31.7% / 16.7% | 17.12% (0.9057) || `umm-maybe/AI-image-detector` | 39.5% / 16.5% | 27.5% / 11.0% | 60.1% / 37.7% | 35.00% (0.7196) |*\*Note on `Shuttle-3 2026 OOD` (`n=800` from [`Tamarillo/ai-image-forensics-bfree-2026`](https://huggingface.co/datasets/Tamarillo/ai-image-forensics-bfree-2026)): `shuttleai/shuttle-3-diffusion` is never seen during training, though it shares the 16-ch FLUX.1 architecture family with Tamarillo v2's `FLUX.1-schnell` training subset (and pairs with disjoint commercial COCO photos); it is excluded from `[U3]`, `[Z4]`, and `[5S]` headline aggregates.*---## ONNX Parity & Same-Machine 4-Thread x86 CPU Latency (`bs=1`)Hardware: GCP `a2-highgpu-1g` (Intel Xeon Cascade Lake @ 2.20 GHz, AVX-512, 4 ORT intra-op threads, `bs=1`, median p50 ms over 25 timed runs after 5 warmups). Same-machine incumbent CPU FP32 ONNX baselines:- `umm-maybe/AI-image-detector` (`86.8M`, `224px`): **`139.50 ms`**- `Organika/sdxl-detector` (`86.8M`, `224px`, `CC-BY-NC-3.0`): **`139.23 ms`**- `Ateeqq/ai-vs-human-image-detector` (`92.9M`, `224px`): **`99.24 ms`**- `buildborderless/CommunityForensics-DeepfakeDet-ViT` (`21.8M`, `384px`): **`91.74 ms`**| Artifact | Input Res | File Size | Parity (`n=64` OpenFake Core: Argmax / Max Δp / Mean Δp) | 4-Thread CPU p50 | 4-Thread CPU p90 || :--- | :---: | :---: | :---: | :---: | :---: || `onnx/model.onnx` (FP32) | 224×224 | 88.5 MB | 100.0% / `0.00000` / `0.00000` | **74.21 ms** | 77.90 ms || `onnx/model_fp16.onnx` (FP16) | 224×224 | 44.4 MB | 100.0% / `0.00249` / `0.00032` | 82.42 ms | 84.50 ms |- **Quantization Hygiene:** Dynamic INT8 quantization (`max Δp = 0.293`, `argmax = 96.9%`) failed our strict forensic parity gate (`max Δp ≤ 0.015`, `argmax ≥ 99%`) and was intentionally **withheld**. `Tamarillo/ai-image-forensics-guard-tiny` ships ONLY `100.0%`-argmax-parity FP32 + FP16 ONNX verified across `n=64` held-out `OpenFake Core` images.---## v2 Training Recipe, Ablation Finding & Commercially Permissive Provenance- **Training Strategy:** Direct canonical fine-tuning of `facebook/dinov2-small` (`22.1M`, `224×224`) for 4 epochs with Focal Smooth CE (`gamma=1.0`, `smoothing=0.03`), differential LR (head `5×`), and EMA (`0.996`). (Controlled ablations showed pure supervised training on the full-diffusion corpus outperformed logit distillation from an overconfident `0.59%`-val-EER teacher on unseen `OpenFake Core` generators.)- **Clean/Degraded Forensic Curriculum:** Every training batch applies **35% clean native-scale crops** (zero resize, zero JPEG recompression, preserving subtle 16-ch rectified-flow & VAE decoder micro-artifacts) + **65% symmetric social-media degradation** (identical JPEG Q35–95, WebP Q40–95, double-JPEG, Bilinear/Bicubic/Lanczos downscale, and mild blur/UnsharpMask applied identically to both authentic and synthetic images).- **Key v2 Ablation Finding (Full-Diffusion vs. VAE-Only Reconstructions) & Commercial Filtering:** Controlled ablations on our flagship `base` (`384px`) backbone showed that over-weighting VAE-only self-reconstructions (`B-Free` pairs alone without diffusion denoising) induced a sharpness/blur inversion shortcut on crisp `flux.2-klein-9b` images against modern smartphone `DOCCI` photos. Training v2 exclusively on **high-density full-diffusion generations (`31,531` train / `2,380` val)** — combining `1,400` 1:1 matched Apache-2.0 `unsloth/FLUX.1-schnell` pairs from [`Tamarillo/ai-image-forensics-bfree-2026`](https://huggingface.co/datasets/Tamarillo/ai-image-forensics-bfree-2026), `3,600` 1:1 matched Apache-2.0 `SANA-Sprint` / `SANA-1.5` / `Lumina-Image-2.0` pairs (all paired exclusively with commercial MS-COCO 2017 `train2017` photos strictly filtered to `license ∈ {4, 7, 8}` = `CC-BY-2.0` / Public Domain, excluding all `CC-BY-NC`, `CC-BY-SA`, `CC-BY-ND`, and `val2017`), `12,000` `finedet/openimages` (`CC-BY-2.0/4.0`), and `12,000` `OwensLab/CommunityForensics` (`Systematic + Manual`, `CC-BY-4.0`, `nsfw_flag=False`) — achieved `0.59%` val EER & `19.34%` `[Z4]` EER on `base` (`1.98%` val EER & `29.92%` `[Z4]` EER on this `tiny` tier).---## Honest Limitations & Where Baselines Win1. **Capacity & `224px` DINOv2 Tradeoff:** At `22.1M` (`224×224`), `Tamarillo/ai-image-forensics-guard-tiny` trails our `SigLIP-2` tiers (`Tamarillo v2 small` `22.79%`, `base` `19.34%` Z4 EER) and `8.8×` larger GPU-only `haywoodsloan` (`20.06%` Z4 EER), especially on held-out `flux.2-klein-9b` (`0.300` AUC vs. `Ateeqq` `0.845`) and `gpt-image-2` (`0.433` AUC).2. **`CommunityForensics-Eval` Home-Benchmark Advantage:** `buildborderless/CommunityForensics-DeepfakeDet-ViT` (`9.35%` EER) outperforms Tamarillo on its home `eval_commfor_comp` split (trained on all 2.7M CommunityForensics images vs. Tamarillo's `12K` subsample), while degrading sharply (`39.95%` EER, `8.1%` recall) under `Social-Media Recompressed` stress.3. **Operating-Point Tradeoffs & Forensic Edge Cases:** On clean `OpenFake Core`, default `0.50` is conservative (`43.9%` fake recall at `20.2%` real-photo FPR on `Tamarillo/ai-image-forensics-guard-tiny`), whereas heavy social-media recompression raises real-photo FPR (`33.9%` real FPR at `59.5%` fake recall). Binary whole-image detectors can struggle on **partial AI inpainting / local edits**, **heavily filtered smartphone photos**, **UI screenshots**, and **3D CGI / digital art**. Combine with C2PA credentials, EXIF/metadata forensics, and human review for high-stakes decisions.4. **Honest ONNX Quantization Scope:** Dynamic INT8 quantization drifted beyond our strict forensic parity gate (`max Δp ≤ 0.015`, `argmax ≥ 99%`) and was intentionally omitted; all 3 v2 tiers ship exact-parity `FP32` and `FP16` ONNX (`100.0%` argmax agreement, `max Δp ≤ 0.0025`).---## License & CitationReleased under the **Apache-2.0 License** by **Tamarillo**. All base backbones and filtered training subsets carry commercially permissive licenses (`Apache-2.0`, `CC-BY-2.0`, `CC-BY-4.0`, Public Domain; all MS-COCO 2017 images were strictly filtered to `license ∈ {4, 7, 8}`, excluding all `CC-BY-NC`, `CC-BY-SA`, and `CC-BY-ND` photos).```bibtex@misc{tamarillo_ai_image_forensics_guard_v2_2026,title = {Tamarillo AI-Image Forensics Guard v2: Apache-2.0 Social-Media-Hardened Visual Deepfake Detectors},author = {Tamarillo Open-Model Lab},year = {2026},howpublished = {\url{https://huggingface.co/Tamarillo/ai-image-forensics-guard-tiny}},
12345678910{"temperature": 1.3757,"val_eer": 0.04163,"val_auc": 0.99279,"calibrated_ece_artificial": 0.02489,"thr_val_5pct_fpr": 0.2105,"thr_val_1pct_fpr": 0.723,"id2label": {"0": "artificial","1": "human"12345678910{"temperature": 1.081,"val_eer": 0.01975,"val_auc": 0.9971,"calibrated_ece_artificial": 0.00786,"thr_val_5pct_fpr": 0.2495,"thr_val_1pct_fpr": 0.7655,"id2label": {"0": "artificial","1": "human"
1234545 unmodified lines51525354555657{"_name_or_path": "facebook/dinov2-small","apply_layernorm": true,"architectures": ["Dinov2ForImageClassification"45 unmodified lines"stage12"],"torch_dtype": "float32","transformers_version": "4.49.0","use_mask_token": true,"use_swiglu_ffn": false}123445 unmodified lines50515253545556{"apply_layernorm": true,"architectures": ["Dinov2ForImageClassification"45 unmodified lines"stage12"],"torch_dtype": "float32","transformers_version": "4.51.3","use_mask_token": true,"use_swiglu_ffn": false}
123version https://git-lfs.github.com/spec/v1oid sha256:68c4b9a7c785df84a1063f8c7fdb75811a524f19912cfc892fab14814f83c6d5size 88257824123version https://git-lfs.github.com/spec/v1oid sha256:b28ddf870f1e66cbc41fc6ad2fc931d7824b93c8096824c61197425129fb816csize 88257824
123version https://git-lfs.github.com/spec/v1oid sha256:6e2d9fb000bcbd1552c7cdb719d8e5fdf378a589c7f56ad391808537c6aac832size 88527361123version https://git-lfs.github.com/spec/v1oid sha256:149325acf9d095579bb4ea9e35aa889d4b1ad1d6a97e2d71798c4e98e658a904size 88502982
123version https://git-lfs.github.com/spec/v1oid sha256:4e9b399b1c4a3ffe2aa8eac15e4b87c3949eaa44318aff2b9b09945c35500990size 44387534123456789101112131415161718192021222324252627282930313233343536373839404142{ "model": "/mnt/disks/gcs/runs/tamarillo-lab-v3/outputs/dd82db4643ef/model_tiny_v2", "img_size": 224, "artifacts": { "fp32": { "file": "onnx/model.onnx", "size_mb": 88.5, "parity": { "n_samples": 64, "max_abs_prob_diff": 0.0, "mean_abs_prob_diff": 0.0, "argmax_agreement": 1.0 }, "cpu_bench": { "p50_ms": 74.21, "p90_ms": 77.9, "img_size": 224 } }, "fp16": { "file": "onnx/model_fp16.onnx", "size_mb": 44.39, "parity": { "n_samples": 64, "max_abs_prob_diff": 0.00249, "mean_abs_prob_diff": 0.00032, "argmax_agreement": 1.0 }, "cpu_bench": { "p50_ms": 82.42, "p90_ms": 84.5, "img_size": 224 } } }, "int8_rejected": { "n_samples": 64, "max_abs_prob_diff": 0.29333, "mean_abs_prob_diff": 0.02872, "argmax_agreement": 0.9688 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276"""Family #12 v2 Pre-Cache (runs on cheap CPU node in parallel with A100 synthesis!):Streams strictly commercial real photography (`finedet/openimages` CC-BY-2.0/4.0, n=12,000),diverse multi-generator synthetic images (`OwensLab/CommunityForensics` CC-BY-4.0, n=12,000),and builds the EXACT 5 frozen Public OOD evaluation suites (`ood_openfake_core`, `ood_openfake_reddit`,`ood_synthbuster`, `ood_social_recompressed`, `eval_commfor_comp`) with v1's exact seeds,then archives them to `$OUTPUT_DIR/img_base_cache_v2.tar` so A100 training/eval jobs spend ZERO GPU time streaming!"""
from __future__ import annotations
import argparseimport gcimport jsonimport osimport randomimport tarfileimport timefrom collections import Counterfrom pathlib import Pathfrom typing import Any, Iterator
import pyarrow.parquet as pqfrom huggingface_hub import HfApi, hf_hub_download
from build_image_data import _decode_pil, _save_rgb_jpg, _social_recompress
def iter_parquet_shards_lowmem( repo_id: str, prefix: str, columns: list[str], seed: int, max_per_shard: int | None = None,) -> Iterator[dict[str, Any]]: """Low-RAM streaming parquet iterator (batch_size=32, <500MB peak RAM even on huge image shards!).""" api = HfApi() shards = sorted(f for f in api.list_repo_files(repo_id, repo_type="dataset") if f.startswith(prefix) and f.endswith(".parquet")) rng = random.Random(seed) rng.shuffle(shards) for sh in shards: local_pq = None for attempt in range(3): try: local_pq = hf_hub_download(repo_id=repo_id, filename=sh, repo_type="dataset") break except Exception as e: print(f" [retry {attempt+1}/3] {repo_id}/{sh}: {e}", flush=True) time.sleep(3 * (attempt + 1)) if not local_pq: continue blob_path = Path(os.path.realpath(local_pq)) try: pf = pq.ParquetFile(local_pq) avail = set(pf.schema_arrow.names) use_cols = [c for c in columns if c in avail] rgs = list(range(pf.num_row_groups)) rng.shuffle(rgs) yielded = 0 for rg in rgs: for batch in pf.iter_batches(batch_size=32, row_groups=[rg], columns=use_cols): rows_b = batch.to_pylist() rng.shuffle(rows_b) for r in rows_b: yield r yielded += 1 if max_per_shard is not None and yielded >= max_per_shard: break del rows_b, batch if max_per_shard is not None and yielded >= max_per_shard: break if max_per_shard is not None and yielded >= max_per_shard: break except Exception as e: print(f" [skip shard] {repo_id}/{sh}: {e}", flush=True) finally: gc.collect() try: Path(local_pq).unlink(missing_ok=True) blob_path.unlink(missing_ok=True) except Exception: pass
iter_parquet_shards = iter_parquet_shards_lowmem
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--work-dir", type=str, default="/tmp/img_cache_work") ap.add_argument("--out-tar", type=str, required=True) ap.add_argument("--n-openimages", type=int, default=12000) ap.add_argument("--n-commfor-sys", type=int, default=6500) ap.add_argument("--n-commfor-man", type=int, default=5500) args = ap.parse_args()
os.environ["HF_HOME"] = "/tmp/hf" t0 = time.time() root = Path(args.work_dir) root.mkdir(parents=True, exist_ok=True)
train_rows: list[dict[str, Any]] = [] val_rows: list[dict[str, Any]] = []
print(f"[1/4] Streaming {args.n_openimages} real photos from finedet/openimages (CC-BY)...", flush=True) oi_dir = root / "openimages" oi_rows: list[dict[str, Any]] = [] for row in iter_parquet_shards("finedet/openimages", "data/train-", ["image"], seed=42, max_per_shard=450): im = _decode_pil(row.get("image")) if im is None: continue rel = f"openimages/oi_{len(oi_rows):06d}.jpg" if _save_rgb_jpg(im, root / rel, quality=95): oi_rows.append({"rel": rel, "label": 1, "source": "openimages", "weight": 1.0}) if len(oi_rows) >= args.n_openimages: break n_oi_val = min(700, len(oi_rows) // 10) val_rows.extend(oi_rows[:n_oi_val]) train_rows.extend(oi_rows[n_oi_val:]) print(f" openimages -> saved={len(oi_rows)} (val={n_oi_val}, train={len(oi_rows)-n_oi_val})", flush=True)
print(f"[2/4] Streaming OwensLab/CommunityForensics (Sys={args.n_commfor_sys}, Man={args.n_commfor_man})...", flush=True) cf_rows: list[dict[str, Any]] = [] for sname, pref, quota, mps, sd in [ ("systematic", "data/systematic/", args.n_commfor_sys, 2000, 51), ("manual", "data/manual/", args.n_commfor_man, 1750, 52), ]: got = 0 for row in iter_parquet_shards("OwensLab/CommunityForensics", pref, ["image_data", "model_name", "nsfw_flag", "split"], seed=sd, max_per_shard=mps): nsfw = row.get("nsfw_flag") if nsfw is True or str(nsfw).lower() == "true": continue if str(row.get("split", "train")).lower() == "test": continue im = _decode_pil(row.get("image_data")) if im is None: continue mname = str(row.get("model_name", "unknown")) rel = f"commfor_train/cf_{sname}_{got:06d}.jpg" if _save_rgb_jpg(im, root / rel, quality=95): cf_rows.append({"rel": rel, "label": 0, "source": f"commfor_{sname}", "generator": mname, "weight": 1.0}) got += 1 if got >= quota: break print(f" commfor {sname} -> saved={got}", flush=True)
cf_by_model: dict[str, list[dict[str, Any]]] = {} for r in cf_rows: cf_by_model.setdefault(r.get("generator", "unk"), []).append(r) mkeys = list(cf_by_model.keys()) random.Random(53).shuffle(mkeys) cf_val, cf_tr = [], [] for mk in mkeys: if len(cf_val) < 700: cf_val.extend(cf_by_model[mk]) else: cf_tr.extend(cf_by_model[mk]) val_rows.extend(cf_val[:700]) train_rows.extend(cf_tr) print(f" commfor -> distinct_models={len(cf_by_model)} | val_unseen_gens={len(cf_val[:700])}, train={len(cf_tr)}", flush=True)
(root / "base_train.jsonl").write_text("\n".join(json.dumps(r) for r in train_rows) + "\n", encoding="utf-8") (root / "base_val.jsonl").write_text("\n".join(json.dumps(r) for r in val_rows) + "\n", encoding="utf-8")
# 3. Frozen 5-Suite Public OOD Eval Cache (exact same seeds & quotas as v1!) ood_root = root / "ood" ood_root.mkdir(parents=True, exist_ok=True) ood_suites: dict[str, list[dict[str, Any]]] = {}
print("[3/4] Building frozen ood_openfake_core, ood_openfake_reddit, ood_synthbuster, eval_commfor_comp...", flush=True) for sname, pref, n_per, sd in [ ("ood_openfake_core", "core/test-", 1000, 201), ("ood_openfake_reddit", "reddit/test-", 800, 202), ]: real_l, fake_l = [], [] for row in iter_parquet_shards("ComplexDataLab/OpenFake", pref, ["image", "label", "model", "type", "release_date"], seed=sd, max_per_shard=None): raw_lbl = str(row.get("label", "")).strip().lower() is_real = raw_lbl in ("real", "human", "0") if raw_lbl in ("real", "human") else (raw_lbl != "fake" and raw_lbl != "artificial") lbl = 1 if is_real else 0 if lbl == 1 and len(real_l) >= n_per: continue if lbl == 0 and len(fake_l) >= n_per: continue im = _decode_pil(row.get("image")) if im is None: continue idx = len(real_l) if lbl == 1 else len(fake_l) rel = f"ood/{sname}/{'real' if lbl == 1 else 'fake'}_{idx:05d}.jpg" if not _save_rgb_jpg(im, root / rel, quality=95): continue rec = {"rel": rel, "label": lbl, "model": str(row.get("model", "unknown")), "media_type": str(row.get("type", "image"))} (real_l if lbl == 1 else fake_l).append(rec) if len(real_l) >= n_per and len(fake_l) >= n_per: break comb = real_l + fake_l random.Random(sd).shuffle(comb) ood_suites[sname] = comb print(f" {sname}: real={len(real_l)}, fake={len(fake_l)}", flush=True)
sb_real, sb_fake = [], [] for row in iter_parquet_shards("marco-willi/synthbuster-plus", "data/test-", ["image", "label", "source", "ds_name"], seed=203): lbl = 1 if int(row["label"]) == 0 else 0 if lbl == 1 and len(sb_real) >= 1000: continue if lbl == 0 and len(sb_fake) >= 1000: continue im = _decode_pil(row.get("image")) if im is None: continue idx = len(sb_real) if lbl == 1 else len(sb_fake) rel = f"ood/ood_synthbuster/{'real' if lbl == 1 else 'fake'}_{idx:05d}.jpg" if not _save_rgb_jpg(im, root / rel, quality=95): continue rec = {"rel": rel, "label": lbl, "model": str(row.get("source") or row.get("ds_name") or "unknown")} (sb_real if lbl == 1 else sb_fake).append(rec) if len(sb_real) >= 1000 and len(sb_fake) >= 1000: break sb_all = sb_real + sb_fake random.Random(203).shuffle(sb_all) ood_suites["ood_synthbuster"] = sb_all print(f" ood_synthbuster: real={len(sb_real)}, fake={len(sb_fake)}", flush=True)
ce_real, ce_fake = [], [] for row in iter_parquet_shards("OwensLab/CommunityForensics-Eval", "data/CompEval-", ["image_data", "label", "model_name", "real_source"], seed=205, max_per_shard=60): lbl = 1 if int(row["label"]) == 0 else 0 if lbl == 1 and len(ce_real) >= 1000: continue if lbl == 0 and len(ce_fake) >= 1000: continue im = _decode_pil(row.get("image_data")) if im is None: continue idx = len(ce_real) if lbl == 1 else len(ce_fake) rel = f"ood/eval_commfor_comp/{'real' if lbl == 1 else 'fake'}_{idx:05d}.jpg" if not _save_rgb_jpg(im, root / rel, quality=95): continue rec = {"rel": rel, "label": lbl, "model": str(row.get("model_name", "unknown"))} (ce_real if lbl == 1 else ce_fake).append(rec) if len(ce_real) >= 1000 and len(ce_fake) >= 1000: break ce_all = ce_real + ce_fake random.Random(205).shuffle(ce_all) ood_suites["eval_commfor_comp"] = ce_all print(f" eval_commfor_comp: real={len(ce_real)}, fake={len(ce_fake)}", flush=True)
print("[4/4] Building ood_social_recompressed & archiving to tar...", flush=True) sr_rows: list[dict[str, Any]] = [] for base_name, pool in [("openfake", ood_suites["ood_openfake_core"]), ("synthbuster", ood_suites["ood_synthbuster"])]: reals = [r for r in pool if r["label"] == 1][:500] fakes = [r for r in pool if r["label"] == 0][:500] for j, r in enumerate(reals + fakes): rel = f"ood/ood_social_recompressed/{base_name}_{'real' if r['label'] == 1 else 'fake'}_{j:04d}.jpg" if _social_recompress(root / r["rel"], root / rel): sr_rows.append({"rel": rel, "label": r["label"], "model": r.get("model", "unknown"), "origin": base_name}) random.Random(204).shuffle(sr_rows) ood_suites["ood_social_recompressed"] = sr_rows
for sname, srows in ood_suites.items(): (ood_root / f"{sname}.jsonl").write_text("\n".join(json.dumps(r) for r in srows) + "\n", encoding="utf-8")
out_tar = Path(args.out_tar) out_tar.parent.mkdir(parents=True, exist_ok=True) with tarfile.open(out_tar, "w") as tf: tf.add(root, arcname=".") summary = { "base_train_n": len(train_rows), "base_val_n": len(val_rows), "ood_counts": {k: len(v) for k, v in ood_suites.items()}, "tar_mb": round(out_tar.stat().st_size / 1e6, 2), "elapsed_min": round((time.time() - t0) / 60.0, 2), } (out_tar.parent / "base_cache_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") print(f"[DONE] Base cache complete: {json.dumps(summary, indent=2)}", flush=True)
if __name__ == "__main__": main()99 unmodified lines10010110210310410510610710810911011199 unmodified linesdef score_hf_classifier(model_id_or_dir: str, paths: list[str], device: torch.device, bs: int = 32) -> tuple[np.ndarray, float]:proc = AutoImageProcessor.from_pretrained(model_id_or_dir)model = AutoModelForImageClassification.from_pretrained(model_id_or_dir).to(device).eval()params_m = sum(p.numel() for p in model.parameters()) / 1e6art_idx = _detect_artificial_index(model.config.id2label)print(f" [hf] {model_id_or_dir}: {params_m:.2f}M | id2label={model.config.id2label} -> art_idx={art_idx}", flush=True)scores = []with torch.no_grad(), torch.amp.autocast("cuda", dtype=torch.bfloat16):for i in range(0, len(paths), bs):ims = [Image.open(p).convert("RGB") for p in paths[i : i + bs]]enc = proc(images=ims, return_tensors="pt").to(device)99 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312499 unmodified linesdef score_hf_classifier(model_id_or_dir: str, paths: list[str], device: torch.device, bs: int = 32) -> tuple[np.ndarray, float]:proc = AutoImageProcessor.from_pretrained(model_id_or_dir)model = AutoModelForImageClassification.from_pretrained(model_id_or_dir).to(device).eval()for _m in model.modules():if _m.__class__.__name__ == "ConvNextV2GRN":_cls = _m.__class__def _grn_fast(self, hidden_states):x = hidden_states.float()gx = torch.linalg.vector_norm(x, ord=2, dim=(1, 2), keepdim=True)nx = gx / (gx.mean(dim=-1, keepdim=True) + 1e-6)w = self.weight if hasattr(self, "weight") else self.gammab = self.bias if hasattr(self, "bias") else self.betareturn (w.float() * (x * nx) + b.float() + x).to(hidden_states.dtype)_cls.forward = _grn_fastbreakparams_m = sum(p.numel() for p in model.parameters()) / 1e6art_idx = _detect_artificial_index(model.config.id2label)print(f" [hf] {model_id_or_dir}: {params_m:.2f}M | id2label={model.config.id2label} -> art_idx={art_idx}", flush=True)use_bf16 = getattr(model.config, "model_type", "").lower() != "convnextv2"scores = []with torch.no_grad(), torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):for i in range(0, len(paths), bs):ims = [Image.open(p).convert("RGB") for p in paths[i : i + bs]]enc = proc(images=ims, return_tensors="pt").to(device)
25 unmodified lines262728293031323334353662 unmodified lines9910010110210310410540 unmodified lines14614714814915015115215315415515615715815925 unmodified linesdef __init__(self, model: torch.nn.Module) -> None:super().__init__()self.model = modeldef forward(self, pixel_values: torch.Tensor) -> torch.Tensor:return self.model(pixel_values=pixel_values).logitsdef _softmax(z: np.ndarray) -> np.ndarray:m = z.max(axis=-1, keepdims=True)e = np.exp(z - m)62 unmodified linesonnx_dir.mkdir(parents=True, exist_ok=True)proc = AutoImageProcessor.from_pretrained(target)model = AutoModelForImageClassification.from_pretrained(target).eval().cpu()wrapper = VisionOnnxWrapper(model).eval()# Load 64 balanced real/fake validation images for rigorous parity verification40 unmodified linesprint(f"[onnx] {target} FP32 ({res['artifacts']['fp32']['size_mb']} MB): parity={p32} bench={b32}", flush=True)if not args.baseline_repo:# 1. FP16 ONNX (half file size, near-zero diff — keep_io_types=True, parity-gated <= 0.015!)fp16_path = onnx_dir / "model_fp16.onnx"try:import onnxfrom onnxconverter_common import float16m_onnx = onnx.load(str(fp32_path))m_fp16 = float16.convert_float_to_float16(m_onnx, keep_io_types=True)onnx.save(m_fp16, str(fp16_path))p16 = verify_parity(model, fp16_path, tensors)if p16["max_abs_prob_diff"] <= 0.015 and p16["argmax_agreement"] >= 0.98:b16 = bench_cpu_onnx(fp16_path, args.img_size)25 unmodified lines2627282930313233343536373839404142434445464748495051525354555657585962 unmodified lines12212312412512612712812913013140 unmodified lines17217317417517617717817918018118218318418518618718818919019119219319419519619719819925 unmodified linesdef __init__(self, model: torch.nn.Module) -> None:super().__init__()self.model = modelfor _m in self.model.modules():if _m.__class__.__name__ == "ConvNextV2GRN":_cls = _m.__class__def _grn_fast(self, hidden_states):x = hidden_states.float()gx = torch.sqrt((x * x).sum(dim=(1, 2), keepdim=True) + 1e-12)nx = gx / (gx.mean(dim=-1, keepdim=True) + 1e-6)w = self.weight if hasattr(self, "weight") else self.gammab = self.bias if hasattr(self, "bias") else self.betareturn (w.float() * (x * nx) + b.float() + x).to(hidden_states.dtype)_cls.forward = _grn_fastbreakdef forward(self, pixel_values: torch.Tensor) -> torch.Tensor:return self.model(pixel_values=pixel_values).logitsclass VisionFp16OnnxWrapper(torch.nn.Module):"""Native PyTorch FP16 exporter with FP32 I/O casts (zero onnxconverter_common graph type mismatches!)."""def __init__(self, model: torch.nn.Module) -> None:super().__init__()self.model = model.half()def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:return self.model(pixel_values=pixel_values.half()).logits.float()def _softmax(z: np.ndarray) -> np.ndarray:m = z.max(axis=-1, keepdims=True)e = np.exp(z - m)62 unmodified linesonnx_dir.mkdir(parents=True, exist_ok=True)proc = AutoImageProcessor.from_pretrained(target)try:model = AutoModelForImageClassification.from_pretrained(target, attn_implementation="eager").eval().cpu()except (TypeError, ValueError):model = AutoModelForImageClassification.from_pretrained(target).eval().cpu()wrapper = VisionOnnxWrapper(model).eval()# Load 64 balanced real/fake validation images for rigorous parity verification40 unmodified linesprint(f"[onnx] {target} FP32 ({res['artifacts']['fp32']['size_mb']} MB): parity={p32} bench={b32}", flush=True)if not args.baseline_repo:# 1. Native PyTorch FP16 ONNX (half file size, FP32 I/O casts, zero graph-rewriter mismatches!)fp16_path = onnx_dir / "model_fp16.onnx"try:import copyfp16_dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")m_half = copy.deepcopy(model).to(fp16_dev).eval()w16 = VisionFp16OnnxWrapper(m_half).to(fp16_dev).eval()d16 = torch.randn(1, 3, args.img_size, args.img_size, dtype=torch.float32, device=fp16_dev)with torch.no_grad():torch.onnx.export(w16,(d16,),str(fp16_path),input_names=["pixel_values"],output_names=["logits"],dynamic_axes={"pixel_values": {0: "batch_size"}, "logits": {0: "batch_size"}},opset_version=17,do_constant_folding=True,)del w16, m_half, d16if torch.cuda.is_available():torch.cuda.empty_cache()p16 = verify_parity(model, fp16_path, tensors)if p16["max_abs_prob_diff"] <= 0.015 and p16["argmax_agreement"] >= 0.98:b16 = bench_cpu_onnx(fp16_path, args.img_size)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Merge cached v2 image archives on GPU VM local SSD (/tmp/img_v2_work) in ~15 seconds: 1. img_base_cache_v2.tar (12,000 openimages + 12,000 CommunityForensics + 5 frozen Public OOD suites) 2. matched_2026_pairs.tar (8,000 v1 1:1 COCO + SANA-Sprint/SANA-1.5/Lumina-2.0/SSD-1B pairs) 3. bfree_flux_v2.tar (6,000 B-Free Multi-VAE pairs + 1,800 FLUX.1-schnell pairs + 600 Shuttle-3 OOD pairs)Strictly keeps `ood_shuttle3_test` (Shuttle-3) OUT of train/val and writes it as a 6th OOD eval suite!"""
from __future__ import annotations
import argparseimport jsonimport randomimport tarfileimport timefrom collections import Counterfrom pathlib import Pathfrom typing import Any
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--base-cache-tar", type=str, required=True) ap.add_argument("--extra-cache-tar", type=str, default="") ap.add_argument("--v1-pairs-tar", type=str, required=True) ap.add_argument("--v2-bfree-tar", type=str, required=True) ap.add_argument("--bfree-max-per-vae", type=int, default=0, help="0 = exclude B-Free VAE-only reconstructions (full-diffusion only!)") ap.add_argument("--out-dir", type=str, default="/tmp/img_v2_work") args = ap.parse_args()
t0 = time.time() root = Path(args.out_dir) root.mkdir(parents=True, exist_ok=True)
# 1. Extract base cache (openimages + commfor + 5 frozen OOD suites) base_dir = root / "base_cache" base_dir.mkdir(parents=True, exist_ok=True) print(f"[merge 1/3] Extracting {args.base_cache_tar}...", flush=True) with tarfile.open(args.base_cache_tar, "r") as tf: tf.extractall(base_dir)
train_rows: list[dict[str, Any]] = [] val_rows: list[dict[str, Any]] = [] for r in (json.loads(l) for l in (base_dir / "base_train.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()): train_rows.append({**r, "path": str(base_dir / r["rel"])}) for r in (json.loads(l) for l in (base_dir / "base_val.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()): val_rows.append({**r, "path": str(base_dir / r["rel"])})
# Rewrite OOD manifests with absolute paths ood_out = root / "ood" ood_out.mkdir(parents=True, exist_ok=True) for jp in sorted((base_dir / "ood").glob("*.jsonl")): fixed = [] for r in (json.loads(l) for l in jp.read_text(encoding="utf-8").splitlines() if l.strip()): fixed.append({**r, "path": str(base_dir / r["rel"])}) (ood_out / jp.name).write_text("\n".join(json.dumps(x) for x in fixed) + "\n", encoding="utf-8")
# Optional 1B: Extract extra full-diffusion cache (+24K openimages + 24K CommunityForensics across 100+ shards!) if args.extra_cache_tar and Path(args.extra_cache_tar).exists(): ex_dir = root / "extra_cache" ex_dir.mkdir(parents=True, exist_ok=True) print(f"[merge 1B] Extracting {args.extra_cache_tar}...", flush=True) with tarfile.open(args.extra_cache_tar, "r") as tf: tf.extractall(ex_dir) for r in (json.loads(l) for l in (ex_dir / "extra_train.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()): train_rows.append({**r, "path": str(ex_dir / r["rel"])}) for r in (json.loads(l) for l in (ex_dir / "extra_val.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()): val_rows.append({**r, "path": str(ex_dir / r["rel"])})
# 2. Extract v1 matched_2026_pairs.tar (SANA-Sprint, SANA-1.5, Lumina-2.0, SSD-1B) v1_dir = root / "matched_v1" v1_dir.mkdir(parents=True, exist_ok=True) print(f"[merge 2/3] Extracting {args.v1_pairs_tar}...", flush=True) with tarfile.open(args.v1_pairs_tar, "r") as tf: tf.extractall(v1_dir) v1_man = [json.loads(l) for l in (v1_dir / "manifest.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()] random.Random(42).shuffle(v1_man) by_g1: dict[str, list[dict[str, Any]]] = {} for r in v1_man: by_g1.setdefault(r["generator"], []).append(r) for gname, grows in sorted(by_g1.items()): n_val = min(120, len(grows) // 8) for idx, r in enumerate(grows): tgt = val_rows if idx < n_val else train_rows tgt.append({"path": str(v1_dir / r["real_rel"]), "label": 1, "source": f"coco_v1_{gname}", "weight": 2.0}) tgt.append({"path": str(v1_dir / r["fake_rel"]), "label": 0, "source": f"gen_v1_{gname}", "weight": 2.0})
# 3. Extract v2 bfree_flux_v2.tar (6,000 B-Free Multi-VAE + 1,800 FLUX.1-schnell + 600 Shuttle-3 OOD) v2_dir = root / "bfree_v2" v2_dir.mkdir(parents=True, exist_ok=True) print(f"[merge 3/3] Extracting {args.v2_bfree_tar}...", flush=True) with tarfile.open(args.v2_bfree_tar, "r") as tf: tf.extractall(v2_dir) v2_man = [json.loads(l) for l in (v2_dir / "manifest.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()] random.Random(2026).shuffle(v2_man)
shuttle_ood: list[dict[str, Any]] = [] by_g2: dict[str, list[dict[str, Any]]] = {} for r in v2_man: if r.get("split") == "ood_shuttle3_test": shuttle_ood.append({"path": str(v2_dir / r["real_rel"]), "label": 1, "model": "coco_real"}) shuttle_ood.append({"path": str(v2_dir / r["fake_rel"]), "label": 0, "model": "shuttle-3-diffusion"}) else: by_g2.setdefault(r["generator"], []).append(r)
for gname, grows in sorted(by_g2.items()): is_bfree = gname.startswith("bfree_") if is_bfree: if args.bfree_max_per_vae <= 0: continue grows = grows[: args.bfree_max_per_vae] n_val = min(150, len(grows) // 8) w = 2.5 if gname == "flux1_schnell" else 1.0 for idx, r in enumerate(grows): tgt = val_rows if idx < n_val else train_rows tgt.append({"path": str(v2_dir / r["real_rel"]), "label": 1, "source": f"coco_v2_{gname}", "weight": w}) tgt.append({"path": str(v2_dir / r["fake_rel"]), "label": 0, "source": f"v2_{gname}", "weight": w})
random.Random(2026).shuffle(shuttle_ood) (ood_out / "ood_shuttle3_2026.jsonl").write_text("\n".join(json.dumps(x) for x in shuttle_ood) + "\n", encoding="utf-8")
random.Random(2026).shuffle(train_rows) random.Random(2027).shuffle(val_rows) (root / "train.jsonl").write_text("\n".join(json.dumps(x) for x in train_rows) + "\n", encoding="utf-8") (root / "val.jsonl").write_text("\n".join(json.dumps(x) for x in val_rows) + "\n", encoding="utf-8")
summary = { "train_n": len(train_rows), "train_by_label": dict(Counter(r["label"] for r in train_rows)), "train_by_source": dict(Counter(r["source"] for r in train_rows)), "val_n": len(val_rows), "val_by_label": dict(Counter(r["label"] for r in val_rows)), "shuttle3_ood_n": len(shuttle_ood), "elapsed_s": round(time.time() - t0, 1), } (root / "v2_merge_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") print(f"[DONE] Merged v2 manifests in {summary['elapsed_s']}s: {json.dumps(summary, indent=2)}", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494"""Family #12 v2 Step 1: Synthesize Tamarillo/ai-image-forensics-bfree-2026 (10th Open Apache-2.0 Dataset)& v2 training archive ($OUTPUT_DIR/bfree_flux_v2.tar) on strictly commercial COCO-2017 train2017 photos(license in {4, 7, 8}: CC-BY-2.0 / Public Domain, disjoint from v1's matched_2026_pairs.tar image_ids!).
100% OpenFake- & Synthbuster-Disjoint Apache-2.0 / MIT Sources: Part A — B-Free (CVPR 2025) Multi-VAE Self-Conditioned Reconstructions (6,000 real -> VAE pairs, ZERO semantic bias!): 1. unsloth/FLUX.1-schnell (subfolder='vae', 16-ch AutoencoderKL, Apache-2.0) : 2,400 pairs 2. mit-han-lab/dc-ae-f32c32-sana-1.1-diffusers (32-ch AutoencoderDC, MIT) : 1,400 pairs 3. Alpha-VLLM/Lumina-Image-2.0 (subfolder='vae', 16-ch AutoencoderKL, Apache-2.0) : 1,200 pairs 4. madebyollin/sdxl-vae-fp16-fix (4-ch AutoencoderKL, MIT) : 1,000 pairs Part B — Full-Diffusion 1:1 Caption- & Aspect-Matched Apache-2.0 Rectified-Flow DiT Fakes (2,400 pairs): 5. unsloth/FLUX.1-schnell (4-step 16-ch DiT, Apache-2.0, TRAIN) : 1,800 pairs 6. shuttleai/shuttle-3-diffusion (4-step 16-ch DiT, Apache-2.0, CROSS-GEN OOD TEST ONLY) : 600 pairs
Outputs: 1. $OUTPUT_DIR/bfree_flux_v2.tar (for v2 model training & OOD Shuttle-3 eval) 2. $OUTPUT_DIR/hf_dataset_parquet/ (compact Parquet shards with embedded JPEG bytes for HF Hub!) 3. $OUTPUT_DIR/synth_v2_summary.json"""
from __future__ import annotations
import argparseimport gcimport ioimport jsonimport osimport randomimport shutilimport tarfileimport timefrom collections import Counterfrom pathlib import Pathfrom typing import Any
import numpy as npimport pyarrow as paimport pyarrow.parquet as pqimport torchfrom diffusers import AutoencoderDC, AutoencoderKL, FluxPipelinefrom huggingface_hub import HfApi, hf_hub_downloadfrom PIL import Image
Image.MAX_IMAGE_PIXELS = NoneCOMMERCIAL_COCO_LICENSES = {4, 7, 8}
STYLE_PREFIXES = [ "", "", "", "", "", "candid smartphone photograph of ", "natural daylight photo, ", "casual handheld camera shot of ", "documentary photograph of ", "slightly grainy film photo of ",]
def _bucket_for_aspect(w: int, h: int) -> tuple[str, int, int]: ratio = w / max(h, 1) if ratio >= 1.18: return "land", 768, 512 if ratio <= 0.85: return "port", 512, 768 return "sq", 640, 640
def _decode_pil_bytes(val: Any) -> Image.Image | None: if isinstance(val, Image.Image): return val if isinstance(val, dict) and val.get("bytes"): return Image.open(io.BytesIO(val["bytes"])) if isinstance(val, (bytes, bytearray)): return Image.open(io.BytesIO(val)) return None
def load_excluded_coco_ids(prev_tar: str) -> set[int]: if not prev_tar or not Path(prev_tar).exists(): return set() ids: set[int] = set() with tarfile.open(prev_tar, "r") as tf: f = tf.extractfile("manifest.jsonl") if f is not None: for line in f.read().decode("utf-8").splitlines(): if line.strip(): ids.add(int(json.loads(line)["image_id"])) print(f"[exclude] Loaded {len(ids)} COCO image_ids from {prev_tar} to guarantee strict disjointness", flush=True) return ids
def collect_commercial_coco(work_dir: Path, n_total: int, exclude_ids: set[int], seed: int = 2026) -> list[dict[str, Any]]: t0 = time.time() repo = "srishti-kaushik/COCO-2017" cap_pq = hf_hub_download(repo_id=repo, filename="data/captions/train2017/train2017.parquet", repo_type="dataset") tbl = pq.read_table(cap_pq, columns=["image_id", "license", "width", "height", "captions"]) cap_map: dict[int, dict[str, Any]] = {} for row in tbl.to_pylist(): iid = int(row["image_id"]) if iid in exclude_ids: continue lic = int(row.get("license", -1)) if lic not in COMMERCIAL_COCO_LICENSES: continue caps = row.get("captions") or [] if not caps: continue first_cap = caps[0]["caption"] if isinstance(caps[0], dict) else str(caps[0]) first_cap = " ".join(first_cap.strip().split()) if len(first_cap) < 12: continue w, h = int(row.get("width", 640)), int(row.get("height", 480)) cap_map[iid] = {"image_id": iid, "license": lic, "width": w, "height": h, "caption": first_cap}
all_ids = list(cap_map.keys()) rng = random.Random(seed) rng.shuffle(all_ids) target_ids = set(all_ids[: int(n_total * 1.25)]) print(f"[coco] Found {len(cap_map)} disjoint commercial captions; targeting {len(target_ids)} IDs ({time.time()-t0:.1f}s)...", flush=True)
api = HfApi() img_shards = sorted(f for f in api.list_repo_files(repo, repo_type="dataset") if f.startswith("data/images/train2017/") and f.endswith(".parquet")) rng.shuffle(img_shards)
real_dir = work_dir / "real_coco" real_dir.mkdir(parents=True, exist_ok=True) matched: list[dict[str, Any]] = [] seen_ids: set[int] = set()
for sh in img_shards: local_pq = hf_hub_download(repo_id=repo, filename=sh, repo_type="dataset") blob = Path(os.path.realpath(local_pq)) try: pf = pq.ParquetFile(local_pq) for batch in pf.iter_batches(batch_size=256, columns=["image_id", "image"]): d = batch.to_pydict() for iid_raw, img_raw in zip(d["image_id"], d["image"]): iid = int(iid_raw) if iid not in target_ids or iid in seen_ids: continue im = _decode_pil_bytes(img_raw) if im is None: continue try: rgb = im.convert("RGB") if min(rgb.size) < 256: continue w, h = rgb.size # Resize cleanly to multiple of 32px in [512, 768] so real & VAE reconstruction have exact pixel geometry! _, tw, th = _bucket_for_aspect(w, h) rgb_fit = rgb.resize((tw, th), Image.Resampling.LANCZOS) rel = f"real_coco/coco_{iid}.jpg" rgb_fit.save(work_dir / rel, format="JPEG", quality=95) info = cap_map[iid] matched.append({ "image_id": iid, "coco_license": info["license"], "caption": info["caption"], "real_rel": rel, "width": tw, "height": th, }) seen_ids.add(iid) if len(matched) >= n_total: break except Exception: continue if len(matched) >= n_total: break finally: try: Path(local_pq).unlink(missing_ok=True) blob.unlink(missing_ok=True) except Exception: pass if len(matched) >= n_total: break
print(f"[coco] Collected {len(matched)} disjoint commercial real photos in {time.time()-t0:.1f}s", flush=True) return matched
def run_bfree_vae_reconstructions( work_dir: Path, items: list[dict[str, Any]], gen_name: str, repo_id: str, subfolder: str | None, is_dc: bool, device: torch.device, batch_size: int = 8,) -> list[dict[str, Any]]: """B-Free (CVPR 2025) self-conditioned VAE reconstruction of real photos.""" t0 = time.time() print(f"\n[bfree-vae] {gen_name} ({repo_id} subfolder={subfolder}) | n={len(items)}...", flush=True) cls = AutoencoderDC if is_dc else AutoencoderKL kwargs: dict[str, Any] = {"torch_dtype": torch.bfloat16} if subfolder: kwargs["subfolder"] = subfolder vae = cls.from_pretrained(repo_id, **kwargs).to(device).eval()
# Group by (width, height) so we can batch cleanly at full native pixel geometry! by_shape: dict[tuple[int, int], list[dict[str, Any]]] = {} for it in items: by_shape.setdefault((it["width"], it["height"]), []).append(it)
out_sub = work_dir / f"fake_{gen_name}" out_sub.mkdir(parents=True, exist_ok=True) records: list[dict[str, Any]] = []
with torch.no_grad(): for (tw, th), grp in sorted(by_shape.items()): for i in range(0, len(grp), batch_size): chunk = grp[i : i + batch_size] arrs = [] for it in chunk: im = Image.open(work_dir / it["real_rel"]).convert("RGB") if im.size != (tw, th): im = im.resize((tw, th), Image.Resampling.LANCZOS) a = (np.asarray(im, dtype=np.float32) / 127.5) - 1.0 arrs.append(np.transpose(a, (2, 0, 1))) x = torch.from_numpy(np.stack(arrs, axis=0)).to(device=device, dtype=torch.bfloat16) enc = vae.encode(x) z = enc.latent_dist.sample() if hasattr(enc, "latent_dist") else enc.latent dec = vae.decode(z) rec_t = dec.sample if hasattr(dec, "sample") else dec[0] rec_np = ((rec_t.float().clamp(-1.0, 1.0) + 1.0) * 127.5).round().byte().permute(0, 2, 3, 1).cpu().numpy() for it, rimg in zip(chunk, rec_np): rel = f"fake_{gen_name}/{gen_name}_{it['image_id']}.jpg" Image.fromarray(rimg).save(work_dir / rel, format="JPEG", quality=95) records.append({ **it, "generator": gen_name, "model_id": repo_id, "synthesis_kind": "bfree_vae_reconstruction", "split": "train", "fake_rel": rel, }) if len(records) % 400 < batch_size: print(f" [{gen_name}] {len(records)}/{len(items)} ({time.time()-t0:.1f}s)", flush=True)
del vae gc.collect() torch.cuda.empty_cache() print(f"[bfree-vae] {gen_name} DONE: {len(records)} pairs in {time.time()-t0:.1f}s", flush=True) return records
def run_flux_generator( work_dir: Path, items: list[dict[str, Any]], gen_name: str, repo_id: str, split_name: str, batch_size: int = 4, num_steps: int = 4, seed: int = 2026,) -> list[dict[str, Any]]: t0 = time.time() device = torch.device("cuda") print(f"\n[flux-gen] {gen_name} ({repo_id}) | n={len(items)} split={split_name} bs={batch_size} steps={num_steps} (zero-offload pre-encoded prompts)...", flush=True) pipe = FluxPipeline.from_pretrained(repo_id, torch_dtype=torch.bfloat16) pipe.set_progress_bar_config(disable=True)
# 1. Pre-encode ALL prompts on GPU with CLIP-L + T5-XXL (~15s), then free text encoders completely! rng = random.Random(seed) prompts_all = [rng.choice(STYLE_PREFIXES) + it["caption"] for it in items] pipe.text_encoder.to(device) pipe.text_encoder_2.to(device) pe_list: list[torch.Tensor] = [] ppe_list: list[torch.Tensor] = [] with torch.no_grad(): for i in range(0, len(prompts_all), 32): sub = prompts_all[i : i + 32] pe, ppe, _ = pipe.encode_prompt( prompt=sub, prompt_2=sub, device=device, max_sequence_length=256, ) pe_list.append(pe.cpu()) ppe_list.append(ppe.cpu()) pe_all = torch.cat(pe_list, dim=0) ppe_all = torch.cat(ppe_list, dim=0) del pe_list, ppe_list pipe.text_encoder.to("cpu") pipe.text_encoder_2.to("cpu") del pipe.text_encoder, pipe.text_encoder_2 pipe.text_encoder = None pipe.text_encoder_2 = None gc.collect() torch.cuda.empty_cache() print(f" [{gen_name}] Pre-encoded {len(prompts_all)} prompts in {time.time()-t0:.1f}s; moving transformer+VAE permanently to CUDA...", flush=True)
# 2. Keep transformer (~24GB) + VAE (~0.2GB) permanently resident on A100-40GB -> ~10x faster than CPU offload! pipe.transformer.to(device) pipe.vae.to(device)
by_shape: dict[tuple[int, int], list[int]] = {} for idx, it in enumerate(items): by_shape.setdefault((it["width"], it["height"]), []).append(idx)
out_sub = work_dir / f"fake_{gen_name}" out_sub.mkdir(parents=True, exist_ok=True) records: list[dict[str, Any]] = [] t_gen = time.time()
with torch.no_grad(): for (tw, th), idx_grp in sorted(by_shape.items()): for i in range(0, len(idx_grp), batch_size): c_idx = idx_grp[i : i + batch_size] pe_b = pe_all[c_idx].to(device=device, dtype=torch.bfloat16) ppe_b = ppe_all[c_idx].to(device=device, dtype=torch.bfloat16) gens = [torch.Generator(device=device).manual_seed(seed + int(items[j]["image_id"])) for j in c_idx] out = pipe( prompt_embeds=pe_b, pooled_prompt_embeds=ppe_b, width=tw, height=th, num_inference_steps=num_steps, guidance_scale=0.0, generator=gens, ).images for j, img in zip(c_idx, out): it = items[j] rel = f"fake_{gen_name}/{gen_name}_{it['image_id']}.jpg" img.convert("RGB").save(work_dir / rel, format="JPEG", quality=95) records.append({ **it, "prompt_used": prompts_all[j], "generator": gen_name, "model_id": repo_id, "synthesis_kind": "full_diffusion_t2i", "split": split_name, "fake_rel": rel, }) if len(records) % 100 < batch_size or len(records) == len(items): elapsed = time.time() - t_gen rate = len(records) / max(elapsed, 1e-3) print(f" [{gen_name}] {len(records)}/{len(items)} ({rate:.2f} img/s, gen_elapsed={elapsed/60:.1f}m)", flush=True)
del pipe, pe_all, ppe_all gc.collect() torch.cuda.empty_cache() hf_hub = Path(os.environ.get("HF_HOME", "/tmp/hf")) / "hub" slug = "models--" + repo_id.replace("/", "--") shutil.rmtree(hf_hub / slug, ignore_errors=True) print(f"[flux-gen] {gen_name} DONE: {len(records)} pairs in {(time.time()-t0)/60:.1f}m", flush=True) return records
def export_hf_parquet(work_dir: Path, manifest: list[dict[str, Any]], out_pq_dir: Path) -> dict[str, int]: """Export compact HF-Datasets-compatible Parquet files with embedded JPEG bytes (image column as struct{bytes,path}).""" out_pq_dir.mkdir(parents=True, exist_ok=True) img_struct = pa.struct([("bytes", pa.binary()), ("path", pa.string())]) schema = pa.schema([ ("image", img_struct), ("label", pa.int64()), ("label_text", pa.string()), ("pair_id", pa.int64()), ("generator", pa.string()), ("model_id", pa.string()), ("synthesis_kind", pa.string()), ("coco_license", pa.int64()), ("width", pa.int64()), ("height", pa.int64()), ("caption", pa.string()), ])
def _write_split(split_rows: list[dict[str, Any]], prefix: str, shard_rows: int = 2000) -> int: expanded: list[dict[str, Any]] = [] for r in split_rows: # 1:1 paired real + synthetic! rb = (work_dir / r["real_rel"]).read_bytes() fb = (work_dir / r["fake_rel"]).read_bytes() expanded.append({ "image": {"bytes": rb, "path": Path(r["real_rel"]).name}, "label": 1, "label_text": "human", "pair_id": int(r["image_id"]), "generator": "coco_real", "model_id": "MS-COCO-2017-Commercial", "synthesis_kind": "authentic_photo", "coco_license": int(r["coco_license"]), "width": int(r["width"]), "height": int(r["height"]), "caption": str(r["caption"]), }) expanded.append({ "image": {"bytes": fb, "path": Path(r["fake_rel"]).name}, "label": 0, "label_text": "artificial", "pair_id": int(r["image_id"]), "generator": str(r["generator"]), "model_id": str(r["model_id"]), "synthesis_kind": str(r["synthesis_kind"]), "coco_license": int(r["coco_license"]), "width": int(r["width"]), "height": int(r["height"]), "caption": str(r["caption"]), }) random.Random(2026).shuffle(expanded) n_shards = max(1, (len(expanded) + shard_rows - 1) // shard_rows) for si in range(n_shards): chunk = expanded[si * shard_rows : (si + 1) * shard_rows] tbl = pa.Table.from_pylist(chunk, schema=schema) pq.write_table(tbl, out_pq_dir / f"{prefix}-{si:05d}-of-{n_shards:05d}.parquet", compression="zstd") return len(expanded)
tr = [r for r in manifest if r["split"] == "train"] te = [r for r in manifest if r["split"] == "ood_shuttle3_test"] counts = { "train_images": _write_split(tr, "train"), "ood_shuttle3_test_images": _write_split(te, "ood_shuttle3_test"), } print(f"[parquet] Exported {counts} to {out_pq_dir}", flush=True) return counts
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--prev-tar", type=str, default="") ap.add_argument("--work-dir", type=str, default="/tmp/bfree_flux_work") ap.add_argument("--out-tar", type=str, required=True) ap.add_argument("--out-parquet-dir", type=str, required=True) ap.add_argument("--n-flux-vae", type=int, default=2400) ap.add_argument("--n-dcae-vae", type=int, default=1400) ap.add_argument("--n-lumina-vae", type=int, default=1200) ap.add_argument("--n-sdxl-vae", type=int, default=1000) ap.add_argument("--n-flux1-gen", type=int, default=1400) ap.add_argument("--n-shuttle3-ood", type=int, default=400) args = ap.parse_args()
t0 = time.time() device = torch.device("cuda") work = Path(args.work_dir) work.mkdir(parents=True, exist_ok=True)
n_total = args.n_flux_vae + args.n_dcae_vae + args.n_lumina_vae + args.n_sdxl_vae + args.n_flux1_gen + args.n_shuttle3_ood excl = load_excluded_coco_ids(args.prev_tar) pool = collect_commercial_coco(work, n_total=n_total, exclude_ids=excl, seed=2026) assert len(pool) >= n_total, f"Only collected {len(pool)}/{n_total} disjoint commercial COCO images!"
c = 0 s_flux_vae = pool[c : c + args.n_flux_vae]; c += args.n_flux_vae s_dcae_vae = pool[c : c + args.n_dcae_vae]; c += args.n_dcae_vae s_lum_vae = pool[c : c + args.n_lumina_vae]; c += args.n_lumina_vae s_sdxl_vae = pool[c : c + args.n_sdxl_vae]; c += args.n_sdxl_vae s_flux_gen = pool[c : c + args.n_flux1_gen]; c += args.n_flux1_gen s_shut_ood = pool[c : c + args.n_shuttle3_ood]; c += args.n_shuttle3_ood
manifest: list[dict[str, Any]] = [] manifest.extend(run_bfree_vae_reconstructions(work, s_flux_vae, "bfree_flux1_vae", "unsloth/FLUX.1-schnell", "vae", False, device)) manifest.extend(run_bfree_vae_reconstructions(work, s_dcae_vae, "bfree_dcae32", "mit-han-lab/dc-ae-f32c32-sana-1.1-diffusers", None, True, device)) manifest.extend(run_bfree_vae_reconstructions(work, s_lum_vae, "bfree_lumina_vae", "Alpha-VLLM/Lumina-Image-2.0", "vae", False, device)) manifest.extend(run_bfree_vae_reconstructions(work, s_sdxl_vae, "bfree_sdxl_vae", "madebyollin/sdxl-vae-fp16-fix", None, False, device)) manifest.extend(run_flux_generator(work, s_flux_gen, "flux1_schnell", "unsloth/FLUX.1-schnell", "train", batch_size=4, num_steps=4, seed=2026)) manifest.extend(run_flux_generator(work, s_shut_ood, "shuttle3_ood", "shuttleai/shuttle-3-diffusion", "ood_shuttle3_test", batch_size=4, num_steps=4, seed=3026))
man_p = work / "manifest.jsonl" man_p.write_text("\n".join(json.dumps(r) for r in manifest) + "\n", encoding="utf-8")
# Package tar archive for fast v2 training out_tar = Path(args.out_tar) out_tar.parent.mkdir(parents=True, exist_ok=True) print(f"\n[tar] Archiving {len(manifest)} pairs to {out_tar}...", flush=True) with tarfile.open(out_tar, "w") as tf: tf.add(man_p, arcname="manifest.jsonl") seen_rel: set[str] = set() for r in manifest: for k in ("real_rel", "fake_rel"): rel = r[k] if rel not in seen_rel: tf.add(work / rel, arcname=rel) seen_rel.add(rel)
pq_counts = export_hf_parquet(work, manifest, Path(args.out_parquet_dir)) summary = { "n_pairs": len(manifest), "by_generator": dict(Counter(r["generator"] for r in manifest)), "by_split": dict(Counter(r["split"] for r in manifest)), "by_kind": dict(Counter(r["synthesis_kind"] for r in manifest)), "parquet_counts": pq_counts, "tar_mb": round(out_tar.stat().st_size / 1e6, 2), "elapsed_min": round((time.time() - t0) / 60.0, 2), } (out_tar.parent / "synth_v2_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") print(f"[DONE] synth_bfree_flux_v2 complete: {json.dumps(summary, indent=2)}", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435"""Family #12 v2 Trainer: CVPR-2025 B-Free Clean/Degraded Curriculum + Online Cross-Architecture Logit KD!
Key v2 Upgrades over v1: 1. 35% Clean Native-Resolution Crop Branch (ZERO resize, ZERO JPEG re-compression when min(w,h) >= img_size) + 65% Symmetric Social-Media Degradation Branch (JPEG/WebP/double-JPEG/resize/blur/unsharp). Fixes v1's over-compression blindspot on crisp 16-ch FLUX/GPT-Image/Z-Image micro-artifacts while preserving #1 social_recompressed robustness! 2. Online bf16 Cross-Architecture / Cross-Resolution Knowledge Distillation (SigLIP2-B-384 teacher -> ConvNeXtV2-T-384 `small` & DINOv2-S-224 `tiny`): feeds the EXACT same augmented PIL image through both student processor and teacher processor, combining FocalSmooth CE + 70% KL(T=2.0) + 30% logit MSE! 3. Validation-only checkpoint selection (val EER / ROC-AUC) + post-hoc temperature calibration.json."""
from __future__ import annotations
import argparseimport copyimport ioimport jsonimport mathimport osimport randomimport timefrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom typing import Any
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom PIL import Image, ImageEnhance, ImageFilterfrom scipy.optimize import minimize_scalarfrom sklearn.metrics import roc_auc_score, roc_curvefrom torch.utils.data import DataLoader, Dataset, WeightedRandomSamplerfrom transformers import AutoImageProcessor, AutoModelForImageClassification, get_cosine_schedule_with_warmup
Image.MAX_IMAGE_PIXELS = NoneID2LABEL = {0: "artificial", 1: "human"}LABEL2ID = {"artificial": 0, "human": 1}
def compute_eer(y_true_artificial: np.ndarray, p_artificial: np.ndarray) -> tuple[float, float]: fpr, tpr, _ = roc_curve(y_true_artificial, p_artificial) fnr = 1.0 - tpr idx = int(np.nanargmin(np.abs(fnr - fpr))) eer = float(0.5 * (fpr[idx] + fnr[idx])) auc = float(roc_auc_score(y_true_artificial, p_artificial)) return eer, auc
def compute_ece(y_true: np.ndarray, probs: np.ndarray, n_bins: int = 15) -> float: bins = np.linspace(0.0, 1.0, n_bins + 1) ece = 0.0 for i in range(n_bins): lo, hi = bins[i], bins[i + 1] m = (probs >= lo) & (probs <= hi if i == n_bins - 1 else probs < hi) if m.any(): ece += float(m.mean()) * abs(float(y_true[m].mean()) - float(probs[m].mean())) return float(ece)
def bfree_forensic_augment(im: Image.Image, target_size: int, rng: random.Random) -> Image.Image: """CVPR-2025 B-Free Clean/Degraded Curriculum: - 35% Clean Native-Pixel Branch: pure native crop (no destructive resize, no JPEG recompression) to preserve ultra-subtle 16-ch VAE & rectified-flow micro-artifacts. - 65% Symmetric Social-Media Degradation Branch: identical JPEG/WebP/double-JPEG/resize/blur/unsharp applied symmetrically to both authentic & synthetic images. """ im = im.convert("RGB") w, h = im.size
if rng.random() < 0.50: im = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
# Branch A (35%): Clean native-pixel crop (preserves high-frequency VAE decoder artifacts!) if rng.random() < 0.35: if min(w, h) >= target_size and rng.random() < 0.65: # Exact native-scale patch crop (no interpolation distortion!) cs = min(w, h, max(target_size, int(min(w, h) * rng.uniform(0.65, 1.0)))) x0 = rng.randint(0, max(0, w - cs)) y0 = rng.randint(0, max(0, h - cs)) im = im.crop((x0, y0, x0 + cs, y0 + cs)) return im
# Branch B (65%): Symmetric realistic social-media degradation chain if rng.random() < 0.65 and min(w, h) >= 192: scale = rng.uniform(0.60, 0.98) ratio = rng.uniform(0.82, 1.22) area = w * h * scale cw = min(w, max(128, int(round(math.sqrt(area * ratio))))) ch = min(h, max(128, int(round(math.sqrt(area / ratio))))) x0 = rng.randint(0, max(0, w - cw)) y0 = rng.randint(0, max(0, h - ch)) im = im.crop((x0, y0, x0 + cw, y0 + ch))
if rng.random() < 0.35: res_alg = rng.choice([Image.Resampling.BILINEAR, Image.Resampling.BICUBIC, Image.Resampling.LANCZOS]) f = rng.uniform(0.45, 0.88) nw, nh = max(128, int(im.width * f)), max(128, int(im.height * f)) im = im.resize((nw, nh), res_alg)
r_filt = rng.random() if r_filt < 0.14: im = im.filter(ImageFilter.GaussianBlur(radius=rng.uniform(0.3, 1.1))) elif r_filt < 0.24: im = im.filter(ImageFilter.UnsharpMask(radius=rng.uniform(0.8, 1.8), percent=rng.randint(60, 140), threshold=2))
if rng.random() < 0.28: im = ImageEnhance.Brightness(im).enhance(rng.uniform(0.91, 1.09)) im = ImageEnhance.Contrast(im).enhance(rng.uniform(0.91, 1.10)) im = ImageEnhance.Color(im).enhance(rng.uniform(0.91, 1.09))
r_codec = rng.random() if r_codec < 0.45: buf = io.BytesIO() im.save(buf, format="JPEG", quality=rng.randint(35, 95)) buf.seek(0) im = Image.open(buf).convert("RGB") elif r_codec < 0.65: buf = io.BytesIO() im.save(buf, format="WEBP", quality=rng.randint(40, 95)) buf.seek(0) im = Image.open(buf).convert("RGB") elif r_codec < 0.85: b1 = io.BytesIO() im.save(b1, format="JPEG", quality=rng.randint(42, 85)) b1.seek(0) im = Image.open(b1).convert("RGB") b2 = io.BytesIO() im.save(b2, format=rng.choice(["JPEG", "WEBP"]), quality=rng.randint(40, 80)) b2.seek(0) im = Image.open(b2).convert("RGB")
return im
class ForensicImageDataset(Dataset): def __init__(self, rows: list[dict[str, Any]]) -> None: self.rows = rows
def __len__(self) -> int: return len(self.rows)
def __getitem__(self, idx: int) -> dict[str, Any]: return self.rows[idx]
class ThreadedImageCollator: def __init__( self, processor: Any, img_size: int, is_train: bool, teacher_processor: Any | None = None, max_workers: int = 8, ) -> None: self.processor = processor self.teacher_processor = teacher_processor self.img_size = img_size self.is_train = is_train self.pool = ThreadPoolExecutor(max_workers=max_workers)
def _load_one(self, r: dict[str, Any]) -> tuple[Image.Image, int]: try: im = Image.open(r["path"]).convert("RGB") except Exception: im = Image.new("RGB", (self.img_size, self.img_size), (128, 128, 128)) if self.is_train: rng = random.Random(random.getrandbits(64)) im = bfree_forensic_augment(im, self.img_size, rng) return im, int(r["label"])
def __call__(self, batch: list[dict[str, Any]]) -> dict[str, torch.Tensor]: loaded = list(self.pool.map(self._load_one, batch)) ims = [x[0] for x in loaded] ys = torch.tensor([x[1] for x in loaded], dtype=torch.long) out: dict[str, torch.Tensor] = { "pixel_values": self.processor(images=ims, return_tensors="pt")["pixel_values"], "labels": ys, } if self.teacher_processor is not None: out["t_pixel_values"] = self.teacher_processor(images=ims, return_tensors="pt")["pixel_values"] return out
class FocalSmoothLoss(nn.Module): def __init__(self, gamma: float = 1.0, smoothing: float = 0.03) -> None: super().__init__() self.gamma = gamma self.smoothing = smoothing
def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: log_p = F.log_softmax(logits, dim=-1) p = log_p.exp() n_cls = logits.size(-1) with torch.no_grad(): smooth_t = torch.full_like(log_p, self.smoothing / (n_cls - 1)) smooth_t.scatter_(1, targets.unsqueeze(1), 1.0 - self.smoothing) pt = p.gather(1, targets.unsqueeze(1)).squeeze(1).clamp(1e-6, 1.0) focal = (1.0 - pt) ** self.gamma ce = -(smooth_t * log_p).sum(dim=-1) return (focal * ce).mean()
def evaluate_val(model: nn.Module, loader: DataLoader, device: torch.device, use_bf16: bool = True) -> tuple[float, float, np.ndarray, np.ndarray]: model.eval() all_logits, all_labels = [], [] with torch.no_grad(), torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16): for batch in loader: pv = batch["pixel_values"].to(device, non_blocking=True) z = model(pixel_values=pv).logits.float().cpu().numpy() all_logits.append(z) all_labels.append(batch["labels"].numpy()) logits = np.concatenate(all_logits, axis=0) labels = np.concatenate(all_labels, axis=0) ex = np.exp(logits - logits.max(axis=-1, keepdims=True)) p_art = (ex / ex.sum(axis=-1, keepdims=True))[:, 0] y_art = (labels == 0).astype(np.int32) eer, auc = compute_eer(y_art, p_art) return eer, auc, logits, labels
def fit_calibration(logits: np.ndarray, labels: np.ndarray) -> dict[str, Any]: y_art = (labels == 0).astype(np.int32) t_logits = torch.tensor(logits, dtype=torch.float32) t_labels = torch.tensor(labels, dtype=torch.long)
def nll(temp: float) -> float: return float(F.cross_entropy(t_logits / temp, t_labels).item())
opt = minimize_scalar(nll, bounds=(0.25, 4.0), method="bounded") T = float(opt.x) probs = torch.softmax(t_logits / T, dim=-1).numpy() p_art = probs[:, 0] eer, auc = compute_eer(y_art, p_art) ece = compute_ece(y_art, p_art) real_scores = p_art[y_art == 0] return { "temperature": round(T, 4), "val_eer": round(eer, 5), "val_auc": round(auc, 5), "calibrated_ece_artificial": round(ece, 5), "thr_val_5pct_fpr": round(float(np.quantile(real_scores, 0.95)), 4), "thr_val_1pct_fpr": round(float(np.quantile(real_scores, 0.99)), 4), "id2label": ID2LABEL, }
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--backbone", type=str, required=True) ap.add_argument("--img-size", type=int, default=224) ap.add_argument("--train-jsonl", type=str, required=True) ap.add_argument("--val-jsonl", type=str, required=True) ap.add_argument("--out-dir", type=str, required=True) ap.add_argument("--teacher-dir", type=str, default="") ap.add_argument("--kd-weight", type=float, default=0.45) ap.add_argument("--kd-temp", type=float, default=2.0) ap.add_argument("--epochs", type=int, default=5) ap.add_argument("--samples-per-epoch", type=int, default=0, help="0 = len(train_rows)") ap.add_argument("--batch-size", type=int, default=64) ap.add_argument("--grad-accum", type=int, default=1) ap.add_argument("--lr", type=float, default=3e-5) ap.add_argument("--seed", type=int, default=2026) args = ap.parse_args()
os.environ["HF_HOME"] = "/tmp/hf" torch.multiprocessing.set_sharing_strategy("file_system") random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed)
torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True use_bf16 = True device = torch.device("cuda") out_dir = Path(args.out_dir) out_dir.mkdir(parents=True, exist_ok=True)
train_rows = [json.loads(l) for l in Path(args.train_jsonl).read_text(encoding="utf-8").splitlines() if l.strip()] val_rows = [json.loads(l) for l in Path(args.val_jsonl).read_text(encoding="utf-8").splitlines() if l.strip()]
processor = AutoImageProcessor.from_pretrained(args.backbone) model = AutoModelForImageClassification.from_pretrained( args.backbone, num_labels=2, id2label=ID2LABEL, label2id=LABEL2ID, ignore_mismatched_sizes=True, ).to(device) # Fix transformers==4.51.3 ConvNextV2GRN bug: torch.linalg.norm(ord=2, dim=(1,2)) dispatches to matrix_norm (SVD!) # instead of vector L2 norm — 100x slower & breaks bf16! Replace with true vector_norm (Frobenius L2). _patched_grn_cls: set[type] = set() for _mod in model.modules(): _cls = _mod.__class__ if _cls.__name__ == "ConvNextV2GRN" and _cls not in _patched_grn_cls: def _grn_fast(self, hidden_states): x = hidden_states.float() gx = torch.linalg.vector_norm(x, ord=2, dim=(1, 2), keepdim=True) nx = gx / (gx.mean(dim=-1, keepdim=True) + 1e-6) w = self.weight if hasattr(self, "weight") else self.gamma b = self.bias if hasattr(self, "bias") else self.beta return (w.float() * (x * nx) + b.float() + x).to(hidden_states.dtype) _cls.forward = _grn_fast _patched_grn_cls.add(_cls) n_params = sum(p.numel() for p in model.parameters()) / 1e6
teacher_model = None teacher_proc = None if args.teacher_dir: print(f"[kd] Loading teacher from {args.teacher_dir} (bf16, kd_weight={args.kd_weight}, T={args.kd_temp})...", flush=True) teacher_proc = AutoImageProcessor.from_pretrained(args.teacher_dir) teacher_model = AutoModelForImageClassification.from_pretrained(args.teacher_dir, torch_dtype=torch.bfloat16).to(device).eval() for p in teacher_model.parameters(): p.requires_grad_(False)
print(f"[train_v2] {args.backbone} ({n_params:.2f}M) @ {args.img_size}px | train={len(train_rows):,}, val={len(val_rows):,} | kd={bool(teacher_model)}", flush=True)
weights = [float(r.get("weight", 1.0)) for r in train_rows] n_spe = args.samples_per_epoch if args.samples_per_epoch > 0 else len(train_rows) sampler = WeightedRandomSampler(weights, num_samples=n_spe, replacement=True)
train_col = ThreadedImageCollator(processor, args.img_size, is_train=True, teacher_processor=teacher_proc, max_workers=8) val_col = ThreadedImageCollator(processor, args.img_size, is_train=False, teacher_processor=None, max_workers=8) train_loader = DataLoader(ForensicImageDataset(train_rows), batch_size=args.batch_size, sampler=sampler, num_workers=0, collate_fn=train_col, pin_memory=True, drop_last=True) val_loader = DataLoader(ForensicImageDataset(val_rows), batch_size=args.batch_size, shuffle=False, num_workers=0, collate_fn=val_col, pin_memory=True)
head_params, body_params = [], [] for name, p in model.named_parameters(): if not p.requires_grad: continue if any(k in name for k in ("classifier", "head")): head_params.append(p) else: body_params.append(p) opt = torch.optim.AdamW([ {"params": body_params, "lr": args.lr, "weight_decay": 0.02}, {"params": head_params, "lr": args.lr * 5.0, "weight_decay": 0.01}, ]) total_steps = max(1, (len(train_loader) // args.grad_accum) * args.epochs) sched = get_cosine_schedule_with_warmup(opt, num_warmup_steps=int(0.08 * total_steps), num_training_steps=total_steps) criterion = FocalSmoothLoss(gamma=1.0, smoothing=0.03)
ema_model = copy.deepcopy(model).eval() for p in ema_model.parameters(): p.requires_grad_(False) ema_decay = 0.996
best_eer = 1.0 best_state: dict[str, torch.Tensor] | None = None t0 = time.time()
for ep in range(1, args.epochs + 1): model.train() opt.zero_grad(set_to_none=True) run_loss = 0.0 for step, batch in enumerate(train_loader, 1): pv = batch["pixel_values"].to(device, non_blocking=True) y = batch["labels"].to(device, non_blocking=True) with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16): logits = model(pixel_values=pv).logits.float() sup_loss = criterion(logits, y) if teacher_model is not None and args.kd_weight > 0.0: tpv = batch["t_pixel_values"].to(device, non_blocking=True) with torch.no_grad(), torch.amp.autocast("cuda", dtype=torch.bfloat16): t_logits = teacher_model(pixel_values=tpv).logits.float() T = args.kd_temp kl = F.kl_div(F.log_softmax(logits / T, dim=-1), F.softmax(t_logits / T, dim=-1), reduction="batchmean") * (T * T) s_std = (logits - logits.mean(dim=0, keepdim=True)) / (logits.std(dim=0, keepdim=True) + 1e-4) t_std = (t_logits - t_logits.mean(dim=0, keepdim=True)) / (t_logits.std(dim=0, keepdim=True) + 1e-4) kd_loss = 0.70 * kl + 0.30 * F.mse_loss(s_std, t_std) loss = ((1.0 - args.kd_weight) * sup_loss + args.kd_weight * kd_loss) / args.grad_accum else: loss = sup_loss / args.grad_accum
loss.backward() run_loss += float(loss.item()) * args.grad_accum
if step % args.grad_accum == 0 or step == len(train_loader): torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() sched.step() opt.zero_grad(set_to_none=True) with torch.no_grad(): for pe, pm in zip(ema_model.parameters(), model.parameters()): pe.data.mul_(ema_decay).add_(pm.data, alpha=1.0 - ema_decay)
val_eer, val_auc, _, _ = evaluate_val(ema_model, val_loader, device, use_bf16=use_bf16) raw_eer, raw_auc, _, _ = evaluate_val(model, val_loader, device, use_bf16=use_bf16) use_ema = val_eer <= raw_eer cur_eer = val_eer if use_ema else raw_eer print( f" [ep {ep}/{args.epochs}] loss={run_loss/len(train_loader):.4f} | " f"ema_val_eer={val_eer*100:.2f}% auc={val_auc:.4f} | raw_val_eer={raw_eer*100:.2f}% auc={raw_auc:.4f} | " f"elapsed={(time.time()-t0)/60:.1f}m", flush=True, ) if cur_eer < best_eer: best_eer = cur_eer src_m = ema_model if use_ema else model best_state = {k: v.detach().cpu().clone() for k, v in src_m.state_dict().items()} # Incremental checkpoint save for Spot resilience! src_m_cpu = copy.deepcopy(src_m).cpu() src_m_cpu.save_pretrained(out_dir, safe_serialization=True) processor.save_pretrained(out_dir)
assert best_state is not None model.load_state_dict(best_state) model.eval() final_eer, final_auc, val_logits, val_labels = evaluate_val(model, val_loader, device, use_bf16=use_bf16) cal = fit_calibration(val_logits, val_labels) print(f"[DONE] Best val EER={final_eer*100:.2f}% AUC={final_auc:.4f} | cal={cal}", flush=True)
model.cpu().save_pretrained(out_dir, safe_serialization=True) processor.save_pretrained(out_dir) (out_dir / "calibration.json").write_text(json.dumps(cal, indent=2), encoding="utf-8") summary = { "backbone": args.backbone, "teacher_dir": args.teacher_dir or None, "kd_weight": args.kd_weight if teacher_model is not None else 0.0, "params_m": round(n_params, 2), "img_size": args.img_size, "train_examples": len(train_rows), "val_examples": len(val_rows), "epochs": args.epochs, "best_val_eer": round(final_eer, 5), "best_val_auc": round(final_auc, 5), "train_minutes": round((time.time() - t0) / 60.0, 2), } (out_dir / "train_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
if __name__ == "__main__": main()12345678910111213{ "backbone": "facebook/dinov2-small", "teacher_dir": null, "kd_weight": 0.0, "params_m": 22.06, "img_size": 224, "train_examples": 31531, "val_examples": 2380, "epochs": 4, "best_val_eer": 0.01975, "best_val_auc": 0.9971, "train_minutes": 30.89}README.md+102-111
assets/pareto.svg
calibration.json+6-6
config.json+1-2
model.safetensors+1-1
onnx/model.onnx+2-2
onnx/model_fp16.onnxAdded+3
onnx_bench.jsonAdded+42
scripts/build_base_cache_v2.pyAdded+276
scripts/eval_image_suite.py+14-1
scripts/export_image_onnx.py+47-7
scripts/prepare_v2_manifests.pyAdded+140
scripts/synth_bfree_flux_v2.pyAdded+494
scripts/train_image_v2.pyAdded+435
train_summary.jsonAdded+13