Image Classification
Transformers
ONNX
Safetensors
siglip
ai-image-detection
deepfake-detection
image-forensics
agent-forensics
siglip2
ai-image-detector
ai-detector
synthetic-image-detection
Instructions to use Tamarillo/ai-image-forensics-guard-base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tamarillo/ai-image-forensics-guard-base with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-classification", model="Tamarillo/ai-image-forensics-guard-base") pipe("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/parrots.png")# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForImageClassification processor = AutoProcessor.from_pretrained("Tamarillo/ai-image-forensics-guard-base") model = AutoModelForImageClassification.from_pretrained("Tamarillo/ai-image-forensics-guard-base", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download scripts/train_image_model.py from Tamarillo/ai-image-forensics-guard-base: direct link, hf CLI and curl.
- Browser
- Download file 16.2 kB
-
https://huggingface.co/Tamarillo/ai-image-forensics-guard-base/resolve/main/scripts/train_image_model.py
- Command line
-
hf download hf://Tamarillo/ai-image-forensics-guard-base/scripts/train_image_model.py
-
curl -L -o train_image_model.py https://huggingface.co/Tamarillo/ai-image-forensics-guard-base/resolve/main/scripts/train_image_model.py
16.2 kB
| """Family #12 Step 1B-2: Train Apache-2.0 AI-Image Forensics Guards | |
| (tiny: facebook/dinov2-small 22.1M 224px | small: facebook/convnextv2-tiny-22k-384 28.6M 384px | | |
| base: google/siglip2-base-patch16-384 92.9M 384px) | |
| Exact 1-line drop-in schema: id2label = {0: "artificial", 1: "human"}, AutoModelForImageClassification. | |
| Key anti-shortcut recipe: | |
| - Identical symmetric social-media degradation chain applied 50/50 to BOTH artificial & human images | |
| (JPEG Q35-95, WebP Q40-95, double-JPEG + Bilinear/Bicubic/Lanczos resize, mild blur/unsharp mask, | |
| RandomResizedCrop, RandomHorizontalFlip, mild ColorJitter). | |
| - WeightedRandomSampler upweighting 1:1 matched 2025-2026 DiT/flow-matching pairs 2x. | |
| - Focal cross-entropy (gamma=1.0, label_smoothing=0.03), differential LR (head 5x), EMA 0.996. | |
| - Validation-only checkpoint selection (val EER / ROC-AUC) + post-hoc temperature calibration.json. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import copy | |
| import io | |
| import json | |
| import math | |
| import os | |
| import random | |
| import time | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from PIL import Image, ImageEnhance, ImageFilter | |
| from scipy.optimize import minimize_scalar | |
| from sklearn.metrics import roc_auc_score, roc_curve | |
| from torch.utils.data import DataLoader, Dataset, WeightedRandomSampler | |
| from transformers import AutoImageProcessor, AutoModelForImageClassification, get_cosine_schedule_with_warmup | |
| Image.MAX_IMAGE_PIXELS = None | |
| ID2LABEL = {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 symmetric_forensic_augment(im: Image.Image, target_size: int, rng: random.Random) -> Image.Image: | |
| """Identical realistic social-media & photography degradation applied to BOTH real & AI images.""" | |
| im = im.convert("RGB") | |
| w, h = im.size | |
| # 1. Random aspect-preserving crop (destroys fixed-border / aspect-ratio shortcuts) | |
| if rng.random() < 0.70 and min(w, h) >= 192: | |
| scale = rng.uniform(0.60, 0.98) | |
| ratio = rng.uniform(0.80, 1.25) | |
| 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.50: | |
| im = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT) | |
| # 2. Random social-media downscale/upscale (destroys resolution shortcuts) | |
| 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) | |
| # 3. Mild blur or smartphone sharpening/HDR jitter | |
| r_filt = rng.random() | |
| if r_filt < 0.14: | |
| im = im.filter(ImageFilter.GaussianBlur(radius=rng.uniform(0.3, 1.2))) | |
| 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.30: | |
| im = ImageEnhance.Brightness(im).enhance(rng.uniform(0.90, 1.10)) | |
| im = ImageEnhance.Contrast(im).enhance(rng.uniform(0.90, 1.12)) | |
| im = ImageEnhance.Color(im).enhance(rng.uniform(0.90, 1.10)) | |
| # 4. Real symmetric JPEG / WebP / double-JPEG compression (crucial for WhatsApp/X/Reddit robustness!) | |
| 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.80: | |
| # Double compression (JPEG -> WebP or JPEG -> JPEG) | |
| b1 = io.BytesIO() | |
| im.save(b1, format="JPEG", quality=rng.randint(45, 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") | |
| # Let AutoImageProcessor perform its exact canonical resize & crop identically in train and eval! | |
| return im | |
| class ForensicImageDataset(Dataset): | |
| """Returns lightweight row dicts so a ThreadPoolExecutor collate_fn can decode/augment | |
| images in parallel across CPU cores with num_workers=0 (ZERO /dev/shm Bus errors!).""" | |
| 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, max_workers: int = 6) -> None: | |
| self.processor = 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 = symmetric_forensic_augment(im, self.img_size, rng) | |
| return im, int(r["label"]) | |
| def __call__(self, batch: list[dict[str, Any]]) -> tuple[torch.Tensor, 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) | |
| pv = self.processor(images=ims, return_tensors="pt")["pixel_values"] | |
| return pv, ys | |
| 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) -> tuple[float, float, np.ndarray, np.ndarray]: | |
| model.eval() | |
| all_logits, all_labels = [], [] | |
| with torch.no_grad(), torch.amp.autocast("cuda", dtype=torch.bfloat16): | |
| for pv, y in loader: | |
| pv = pv.to(device, non_blocking=True) | |
| z = model(pixel_values=pv).logits.float().cpu().numpy() | |
| all_logits.append(z) | |
| all_labels.append(y.numpy()) | |
| logits = np.concatenate(all_logits, axis=0) | |
| labels = np.concatenate(all_labels, axis=0) | |
| # Class 0 = artificial (positive class for EER / ROC-AUC!) | |
| 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] | |
| thr_5 = float(np.quantile(real_scores, 0.95)) | |
| thr_1 = float(np.quantile(real_scores, 0.99)) | |
| 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(thr_5, 4), | |
| "thr_val_1pct_fpr": round(thr_1, 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("--epochs", type=int, default=5) | |
| 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=42) | |
| 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) | |
| 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()] | |
| # Keep each canonical backbone's official AutoImageProcessor untouched so train, eval, | |
| # Hugging Face pipeline("image-classification"), ONNX, and Transformers.js match 100%! | |
| 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) | |
| n_params = sum(p.numel() for p in model.parameters()) / 1e6 | |
| print(f"[train] {args.backbone} ({n_params:.2f}M params) @ {args.img_size}px | train={len(train_rows)}, val={len(val_rows)}", flush=True) | |
| # Weighted sampler upweighting 1:1 matched 2025-2026 pairs 2x! | |
| weights = [float(r.get("weight", 1.0)) for r in train_rows] | |
| sampler = WeightedRandomSampler(weights, num_samples=len(train_rows), replacement=True) | |
| train_ds = ForensicImageDataset(train_rows) | |
| val_ds = ForensicImageDataset(val_rows) | |
| # Multi-threaded PIL JPEG/WebP decoding + augmentation with num_workers=0 (5x faster & ZERO /dev/shm!) | |
| train_col = ThreadedImageCollator(processor, args.img_size, is_train=True, max_workers=6) | |
| val_col = ThreadedImageCollator(processor, args.img_size, is_train=False, max_workers=6) | |
| train_loader = DataLoader(train_ds, batch_size=args.batch_size, sampler=sampler, num_workers=0, collate_fn=train_col, pin_memory=True, drop_last=True) | |
| val_loader = DataLoader(val_ds, batch_size=args.batch_size, shuffle=False, num_workers=0, collate_fn=val_col, pin_memory=True) | |
| # Differential LR: backbone = args.lr, classification head = 5 * args.lr | |
| 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_auc = 0.0 | |
| best_state: dict[str, torch.Tensor] | None = None | |
| t0 = time.time() | |
| gstep = 0 | |
| for ep in range(1, args.epochs + 1): | |
| model.train() | |
| opt.zero_grad(set_to_none=True) | |
| run_loss = 0.0 | |
| for step, (pv, y) in enumerate(train_loader, 1): | |
| pv = pv.to(device, non_blocking=True) | |
| y = y.to(device, non_blocking=True) | |
| with torch.amp.autocast("cuda", dtype=torch.bfloat16): | |
| logits = model(pixel_values=pv).logits | |
| loss = criterion(logits, y) / 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) | |
| gstep += 1 | |
| 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) | |
| raw_eer, raw_auc, _, _ = evaluate_val(model, val_loader, device) | |
| use_ema = val_eer <= raw_eer | |
| cur_eer = val_eer if use_ema else raw_eer | |
| cur_auc = val_auc if use_ema else raw_auc | |
| 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 | |
| best_auc = cur_auc | |
| 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()} | |
| 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) | |
| 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, | |
| "params_m": round(n_params, 2), | |
| "img_size": args.img_size, | |
| "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() | |