#!/usr/bin/env python3 """ Unified evaluation script for legacy AI-generated image detection methods on ACID dataset. This script evaluates CNNDetection and UnivFD pretrained models to verify that existing methods struggle to generalize to unseen AI models in the ACID dataset. Usage: python evaluate_legacy.py --method CNNDetection --acid-root /path/to/acid/images python evaluate_legacy.py --method UnivFD --acid-root /path/to/acid/images """ import argparse import csv import os import sys from datetime import datetime from pathlib import Path from typing import Dict, List, Tuple, Optional import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from tqdm import tqdm import torchvision.transforms as T # Define directories first SCRIPT_DIR = Path(__file__).resolve().parent METHODS_DIR = SCRIPT_DIR.parent / "methods" # Import local eval_utils BEFORE modifying sys.path to avoid conflicts with method utils from eval_utils import ( load_model_mapping, get_model_folders, get_image_files, ACIDEvalDataset, create_per_model_datasets, create_real_dataset, get_model_name, compute_metrics, save_image_paths, ) # Training-free methods that use relative scores without learned thresholds. # For these methods, AUC and AP are the primary metrics (accuracy is less meaningful). TRAINING_FREE_METHODS = {"AEROBLADE", "WaRPAD", "RIGID", "ManifoldBias"} # Add method directories to path for their imports (after local utils import) # NOTE: We intentionally DO NOT add WaRPAD, RINE/src, or other paths with utils.py files # that could conflict with HiFi_IFDL's utils/utils.py package structure. # These will be added dynamically in their respective wrappers. sys.path.insert(0, str(METHODS_DIR / "CNNDetection")) sys.path.insert(0, str(METHODS_DIR / "UniversalFakeDetect")) sys.path.insert(0, str(METHODS_DIR / "LGrad" / "CNNDetection")) sys.path.insert(0, str(METHODS_DIR / "FusingGlobalandLocal")) sys.path.insert(0, str(METHODS_DIR / "DeeCLIP")) sys.path.insert(0, str(METHODS_DIR / "DIRE")) class CNNDetectionWrapper: """Wrapper for CNNDetection model.""" def __init__(self, weights_path: str, device: str = "cuda"): if not Path(weights_path).is_file(): raise FileNotFoundError(weights_path) self.device = device # Import CNNDetection model using importlib for reliable path handling import importlib.util resnet_path = METHODS_DIR / "CNNDetection" / "networks" / "resnet.py" spec = importlib.util.spec_from_file_location("resnet", resnet_path) resnet_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(resnet_module) resnet50 = resnet_module.resnet50 self.model = resnet50(num_classes=1) state_dict = torch.load(weights_path, map_location="cpu", weights_only=False) # Handle different state dict formats if "model" in state_dict: state_dict = state_dict["model"] self.model.load_state_dict(state_dict) self.model = self.model.to(device) self.model.eval() # CNNDetection uses ImageNet normalization import torchvision.transforms as T self.transform = T.Compose([ T.Resize(256), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: """ Predict if images are fake. Args: images: Batch of images [B, 3, H, W] Returns: predictions: Binary predictions (0=real, 1=fake) probabilities: Probability of being fake """ images = images.to(self.device) logits = self.model(images) probs = torch.sigmoid(logits).squeeze(-1) preds = (probs > 0.5).int() return preds.cpu().tolist(), probs.cpu().tolist() class UnivFDWrapper: """Wrapper for UniversalFakeDetect (UnivFD) model.""" def __init__(self, weights_path: str, device: str = "cuda"): if not Path(weights_path).is_file(): raise FileNotFoundError(weights_path) self.device = device # Load CLIP model try: import clip except ImportError: raise ImportError("Please install clip: pip install git+https://github.com/openai/CLIP.git") self.clip_model, self.preprocess = clip.load("ViT-L/14", device=device) self.clip_model.eval() # Load FC weights fc_weights = torch.load(weights_path, map_location="cpu") # The FC layer maps from CLIP feature dim (768) to 1 self.fc = nn.Linear(768, 1) # Handle different weight formats if isinstance(fc_weights, dict): if "weight" in fc_weights: self.fc.weight.data = fc_weights["weight"] self.fc.bias.data = fc_weights["bias"] else: self.fc.load_state_dict(fc_weights) else: self.fc.load_state_dict(fc_weights) self.fc = self.fc.to(device) self.fc.eval() # CLIP uses 224x224 input import torchvision.transforms as T self.transform = T.Compose([ T.Resize(224), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]), ]) @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: """ Predict if images are fake. Args: images: Batch of images [B, 3, H, W] Returns: predictions: Binary predictions (0=real, 1=fake) probabilities: Probability of being fake """ images = images.to(self.device) # Extract CLIP features features = self.clip_model.encode_image(images) features = features.float() # Apply FC layer logits = self.fc(features).squeeze(-1) probs = torch.sigmoid(logits) preds = (probs > 0.5).int() return preds.cpu().tolist(), probs.cpu().tolist() class LGradWrapper: """Wrapper for LGrad (Learning on Gradients) detector. Reference: "Learning on Gradients: Generalized Artifacts Representation for GAN-Generated Images Detection" Tan et al., CVPR 2023 GitHub: https://github.com/chuangchuangtan/LGrad LGrad works by: 1. Passing images through a pretrained StyleGAN discriminator 2. Computing gradients of the discriminator output w.r.t. input images via backpropagation 3. Using these gradient images as input to a binary classifier The key insight is that the discriminator gradients reveal artifacts specific to generated images that are not visible in the original pixel space. Requirements: - StyleGAN discriminator weights: Download from the LGrad repo or use the provided path - Classifier weights: Pre-trained ResNet50 on gradient images """ # Default path to StyleGAN discriminator weights (256x256 bedroom model) DEFAULT_STYLEGAN_WEIGHTS = "weights/stylegan_discriminator.pth" def __init__(self, weights_path: str, device: str = "cuda", stylegan_weights_path: str = None): if not Path(weights_path).is_file(): raise FileNotFoundError(weights_path) self.device = device # Import LGrad classifier model (uses same ResNet architecture as CNNDetection) import importlib.util resnet_path = METHODS_DIR / "LGrad" / "CNNDetection" / "networks" / "resnet.py" spec = importlib.util.spec_from_file_location("resnet_lgrad", resnet_path) resnet_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(resnet_module) resnet50 = resnet_module.resnet50 self.model = resnet50(num_classes=1) state_dict = torch.load(weights_path, map_location="cpu", weights_only=False) if "model" in state_dict: state_dict = state_dict["model"] self.model.load_state_dict(state_dict) self.model = self.model.to(device) self.model.eval() # Load StyleGAN discriminator for gradient computation lgrad_path = METHODS_DIR / "LGrad" / "img2gad_pytorch" sys.path.insert(0, str(lgrad_path)) from models import build_model as build_stylegan_model self.discriminator = build_stylegan_model( gan_type='stylegan', module='discriminator', resolution=256, label_size=0, image_channels=3 ) # Load StyleGAN discriminator weights if stylegan_weights_path is None: stylegan_weights_path = METHODS_DIR / "LGrad" / "img2gad_pytorch" / self.DEFAULT_STYLEGAN_WEIGHTS if os.path.exists(stylegan_weights_path): self.discriminator.load_state_dict(torch.load(stylegan_weights_path, map_location="cpu", weights_only=False), strict=True) print(f"Loaded StyleGAN discriminator weights from {stylegan_weights_path}") else: raise FileNotFoundError(stylegan_weights_path) self.discriminator = self.discriminator.to(device) self.discriminator.eval() # Transform for gradient computation (StyleGAN expects 256x256, normalized to [-1, 1]) self.grad_transform = T.Compose([ T.Resize((256, 256)), T.ToTensor(), T.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]), ]) # Transform for classifier input (ImageNet normalization after gradient computation) self.classifier_transform = T.Compose([ T.Resize(256), T.CenterCrop(224), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) # Standard transform for dataset loading (same as get_transform) self.transform = T.Compose([ T.Resize(256), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) def _compute_discriminator_gradient(self, images: torch.Tensor) -> torch.Tensor: """Compute gradients of StyleGAN discriminator output w.r.t. input images. This is the core of LGrad: the gradient image reveals artifacts that the discriminator is sensitive to, which differ between real and generated images. Args: images: Batch of images [B, 3, H, W] normalized to [-1, 1] range Returns: Gradient images [B, 3, H, W] normalized to [0, 1] range """ # Ensure images require gradients for backpropagation images = images.clone().detach().requires_grad_(True) # Forward pass through discriminator disc_output = self.discriminator(images) # Compute gradients w.r.t. input images # We sum the discriminator output and backpropagate to get per-pixel gradients self.discriminator.zero_grad() grad = torch.autograd.grad( disc_output.sum(), images, create_graph=False, retain_graph=False, allow_unused=False )[0] # Normalize gradients to [0, 1] range (per-image normalization as in original LGrad) batch_size = grad.shape[0] grad_normalized = [] for i in range(batch_size): g = grad[i] g = g - g.min() if g.max() != 0: g = g / g.max() grad_normalized.append(g) return torch.stack(grad_normalized, dim=0) def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: """Predict if images are fake using LGrad method. Args: images: Batch of images [B, 3, H, W] - expects images already preprocessed with grad_transform (256x256, normalized to [-1, 1]) Returns: predictions: Binary predictions (0=real, 1=fake) probabilities: Probability of being fake """ images = images.to(self.device) # Step 1: Resize to 256x256 and normalize to [-1, 1] for discriminator # (images are expected to be in ImageNet normalized format, convert back first) # Actually, we need raw [0,1] images, then apply grad_transform # For efficiency, we'll denormalize and renormalize # Assume input is ImageNet normalized, denormalize first mean = torch.tensor([0.485, 0.456, 0.406], device=self.device).view(1, 3, 1, 1) std = torch.tensor([0.229, 0.224, 0.225], device=self.device).view(1, 3, 1, 1) images_01 = images * std + mean # Back to [0, 1] # Resize to 256x256 for discriminator if images_01.shape[-1] != 256 or images_01.shape[-2] != 256: images_256 = F.interpolate(images_01, size=(256, 256), mode='bilinear', align_corners=False) else: images_256 = images_01 # Normalize to [-1, 1] for StyleGAN discriminator images_disc = images_256 * 2.0 - 1.0 # Step 2: Compute discriminator gradients (requires grad, so no torch.no_grad()) grad_images = self._compute_discriminator_gradient(images_disc) # Step 3: Prepare gradient images for classifier # Center crop to 224x224 (matching original: Resize(256) -> CenterCrop(224)) # Since gradient is already 256x256, we just need the center crop with torch.no_grad(): if grad_images.shape[-1] == 256 and grad_images.shape[-2] == 256: # Center crop from 256 to 224 (crop 16 pixels from each side) crop_margin = (256 - 224) // 2 # 16 grad_images = grad_images[:, :, crop_margin:-crop_margin, crop_margin:-crop_margin] elif grad_images.shape[-1] != 224 or grad_images.shape[-2] != 224: # Fallback: resize then center crop if not 256x256 grad_images = F.interpolate(grad_images, size=(256, 256), mode='bilinear', align_corners=False) crop_margin = (256 - 224) // 2 grad_images = grad_images[:, :, crop_margin:-crop_margin, crop_margin:-crop_margin] # Apply ImageNet normalization grad_images = (grad_images - mean) / std # Step 4: Classify gradient images logits = self.model(grad_images) probs = torch.sigmoid(logits).squeeze(-1) preds = (probs > 0.5).int() return preds.cpu().tolist(), probs.cpu().tolist() @classmethod def get_transform(cls): """Get the transform for input images. Note: LGrad needs to perform its own preprocessing (discriminator gradient), so we just return a basic transform to get images to [0, 1] tensor format. The actual discriminator preprocessing happens in predict(). """ return T.Compose([ T.Resize(256), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) class HiFiNetWrapper: """Wrapper for HiFi-Net (Hierarchical Fine-Grained) detector.""" def __init__(self, weights_path: str, device: str = "cuda"): if not Path(weights_path).is_dir(): raise FileNotFoundError(weights_path) self.device = device # HiFi-Net requires specific imports and working directory setup hifi_path = METHODS_DIR / "HiFi_IFDL" # Add HiFi paths to front of sys.path sys.path.insert(0, str(hifi_path)) sys.path.insert(0, str(hifi_path / "models")) # Change to HiFi directory for proper weight loading original_cwd = os.getcwd() os.chdir(str(hifi_path)) try: from HiFi_Net import HiFi_Net self.hifi = HiFi_Net() finally: os.chdir(original_cwd) self.transform = T.Compose([ T.Resize((256, 256)), T.ToTensor(), ]) @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: """HiFi-Net processes images one at a time via detect() method.""" predictions = [] probabilities = [] # HiFi expects file paths, so we need to process tensors differently # Using the underlying FENet and SegNet directly images = images.to(self.device) # Normalize to [0, 1] range expected by HiFi if images.max() > 1.0: images = images / 255.0 output = self.hifi.FENet(images) mask1_fea, mask1_binary, out0, out1, out2, out3 = self.hifi.SegNet(output, images) # out3 contains classification logits (3 classes: 0=real, 1+=fake) # Following HiFi-Net's one_hot_label_new: prob = 1 - x[:,0] # This gives probability of being ANY fake class (not just class 1) probs = torch.softmax(out3, dim=1) fake_probs = 1 - probs[:, 0] # Probability of not being real preds = (fake_probs > 0.5).int() return preds.cpu().tolist(), fake_probs.cpu().tolist() class RINEWrapper: """Wrapper for RINE (Representations from Intermediate Encoder-blocks) detector.""" def __init__(self, weights_path: str, device: str = "cuda"): if not Path(weights_path).is_file(): raise FileNotFoundError(weights_path) self.device = device # Import RINE model rine_path = METHODS_DIR / "RINE" sys.path.insert(0, str(rine_path / "src")) from models import Model # Determine config based on weight file name if "1class" in weights_path: nproj, proj_dim = 4, 1024 elif "2class" in weights_path: nproj, proj_dim = 4, 128 elif "4class" in weights_path: nproj, proj_dim = 2, 1024 else: nproj, proj_dim = 4, 1024 # default self.model = Model( backbone=("ViT-L/14", 1024), nproj=nproj, proj_dim=proj_dim, device=device, ) # Load weights if os.path.exists(weights_path): state_dict = torch.load(weights_path, map_location=device) # RINE saves only trainable params, need special loading for name in state_dict: try: exec(f'self.model.{name.replace(".", "[", 1).replace(".", "].", 1)} = torch.nn.Parameter(state_dict["{name}"])') except: pass self.model = self.model.to(device) self.model.eval() # CLIP preprocessing self.transform = T.Compose([ T.Resize(224), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]), ]) @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: images = images.to(self.device) outputs = self.model(images) logits = outputs[0] # First element is classification logits probs = torch.sigmoid(logits).squeeze(-1) preds = (probs > 0.5).int() return preds.cpu().tolist(), probs.cpu().tolist() class DeeCLIPWrapper: """Wrapper for DeeCLIP (CLIP + LoRA + DeeFuser) detector.""" def __init__(self, weights_path: str, device: str = "cuda"): if not Path(weights_path).is_file(): raise FileNotFoundError(weights_path) self.device = device # Import DeeCLIP model deeclip_path = METHODS_DIR / "DeeCLIP" sys.path.insert(0, str(deeclip_path)) from model import DeeCLIP self.model = DeeCLIP(layer_indices=[1, 3, 5, 8, 10, 13, 15, 17, 19, 21, 22, 23]) # Load weights if os.path.exists(weights_path): state_dict = torch.load(weights_path, map_location="cpu") self.model.load_state_dict(state_dict, strict=False) self.model = self.model.to(device) self.model.eval() # CLIP ViT-L/14 preprocessing self.transform = T.Compose([ T.Resize(224), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]), ]) @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: images = images.to(self.device) # DeeCLIP returns (embeddings, logits) in train mode, (features, visual, logits) in eval outputs = self.model(images, train=False) logits = outputs[-1] # Last element is logits probs = torch.sigmoid(logits).squeeze(-1) preds = (probs > 0.5).int() return preds.cpu().tolist(), probs.cpu().tolist() class DIREWrapper: """Wrapper for DIRE (Diffusion Reconstruction Error) detector. Reference: "DIRE for Diffusion-Generated Image Detection" Wang et al., ICCV 2023 GitHub: https://github.com/ZhendongWang6/DIRE DIRE works by: 1. Encoding an image to latent space via DDIM reverse process 2. Reconstructing the image via DDIM forward process 3. Computing DIRE = |original - reconstruction| 4. Classifying the DIRE image with a binary classifier The key insight is that diffusion-generated images can be approximately reconstructed by a diffusion model, while real images cannot. Requirements: - ADM diffusion model weights for reconstruction (256x256_diffusion_uncond.pt) - DIRE classifier weights (trained on DIRE images) Note: Computing DIRE images is expensive (requires diffusion model inference). For efficiency, images are processed one at a time. """ # Default ADM model path # Use lsun_bedroom.pt to match the lsun_adm.pth classifier training DEFAULT_ADM_WEIGHTS = "models/lsun_bedroom.pt" def __init__(self, weights_path: str, device: str = "cuda", adm_weights_path: str = None): if not Path(weights_path).is_file(): raise FileNotFoundError(weights_path) self.device = device # Import DIRE classifier model import importlib.util resnet_path = METHODS_DIR / "DIRE" / "networks" / "resnet.py" spec = importlib.util.spec_from_file_location("resnet_dire", resnet_path) resnet_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(resnet_module) resnet50 = resnet_module.resnet50 self.model = resnet50(num_classes=1) if os.path.exists(weights_path): state_dict = torch.load(weights_path, map_location="cpu", weights_only=False) if "model" in state_dict: state_dict = state_dict["model"] self.model.load_state_dict(state_dict) self.model = self.model.to(device) self.model.eval() # Load ADM diffusion model for DIRE computation guided_diffusion_path = METHODS_DIR / "DIRE" / "guided-diffusion" sys.path.insert(0, str(guided_diffusion_path)) from guided_diffusion.script_util import ( model_and_diffusion_defaults, create_model_and_diffusion, ) # ADM model configuration for 256x256 unconditional model self.image_size = 256 model_config = model_and_diffusion_defaults() model_config.update({ "image_size": 256, "attention_resolutions": "32,16,8", "class_cond": False, "diffusion_steps": 1000, "dropout": 0.1, "learn_sigma": True, "noise_schedule": "linear", "num_channels": 256, "num_head_channels": 64, "num_res_blocks": 2, "resblock_updown": True, "use_fp16": True, "use_scale_shift_norm": True, "timestep_respacing": "ddim20", # Use DDIM with 20 steps for efficiency "use_checkpoint": False, "num_heads": 4, "num_heads_upsample": -1, "channel_mult": "", "use_kl": False, "predict_xstart": False, "rescale_timesteps": False, "rescale_learned_sigmas": False, "use_new_attention_order": False, }) self.diffusion_model, self.diffusion = create_model_and_diffusion(**model_config) # Load ADM weights if adm_weights_path is None: adm_weights_path = METHODS_DIR / "DIRE" / self.DEFAULT_ADM_WEIGHTS self.adm_loaded = False if os.path.exists(adm_weights_path): adm_state_dict = torch.load(adm_weights_path, map_location="cpu") self.diffusion_model.load_state_dict(adm_state_dict) self.diffusion_model = self.diffusion_model.to(device) self.diffusion_model.convert_to_fp16() self.diffusion_model.eval() self.adm_loaded = True print(f"Loaded ADM diffusion model from {adm_weights_path}") else: raise FileNotFoundError(adm_weights_path) # DDIM parameters self.real_step = 0 # Number of real denoising steps (0 = full reconstruction) # Transform for classifier input self.transform = T.Compose([ T.Resize(256), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) def _reshape_image(self, imgs: torch.Tensor) -> torch.Tensor: """Reshape images to 256x256 for diffusion model.""" if len(imgs.shape) == 3: imgs = imgs.unsqueeze(0) if imgs.shape[2] != imgs.shape[3]: # Center crop to square min_dim = min(imgs.shape[2], imgs.shape[3]) start_h = (imgs.shape[2] - min_dim) // 2 start_w = (imgs.shape[3] - min_dim) // 2 imgs = imgs[:, :, start_h:start_h+min_dim, start_w:start_w+min_dim] if imgs.shape[2] != self.image_size: imgs = F.interpolate(imgs, size=(self.image_size, self.image_size), mode="bicubic", align_corners=False) return imgs def _compute_dire(self, images: torch.Tensor) -> torch.Tensor: """Compute DIRE (Diffusion Reconstruction Error) images. Args: images: Batch of images [B, 3, H, W] in [-1, 1] range Returns: DIRE images [B, 3, H, W] in [0, 1] range """ batch_size = images.shape[0] # Step 1: DDIM reverse (encode image to latent) latent = self.diffusion.ddim_reverse_sample_loop( self.diffusion_model, (batch_size, 3, self.image_size, self.image_size), noise=images, clip_denoised=True, model_kwargs={}, real_step=self.real_step, ) # Step 2: DDIM forward (reconstruct from latent) # Note: Original compute_dire.sh uses --use_ddim True, so ddim_sample_loop is used. recons = self.diffusion.ddim_sample_loop( self.diffusion_model, (batch_size, 3, self.image_size, self.image_size), noise=latent, clip_denoised=True, model_kwargs={}, real_step=self.real_step, ) # Step 3: Compute DIRE as absolute difference # Scale from [-1, 1] to [0, 1] for the difference dire = torch.abs(images - recons) # Normalize DIRE to [0, 1] range (original uses dire * 255 / 2 / 255 = dire / 2) dire = dire / 2.0 return dire @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: """Predict if images are fake using DIRE method. Args: images: Batch of images [B, 3, H, W] - ImageNet normalized Returns: predictions: Binary predictions (0=real, 1=fake) probabilities: Probability of being fake """ images = images.to(self.device) if not self.adm_loaded: raise RuntimeError("DIRE requires the ADM reconstruction model") # Denormalize from ImageNet to [0, 1] mean = torch.tensor([0.485, 0.456, 0.406], device=self.device).view(1, 3, 1, 1) std = torch.tensor([0.229, 0.224, 0.225], device=self.device).view(1, 3, 1, 1) images_01 = images * std + mean # Reshape to 256x256 for diffusion model images_256 = self._reshape_image(images_01) # Convert to [-1, 1] range for diffusion model images_diff = images_256 * 2.0 - 1.0 # Compute DIRE images (process one at a time to avoid OOM) dire_images = [] for i in range(images_diff.shape[0]): img = images_diff[i:i+1] dire = self._compute_dire(img) dire_images.append(dire) dire_images = torch.cat(dire_images, dim=0) # Resize DIRE images for classifier (224x224) if dire_images.shape[-1] != 224 or dire_images.shape[-2] != 224: dire_images = F.interpolate(dire_images, size=(224, 224), mode='bilinear', align_corners=False) # Apply ImageNet normalization to DIRE images dire_images = (dire_images - mean) / std # Classify DIRE images logits = self.model(dire_images) probs = torch.sigmoid(logits).squeeze(-1) preds = (probs > 0.5).int() return preds.cpu().tolist(), probs.cpu().tolist() @classmethod def get_transform(cls): """Get the transform for input images.""" return T.Compose([ T.Resize(256), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) class WaRPADWrapper: """Wrapper for WaRPAD (Training-free detection via Cropping Robustness). Reference: "Training-free Detection of AI-generated images via Cropping Robustness" Link: https://arxiv.org/abs/2511.14030 IMPORTANT: WaRPAD requires high-resolution input (896x896) with BICUBIC interpolation. Use get_transform() to get the proper transform for the dataset. """ # Class-level constants for transform PREP_SIZE = 896 PATCH_SIZE = 224 def __init__(self, weights_path: str = None, device: str = "cuda"): self.device = device # Load DINOv2 model from torch.hub self.model = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14') self.model = self.model.to(device) self.model.eval() # WaRPAD parameters self.patch_size = self.PATCH_SIZE self.prep_size = self.PREP_SIZE self.noise_level = 0.1 # Haar wavelet transform try: from pytorch_wavelets import DWTForward, DWTInverse self.dwt = DWTForward(J=2, wave='haar').to(device) self.idwt = DWTInverse(wave='haar').to(device) self.use_wavelet = True except ImportError: raise ImportError("WaRPAD requires pytorch_wavelets; approximate perturbations are not supported") @classmethod def get_transform(cls) -> T.Compose: """Get the transform required for WaRPAD. WaRPAD requires 896x896 images resized with BICUBIC interpolation to preserve high-frequency details needed for detection. Returns: torchvision transform for WaRPAD preprocessing """ from PIL import Image return T.Compose([ T.Resize((cls.PREP_SIZE, cls.PREP_SIZE), interpolation=Image.BICUBIC), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) @classmethod def get_target_size(cls) -> int: """Get the target image size for WaRPAD.""" return cls.PREP_SIZE def _compute_warpad_score(self, image: torch.Tensor) -> Tuple[float, float]: """Compute WaRPAD score for a single image. Returns: Tuple of (fake_probability, raw_similarity_score) """ b, c, h, w = image.shape # Unfold into patches patches = image.unfold(2, self.patch_size, self.patch_size).unfold(3, self.patch_size, self.patch_size) patches = patches.reshape(b, c, -1, self.patch_size, self.patch_size).transpose(1, 2) patches = patches.reshape(-1, c, self.patch_size, self.patch_size) if self.use_wavelet: # Apply wavelet perturbation (original WaRPAD method) yl, yh = self.dwt(patches) yl_zeros = torch.zeros_like(yl) pert_hf = self.idwt((yl_zeros, yh)) perturbed = patches - self.noise_level * pert_hf else: raise RuntimeError("WaRPAD requires wavelet perturbations") # Get features outputs = self.model.forward_features(patches, None)["x_norm_clstoken"] perturbed_outputs = self.model.forward_features(perturbed, None)["x_norm_clstoken"] # Compute cosine similarity similarity = F.cosine_similarity(outputs, perturbed_outputs, dim=-1) similarity = similarity.reshape(b, -1) # WaRPAD uses mean similarity as score # fake images have LOWER similarity (less robust to perturbation) raw_score = similarity.mean().item() # Convert to fake probability # With wavelet perturbation, scores are typically in range [0.98, 1.0] # Lower similarity = more likely fake # Using a sigmoid-based conversion for smoother probability mapping if self.use_wavelet: # Threshold around 0.995, with sigmoid mapping threshold = 0.995 scale = 200.0 # Steepness of sigmoid fake_prob = 1.0 / (1.0 + np.exp(scale * (raw_score - threshold))) else: raise RuntimeError("WaRPAD requires wavelet perturbations") return fake_prob, raw_score @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: images = images.to(self.device) # Images should already be at prep_size (896x896) from the dataset transform # If not, resize with bicubic (fallback for compatibility) if images.shape[-1] != self.prep_size or images.shape[-2] != self.prep_size: images = F.interpolate(images, size=(self.prep_size, self.prep_size), mode='bicubic', align_corners=False) probabilities = [] for i in range(images.shape[0]): prob, _ = self._compute_warpad_score(images[i:i+1]) probabilities.append(prob) predictions = [1 if p > 0.5 else 0 for p in probabilities] return predictions, probabilities class RIGIDWrapper: """Wrapper for RIGID (Training-free detection via Noise Perturbation Robustness). Reference: https://github.com/IBM/RIGID Key insight: Real images are more robust to noise perturbation than AI-generated images. """ def __init__(self, weights_path: str = None, device: str = "cuda"): self.device = device # Load DINOv2 model (same as WaRPAD) self.model = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14') self.model = self.model.to(device) self.model.eval() # RIGID hyperparameter self.lamb = 0.05 self.transform = T.Compose([ T.Resize(224), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: images = images.to(self.device) # Resize to 224x224 if needed if images.shape[-1] != 224: images = F.interpolate(images, size=(224, 224), mode='bilinear', align_corners=False) # Get original features features = self.model(images) # Add Gaussian noise perturbation noise = torch.randn_like(images) perturbed = images + noise * self.lamb # Get perturbed features perturbed_features = self.model(perturbed) # Compute cosine similarity (same as original RIGID) similarity = F.cosine_similarity(features, perturbed_features, dim=-1) # Return raw similarity as score (matching original RIGID behavior) # Real images: higher similarity (more robust to noise) ~0.99 # Fake images: lower similarity (less robust) ~0.95-0.97 # # Since our evaluation expects fake_probs (higher = more likely fake), # we invert the similarity: fake_prob = 1 - similarity # This preserves the relative ordering for AUC computation fake_probs = 1.0 - similarity # Threshold at 0.5 corresponds to similarity of 0.5 # But for AUC evaluation, the threshold doesn't matter - only ranking matters preds = (fake_probs > 0.5).int() return preds.cpu().tolist(), fake_probs.cpu().tolist() class AEROBLADEWrapper: """Wrapper for AEROBLADE (Autoencoder Reconstruction-Based Latent Detector). AEROBLADE is a training-free method that detects AI-generated images by measuring autoencoder reconstruction error. The key insight is that images generated by latent diffusion models (like Stable Diffusion) have lower reconstruction error when passed through the same autoencoder used during generation. Reference: https://arxiv.org/abs/2401.17879 GitHub: https://github.com/jonasricker/aeroblade This implementation strictly follows the original codebase: - Uses lpips_vgg_2 (second VGG layer) as distance metric (best in reference implementation) - Uses SD1, SD2, and Kandinsky 2.1 autoencoders - Takes maximum distance across all autoencoders """ def __init__(self, weights_path: str = None, device: str = "cuda"): self.device = device # Add AEROBLADE to path aeroblade_path = METHODS_DIR / "AEROBLADE" / "src" if str(aeroblade_path) not in sys.path: sys.path.insert(0, str(aeroblade_path)) # Import LPIPS - use spatial=True to get per-layer outputs # Following aeroblade/distances.py _PatchedLPIPS import lpips import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") self.lpips_model = lpips.LPIPS(net='vgg', spatial=True).to(device) self.lpips_model.eval() # Original AEROBLADE code stores: lpips_layers[0] = sum, lpips_layers[i+1] = layer i # So lpips_vgg_2 accesses lpips_layers[2] = layers_batch[1] = second VGG layer (0-indexed: 1) # Standard LPIPS returns layers directly without sum prefix, so we use index 1 self.lpips_layer = 1 # Second VGG layer (0-indexed) as in lpips_vgg_2 # Load VAE autoencoders from Stable Diffusion # Following run_aeroblade.py defaults: # - CompVis/stable-diffusion-v1-1 (SD1) # - stabilityai/stable-diffusion-2-base (SD2) # - kandinsky-community/kandinsky-2-1 (KD2.1) from diffusers import AutoPipelineForImage2Image from diffusers.models import VQModel self.autoencoders = {} self.ae_types = {} # 'vae' or 'movq' # Note: stabilityai/stable-diffusion-2-base is gated on HuggingFace, # so we use Manojb/stable-diffusion-2-1-base as a community mirror repo_ids = [ "CompVis/stable-diffusion-v1-1", # SD1 "Manojb/stable-diffusion-2-1-base", # SD2 (community mirror) "kandinsky-community/kandinsky-2-1", # KD2.1 ] print(f"Loading AEROBLADE autoencoders (following original implementation)...") for repo_id in repo_ids: try: # Load full pipeline and extract AE (as in aeroblade/image.py) pipe = AutoPipelineForImage2Image.from_pretrained( repo_id, torch_dtype=torch.float16, use_safetensors=True, variant="fp16" if "kandinsky-2" not in repo_id else None, ) # Extract autoencoder from pipeline if hasattr(pipe, "vae"): ae = pipe.vae ae_type = "vae" # Upcast VAE if available (for numerical stability) if hasattr(pipe, "upcast_vae"): pipe.upcast_vae() elif hasattr(pipe, "movq"): ae = pipe.movq ae_type = "movq" else: raise RuntimeError(f"No autoencoder found in {repo_id}") ae = ae.to(device) ae.eval() self.autoencoders[repo_id] = ae self.ae_types[repo_id] = ae_type print(f" Loaded: {repo_id} ({ae_type})") # Clean up pipeline to save memory del pipe torch.cuda.empty_cache() except Exception as e: raise RuntimeError(f"Required AEROBLADE autoencoder failed to load: {repo_id}") from e if not self.autoencoders: raise RuntimeError("Failed to load any autoencoders for AEROBLADE") def _compute_lpips_layer(self, img_a: torch.Tensor, img_b: torch.Tensor) -> torch.Tensor: """Compute LPIPS distance for a specific layer. Following aeroblade/distances.py _PatchedLPIPS and LPIPS class. Returns the distance for lpips_vgg_2 (second VGG layer, 0-indexed as 1). """ # LPIPS expects inputs in [0, 1] with normalize=True, or [-1, 1] without # We pass [0, 1] images and let LPIPS normalize them with torch.no_grad(): # Get per-layer distances using retPerLayer # Standard LPIPS returns (total, [layer0, layer1, layer2, ...]) total, layers = self.lpips_model(img_a, img_b, retPerLayer=True, normalize=True) # Get the second VGG layer (index 1) matching lpips_vgg_2 from original layer_dist = layers[self.lpips_layer] # Average over spatial dimensions (as in original when spatial=False for output) layer_dist = layer_dist.mean(dim=(2, 3)) return layer_dist.squeeze() def _compute_reconstruction_error(self, images: torch.Tensor, ae, ae_type: str) -> torch.Tensor: """Compute reconstruction error through autoencoder. Following aeroblade/image.py compute_reconstructions(). """ from diffusers.models import VQModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img import retrieve_latents # Normalize to [-1, 1] as expected by VAE (as in original: images * 2.0 - 1.0) images_norm = images * 2.0 - 1.0 # Encode - use retrieve_latents for proper handling (as in original) generator = torch.Generator(device=self.device).manual_seed(1) latents = retrieve_latents(ae.encode(images_norm), generator=generator) # Get decode dtype from model if hasattr(ae, 'post_quant_conv'): decode_dtype = next(iter(ae.post_quant_conv.parameters())).dtype else: decode_dtype = images.dtype # Decode if isinstance(ae, VQModel): reconstructions = ae.decode( latents.to(decode_dtype), force_not_quantize=True, return_dict=False )[0] else: reconstructions = ae.decode(latents.to(decode_dtype), return_dict=False)[0] # De-normalize to [0, 1] reconstructions = (reconstructions / 2 + 0.5).clamp(0, 1) images_01 = images.clamp(0, 1) # Compute LPIPS distance for the specified layer lpips_dist = self._compute_lpips_layer(images_01.float(), reconstructions.float()) return lpips_dist @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: """Predict if images are fake based on reconstruction error. AEROBLADE's key insight: - Real images: HIGH reconstruction error (hard to reconstruct) - AI-generated images: LOW reconstruction error (easy to reconstruct) We invert this to get fake probability: - Low error → High fake probability - High error → Low fake probability Args: images: Batch of images [B, 3, H, W] in ImageNet-normalized format (the standard format from the evaluation pipeline) Returns: predictions: Binary predictions (0=real, 1=fake) probabilities: Probability of being fake """ images = images.to(self.device, dtype=torch.float16) # De-normalize from ImageNet normalization back to [0, 1] range # The dataset applies: (img - mean) / std, so we reverse: img * std + mean mean = torch.tensor([0.485, 0.456, 0.406], device=self.device, dtype=torch.float16).view(1, 3, 1, 1) std = torch.tensor([0.229, 0.224, 0.225], device=self.device, dtype=torch.float16).view(1, 3, 1, 1) images = images * std + mean # Back to [0, 1] range images = images.clamp(0, 1) # Ensure valid range # Resize to 512x512 if needed (AEROBLADE expects 512x512 images) if images.shape[-1] != 512 or images.shape[-2] != 512: images = F.interpolate(images, size=(512, 512), mode='bilinear', align_corners=False) # Compute reconstruction error for each autoencoder and take maximum # Following original: maximum distance across all autoencoders max_errors = None for repo_id, ae in self.autoencoders.items(): errors = self._compute_reconstruction_error(images, ae, self.ae_types[repo_id]) if max_errors is None: max_errors = errors else: max_errors = torch.maximum(max_errors, errors) # Convert reconstruction error to fake probability # AEROBLADE's key insight: lower reconstruction error → more likely AI-generated # Because generated images come from the same latent space as the autoencoder # # Original AEROBLADE returns raw (negated) distances for AUC computation # We follow the same approach: invert error so higher value = more likely fake # This preserves ranking for AUC and doesn't rely on arbitrary thresholds fake_probs = 1.0 - max_errors.float() fake_probs = torch.clamp(fake_probs, 0.0, 1.0) preds = (fake_probs > 0.5).int() return preds.cpu().tolist(), fake_probs.cpu().tolist() class FatFormerWrapper: """Wrapper for FatFormer (Forgery-Aware Transformer) detector. Reference: https://arxiv.org/abs/2303.17111 GitHub: https://github.com/Michel-liu/FatFormer FatFormer uses CLIP ViT-L/14 as backbone with: - Forgery-aware adapters that process spatial and frequency domain features - Language-guided alignment for improved generalization Requirements: - pytorch_wavelets: pip install pytorch_wavelets - CLIP ViT-L/14 weights at: FatFormer/pretrained/ViT-L-14.pt (Download from: https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt) """ def __init__(self, weights_path: str, device: str = "cuda"): if not Path(weights_path).is_file(): raise FileNotFoundError(weights_path) self.device = device # FatFormer requires specific imports fatformer_path = METHODS_DIR / "FatFormer" # Save original cwd and change to FatFormer directory for proper import original_cwd = os.getcwd() os.chdir(str(fatformer_path)) # Add FatFormer to path sys.path.insert(0, str(fatformer_path)) try: # Create args namespace with required parameters class Args: backbone = "CLIP:ViT-L/14" num_classes = 2 num_vit_adapter = 3 num_context_embedding = 8 init_context_embedding = "" hidden_dim = 768 clip_vision_width = 1024 frequency_encoder_layer = 2 decoder_layer = 4 num_heads = 12 args = Args() # Import and build model from models import build_model self.model = build_model(args) # Load checkpoint if os.path.exists(weights_path): checkpoint = torch.load(weights_path, map_location="cpu", weights_only=False) if "model" in checkpoint: state_dict = checkpoint["model"] else: state_dict = checkpoint self.model.load_state_dict(state_dict, strict=False) self.model = self.model.to(device) self.model.eval() finally: os.chdir(original_cwd) # FatFormer preprocessing (from utils/dataset.py) # Uses ImageNet normalization, resize to 256, center crop to 224 self.transform = T.Compose([ T.Resize((256, 256)), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: """Predict if images are fake. Args: images: Batch of images [B, 3, H, W] Returns: predictions: Binary predictions (0=real, 1=fake) probabilities: Probability of being fake """ images = images.to(self.device) # Resize if needed if images.shape[-1] != 224 or images.shape[-2] != 224: images = F.interpolate(images, size=(224, 224), mode='bilinear', align_corners=False) # Forward pass outputs = self.model(images) # FatFormer outputs logits for 2 classes: [real, fake] # Apply softmax and get fake probability (class 1) probs = torch.softmax(outputs, dim=1) fake_probs = probs[:, 1] preds = (fake_probs > 0.5).int() return preds.cpu().tolist(), fake_probs.cpu().tolist() class AIDEWrapper: """Wrapper for AIDE (AI-generated Image DEtector with Hybrid Features).""" def __init__(self, weights_path: str, device: str = "cuda"): if not Path(weights_path).is_file(): raise FileNotFoundError(weights_path) self.device = device # Add AIDE path to sys.path for proper module resolution aide_path = METHODS_DIR / "AIDE" # Save original sys.path original_path = sys.path.copy() # Add necessary paths sys.path.insert(0, str(aide_path)) sys.path.insert(0, str(aide_path / "models")) sys.path.insert(0, str(aide_path / "data")) try: # Import AIDE components from data.dct import DCT_base_Rec_Module # Need to import srm_filter_kernel first to resolve relative import import srm_filter_kernel import sys as _sys _sys.modules['models.srm_filter_kernel'] = srm_filter_kernel # Now import AIDE model import importlib.util aide_model_path = aide_path / "models" / "AIDE.py" # Read and modify the source to fix relative import with open(aide_model_path, 'r') as f: source = f.read() # Replace relative import with absolute modified_source = source.replace( 'from .srm_filter_kernel import all_normalized_hpf_list', 'from srm_filter_kernel import all_normalized_hpf_list' ) # Execute the modified source exec_globals = {'__name__': 'aide_model', '__file__': str(aide_model_path)} exec(compile(modified_source, str(aide_model_path), 'exec'), exec_globals) AIDE_Model = exec_globals['AIDE_Model'] finally: # Restore original sys.path to avoid polluting the namespace pass # Keep paths for model to work properly # Initialize DCT module for preprocessing self.dct = DCT_base_Rec_Module() # Build model without loading pretrained weights (we'll load from checkpoint) self.model = AIDE_Model(resnet_path=None, convnext_path=None) # Load checkpoint if os.path.exists(weights_path): state_dict = torch.load(weights_path, map_location="cpu", weights_only=False) if "model" in state_dict: state_dict = state_dict["model"] # Load state dict (may need to handle prefix differences) self.model.load_state_dict(state_dict, strict=False) self.model = self.model.to(device) self.model.eval() # Move DCT module to device self.dct = self.dct.to(device) # Transform: resize to 256x256 and normalize self.transform = T.Compose([ T.Resize((256, 256)), T.ToTensor(), ]) # Normalization for the final input self.normalize = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) def _preprocess_batch(self, images: torch.Tensor) -> torch.Tensor: """Preprocess a batch of images for AIDE. AIDE expects input of shape [B, 5, 3, 256, 256] where: - images[:, 0] = x_minmin (DCT min-frequency patch) - images[:, 1] = x_maxmax (DCT max-frequency patch) - images[:, 2] = x_minmin1 (DCT second min-frequency patch) - images[:, 3] = x_maxmax1 (DCT second max-frequency patch) - images[:, 4] = x_0 (original image, normalized) """ batch_size = images.shape[0] stacked_inputs = [] for i in range(batch_size): img = images[i] # [3, H, W] # Resize to 256x256 if needed if img.shape[-1] != 256 or img.shape[-2] != 256: img = F.interpolate(img.unsqueeze(0), size=(256, 256), mode='bilinear', align_corners=False).squeeze(0) # Apply DCT to get frequency-based patches # DCT expects [C, H, W] and returns 4 tensors of shape [3, 32, 32] x_minmin, x_maxmax, x_minmin1, x_maxmax1 = self.dct(img) # Resize DCT outputs from 32x32 to 256x256 # Add batch dimension, interpolate, then remove x_minmin = F.interpolate(x_minmin.unsqueeze(0), size=(256, 256), mode='bilinear', align_corners=False).squeeze(0) x_maxmax = F.interpolate(x_maxmax.unsqueeze(0), size=(256, 256), mode='bilinear', align_corners=False).squeeze(0) x_minmin1 = F.interpolate(x_minmin1.unsqueeze(0), size=(256, 256), mode='bilinear', align_corners=False).squeeze(0) x_maxmax1 = F.interpolate(x_maxmax1.unsqueeze(0), size=(256, 256), mode='bilinear', align_corners=False).squeeze(0) # Normalize all inputs x_minmin = self.normalize(x_minmin) x_maxmax = self.normalize(x_maxmax) x_minmin1 = self.normalize(x_minmin1) x_maxmax1 = self.normalize(x_maxmax1) x_0 = self.normalize(img) # Stack: [5, 3, 256, 256] stacked = torch.stack([x_minmin, x_maxmax, x_minmin1, x_maxmax1, x_0], dim=0) stacked_inputs.append(stacked) # Stack batch: [B, 5, 3, 256, 256] return torch.stack(stacked_inputs, dim=0) @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: images = images.to(self.device) # Preprocess batch inputs = self._preprocess_batch(images) # Forward pass logits = self.model(inputs) # [B, 2] # Get probabilities (class 1 = fake) probs = torch.softmax(logits, dim=1) fake_probs = probs[:, 1] preds = (fake_probs > 0.5).int() return preds.cpu().tolist(), fake_probs.cpu().tolist() class AlignedForensicsWrapper: """Wrapper for AlignedForensics detector. Reference: "Aligned Datasets Improve Detection of Latent Diffusion-Generated Images" Rajan et al., ICLR 2025 GitHub: https://github.com/AniSundar18/AlignedForensics Key Idea: Training fake image detectors on aligned (same content) real/fake pairs reduces spurious correlations and improves generalization. Uses ResNet-50 with modified first layer (stride=1 instead of 2) for better spatial resolution. """ def __init__(self, weights_path: str, device: str = "cuda"): if not Path(weights_path).is_file(): raise FileNotFoundError(weights_path) self.device = device if not os.path.exists(weights_path): raise FileNotFoundError(f"AlignedForensics checkpoint not found: {weights_path}") # Add AlignedForensics paths aligned_path = METHODS_DIR / "AlignedForensics" / "training_code" if str(aligned_path) not in sys.path: sys.path.insert(0, str(aligned_path)) # Import model architecture from networks import create_architecture, load_weights # Create ResNet-50 with no downsampling in first layer self.model = create_architecture( "res50nodown", pretrained=False, num_classes=1, dropout=0.5 ) # Load weights if os.path.exists(weights_path): load_weights(self.model, weights_path) print(f"Loaded AlignedForensics checkpoint from {weights_path}") self.model = self.model.to(device) self.model.eval() # AlignedForensics uses ImageNet normalization self.transform = T.Compose([ T.Resize(256), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: """Predict if images are fake. Args: images: Batch of images [B, 3, H, W] Returns: predictions: Binary predictions (0=real, 1=fake) probabilities: Probability of being fake """ images = images.to(self.device) # Forward pass - model returns (logits, features) tuple outputs = self.model(images) if isinstance(outputs, tuple): logits = outputs[0] # First element is logits else: logits = outputs # Get last dimension if multi-dimensional while len(logits.shape) > 1: logits = logits.mean(dim=-1) if logits.shape[-1] > 1 else logits.squeeze(-1) probs = torch.sigmoid(logits) preds = (probs > 0.5).int() return preds.cpu().tolist(), probs.cpu().tolist() class _SVDResidualLinear(nn.Module): """Custom module to represent the residual using SVD components. Used by EffortWrapper for SVD-based orthogonal decomposition of linear layers. """ def __init__(self, in_features, out_features, r, bias=True, init_weight=None): super(_SVDResidualLinear, self).__init__() self.in_features = in_features self.out_features = out_features self.r = r self.weight_main = nn.Parameter(torch.Tensor(out_features, in_features), requires_grad=False) if init_weight is not None: self.weight_main.data.copy_(init_weight) else: nn.init.kaiming_uniform_(self.weight_main, a=np.sqrt(5)) if bias: self.bias = nn.Parameter(torch.Tensor(out_features)) nn.init.zeros_(self.bias) else: self.register_parameter('bias', None) def forward(self, x): if hasattr(self, 'U_residual') and hasattr(self, 'V_residual') and self.S_residual is not None: residual_weight = self.U_residual @ torch.diag(self.S_residual) @ self.V_residual weight = self.weight_main + residual_weight else: weight = self.weight_main return F.linear(x, weight, self.bias) def _replace_with_svd_residual(module, r): """Replace nn.Linear with SVDResidualLinear for Effort method.""" if isinstance(module, nn.Linear): in_features = module.in_features out_features = module.out_features bias = module.bias is not None new_module = _SVDResidualLinear(in_features, out_features, r, bias=bias, init_weight=module.weight.data.clone()) if bias and module.bias is not None: new_module.bias.data.copy_(module.bias.data) U, S, Vh = torch.linalg.svd(module.weight.data, full_matrices=False) r = min(r, len(S)) U_r = U[:, :r] S_r = S[:r] Vh_r = Vh[:r, :] weight_main = U_r @ torch.diag(S_r) @ Vh_r new_module.weight_main.data.copy_(weight_main) U_residual = U[:, r:] S_residual = S[r:] Vh_residual = Vh[r:, :] if len(S_residual) > 0: new_module.S_residual = nn.Parameter(S_residual.clone()) new_module.U_residual = nn.Parameter(U_residual.clone()) new_module.V_residual = nn.Parameter(Vh_residual.clone()) else: new_module.S_residual = None new_module.U_residual = None new_module.V_residual = None return new_module return module def _apply_svd_residual_to_self_attn(model, r): """Apply SVD residual decomposition to self-attention layers in a model.""" for name, module in model.named_children(): if 'self_attn' in name: for sub_name, sub_module in module.named_modules(): if isinstance(sub_module, nn.Linear): parent_module = module sub_module_names = sub_name.split('.') for module_name in sub_module_names[:-1]: parent_module = getattr(parent_module, module_name) setattr(parent_module, sub_module_names[-1], _replace_with_svd_residual(sub_module, r)) else: _apply_svd_residual_to_self_attn(module, r) for param_name, param in model.named_parameters(): if any(x in param_name for x in ['S_residual', 'U_residual', 'V_residual']): param.requires_grad = True else: param.requires_grad = False return model class EffortWrapper: """Wrapper for Effort (Efficient Orthogonal Modeling) detector. Reference: "Effort: Efficient Orthogonal Modeling for Generalizable AI-Generated Image Detection" Yan et al., ICML 2025 Oral GitHub: https://github.com/YZY-stack/Effort-AIGI-Detection Effort uses SVD decomposition of CLIP ViT-L/14 self-attention weights: - Main weights (frozen): Top-r singular components - Residual weights (trainable): Remaining singular components This preserves generalizable features while learning task-specific patterns. Architecture: CLIP ViT-L/14 + SVD residual decomposition + Linear head (2 classes) """ def __init__(self, weights_path: str, device: str = "cuda"): if not Path(weights_path).is_file(): raise FileNotFoundError(weights_path) self.device = device from transformers import CLIPModel # Load CLIP ViT-L/14 from HuggingFace print("Loading CLIP ViT-L/14 for Effort...") clip_model = CLIPModel.from_pretrained("openai/clip-vit-large-patch14") # Apply SVD to self_attn layers (r=1024-1=1023 keeps top 1023 singular values) clip_model.vision_model = _apply_svd_residual_to_self_attn(clip_model.vision_model, r=1024-1) # Create the detector module self.model = nn.Module() self.model.backbone = clip_model.vision_model self.model.head = nn.Linear(1024, 2) # Load weights if os.path.exists(weights_path): checkpoint = torch.load(weights_path, map_location="cpu", weights_only=False) state_dict = checkpoint.get("state_dict", checkpoint) # Remove "module." prefix if present (from DataParallel training) new_state_dict = {} for k, v in state_dict.items(): if k.startswith("module."): k = k[7:] new_state_dict[k] = v # Load backbone and head weights backbone_state = {k.replace("backbone.", ""): v for k, v in new_state_dict.items() if k.startswith("backbone.")} head_state = {k.replace("head.", ""): v for k, v in new_state_dict.items() if k.startswith("head.")} if backbone_state: self.model.backbone.load_state_dict(backbone_state, strict=False) if head_state: self.model.head.load_state_dict(head_state, strict=True) print(f"Loaded Effort checkpoint from {weights_path}") self.model = self.model.to(device) self.model.eval() @staticmethod def get_transform(): """Return the CLIP ViT-L/14 preprocessing transform.""" return T.Compose([ T.Resize((224, 224)), T.ToTensor(), T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]), ]) @staticmethod def get_target_size(): """Return the target image size.""" return 224 @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: """Predict if images are fake. Args: images: Batch of images [B, 3, H, W] Returns: predictions: Binary predictions (0=real, 1=fake) probabilities: Probability of being fake """ images = images.to(self.device) # Resize if needed if images.shape[-1] != 224 or images.shape[-2] != 224: images = F.interpolate(images, size=(224, 224), mode='bilinear', align_corners=False) # Forward pass through backbone features = self.model.backbone(images)['pooler_output'] # Classification logits = self.model.head(features) # Get probabilities (class 1 = fake) probs = torch.softmax(logits, dim=1) fake_probs = probs[:, 1] preds = (fake_probs > 0.5).int() return preds.cpu().tolist(), fake_probs.cpu().tolist() class NPRWrapper: """Wrapper for NPR (Nearest-neighbor Pattern Representation) detector. Reference: "Rethinking the Up-Sampling Operations in CNN-based Generative Network for Generalizable Deepfake Detection" Tan et al., CVPR 2024 GitHub: https://github.com/chuangchuangtan/NPR-DeepfakeDetection Key Idea: Detect artifacts from upsampling operations in CNN-based generators. The NPR representation is computed as the difference between the original image and the nearest-neighbor downsampled-then-upsampled version, highlighting interpolation patterns specific to generative models. """ def __init__(self, weights_path: str, device: str = "cuda"): if not Path(weights_path).is_file(): raise FileNotFoundError(weights_path) self.device = device # Import NPR model import importlib.util resnet_path = METHODS_DIR / "NPR" / "networks" / "resnet.py" spec = importlib.util.spec_from_file_location("resnet_npr", resnet_path) resnet_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(resnet_module) resnet50 = resnet_module.resnet50 self.model = resnet50(num_classes=1) if os.path.exists(weights_path): state_dict = torch.load(weights_path, map_location="cpu", weights_only=False) # Handle different checkpoint formats if "model" in state_dict: state_dict = state_dict["model"] # Remove "module." prefix from DataParallel training new_state_dict = {} for k, v in state_dict.items(): if k.startswith("module."): new_state_dict[k[7:]] = v # Remove "module." prefix else: new_state_dict[k] = v self.model.load_state_dict(new_state_dict, strict=True) self.model = self.model.to(device) self.model.eval() # NPR uses ImageNet normalization, resize to 256, center crop to 224 self.transform = T.Compose([ T.Resize(256), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: """Predict if images are fake. Args: images: Batch of images [B, 3, H, W] Returns: predictions: Binary predictions (0=real, 1=fake) probabilities: Probability of being fake """ images = images.to(self.device) # Ensure image dimensions are even (required by NPR's interpolation) n, c, h, w = images.shape if h % 2 == 1: images = images[:, :, :-1, :] if w % 2 == 1: images = images[:, :, :, :-1] logits = self.model(images) probs = torch.sigmoid(logits).squeeze(-1) preds = (probs > 0.5).int() return preds.cpu().tolist(), probs.cpu().tolist() class ManifoldBiasWrapper: """Wrapper for Manifold Induced Biases detector. Reference: "Manifold Induced Biases for Zero-shot and Few-shot Detection of Generated Images" Brokman et al., ICLR 2025 GitHub: https://github.com/JonathanBrok/Manifold-Induced-Biases-for-Zero-shot-and-Few-shot-Detection-of-Generated-Images This is a training-free zero-shot method that: 1. Uses Stable Diffusion v1.4 (UNet, VAE) to analyze diffusion behavior 2. Uses CLIP to measure similarity in embedding space 3. Computes a criterion score based on manifold-induced biases Higher criterion score = more likely AI-generated Lower criterion score = more likely real """ def __init__(self, weights_path: str = None, device: str = "cuda"): self.device = device # Add ManifoldBias to path manifold_path = METHODS_DIR / "ManifoldBias" if str(manifold_path) not in sys.path: sys.path.insert(0, str(manifold_path)) # Import the criterion functions from manifold_bias_criteria import ( get_sd_v14_model, factory_sdv14_based_criterion, ) from transformers import CLIPModel, AutoImageProcessor # Store factory function for lazy criterion creation self.factory_sdv14_based_criterion = factory_sdv14_based_criterion # Load SD v1.4 models print("Loading ManifoldBias models (SD v1.4, CLIP)...") print(" This may take a while on first run (downloading models)...") ( self.unet, self.tokenizer, self.text_encoder, self.vae, self.scheduler, ) = get_sd_v14_model(device) # Load CLIP model self.cos = torch.nn.CosineSimilarity(dim=1, eps=1e-6).to(device) self.processor = AutoImageProcessor.from_pretrained("openai/clip-vit-large-patch14") self.clip = CLIPModel.from_pretrained("openai/clip-vit-large-patch14").to(device) self.num_noise = 8 self.time_frac = 0.01 # Fraction of diffusion time self.epsilon_reg = 1e-8 # Regularization parameter self.siz = 512 # Image size # Create the criterion function with a generic prompt (skip LLaVA auto-captioning) # Using a generic prompt is faster and avoids LLaVA compatibility issues self.criterion_fn = self.factory_sdv14_based_criterion( device, self.num_noise, self.epsilon_reg, self.time_frac, self.tokenizer, self.text_encoder, None, # image_to_text - not used when prompts_list is provided self.vae, self.scheduler, self.unet, self.clip, self.processor, self.cos, self.siz, prompts_list=["a photograph"], # Generic prompt used for all images ) print("ManifoldBias models loaded successfully") @torch.no_grad() def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]: """Predict if images are fake based on manifold-induced biases. The criterion score indicates: - Higher values: more likely AI-generated - Lower values: more likely real We convert this to fake probability using a sigmoid centered at empirical threshold. Note: To avoid OOM with num_noise=8, images are processed one at a time. Args: images: Batch of images [B, 3, H, W] in [0, 1] range Returns: predictions: Binary predictions (0=real, 1=fake) probabilities: Probability of being fake """ images = images.to(self.device) # Process images one at a time to avoid OOM with num_noise=8 # With num_noise=8, effective batch size is 8 per image which requires significant VRAM criterion_scores = [] for i in range(images.shape[0]): # Clear cache before each image torch.cuda.empty_cache() # Convert single image from [C, H, W] [0,1] to [H, W, C] [0,255] tensor img = images[i] # [C, H, W] img = img.permute(1, 2, 0) # [H, W, C] img = (img * 255).clamp(0, 255).to(torch.uint8) # Run the criterion on single image results = self.criterion_fn([img]) criterion_scores.append(results[0]["criterion"]) # Convert criterion to fake probability # Empirical threshold around 0.5-0.7 based on examples threshold = 0.6 scale = 5.0 # steepness of sigmoid fake_probs = [] preds = [] for score in criterion_scores: # Sigmoid mapping: score > threshold → high fake prob prob = 1.0 / (1.0 + np.exp(-scale * (score - threshold))) fake_probs.append(float(prob)) preds.append(1 if prob > 0.5 else 0) return preds, fake_probs def evaluate_model( model_wrapper, dataset: ACIDEvalDataset, batch_size: int = 32, num_workers: int = 4, ) -> Dict[str, float]: """ Evaluate a model on a dataset. Args: model_wrapper: Model wrapper with predict() method dataset: Evaluation dataset batch_size: Batch size for evaluation num_workers: Number of data loading workers Returns: Dictionary of metrics """ loader = DataLoader( dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers, pin_memory=True, ) all_preds = [] all_labels = [] all_probs = [] for images, labels, _ in tqdm(loader, desc="Evaluating"): preds, probs = model_wrapper.predict(images) all_preds.extend(preds) all_labels.extend(labels.tolist()) all_probs.extend(probs) return compute_metrics(all_preds, all_labels, all_probs) def evaluate_per_model( model_wrapper, fake_root: str, model_mapping: Optional[Dict] = None, samples_per_model: int = 100, batch_size: int = 32, num_workers: int = 4, ) -> Dict[int, Dict[str, float]]: """ Evaluate model on each AI model separately. Args: model_wrapper: Model wrapper with predict() method fake_root: Root directory of fake images model_mapping: Optional model mapping samples_per_model: Samples per model batch_size: Batch size num_workers: Number of workers Returns: Dictionary mapping model_id to metrics """ datasets = create_per_model_datasets(fake_root, model_mapping, samples_per_model) results = {} for model_id, dataset in tqdm(datasets.items(), desc="Evaluating per model"): if len(dataset) > 0: metrics = evaluate_model(model_wrapper, dataset, batch_size, num_workers) results[model_id] = metrics return results def evaluate_per_model_with_real( model_wrapper, fake_datasets: Dict[int, ACIDEvalDataset], real_preds: List[int], real_probs: List[float], real_labels: List[int], batch_size: int = 32, num_workers: int = 4, ) -> Dict[int, Dict[str, float]]: """ Evaluate model on each AI model paired with real images for proper AUC/AP calculation. For training-free methods, AUC/AP require both classes (real and fake) to be meaningful. This function pairs each AI model's fake images with the same set of real images. Args: model_wrapper: Model wrapper with predict() method fake_datasets: Dictionary mapping model_id to fake image dataset real_preds: Pre-computed predictions for real images real_probs: Pre-computed probabilities for real images real_labels: Labels for real images (all 0s) batch_size: Batch size num_workers: Number of workers Returns: Dictionary mapping model_id to metrics (with proper AUC/AP) """ results = {} for model_id, fake_dataset in tqdm(fake_datasets.items(), desc="Evaluating per model (with real)"): if len(fake_dataset) == 0: continue # Get predictions for this model's fake images loader = DataLoader( fake_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers, pin_memory=True, ) fake_preds = [] fake_probs = [] fake_labels = [] for images, labels, _ in loader: preds, probs = model_wrapper.predict(images) fake_preds.extend(preds) fake_probs.extend(probs) fake_labels.extend(labels.tolist()) # Combine real and fake for this model all_preds = real_preds + fake_preds all_probs = real_probs + fake_probs all_labels = real_labels + fake_labels # Compute metrics with both classes present metrics = compute_metrics(all_preds, all_labels, all_probs) results[model_id] = metrics return results def save_results( results: Dict[int, Dict[str, float]], model_mapping: Optional[Dict], output_path: str, method_name: str, ): """Save evaluation results to CSV.""" with open(output_path, "w", newline="") as f: writer = csv.writer(f) writer.writerow([ "method", "model_id", "model_name", "accuracy", "precision", "recall", "f1", "auc", "ap", "timestamp" ]) timestamp = datetime.now().isoformat() for model_id, metrics in results.items(): model_name = get_model_name(model_id, model_mapping) if model_mapping else f"Model_{model_id}" writer.writerow([ method_name, model_id, model_name, f"{metrics.get('accuracy', 0):.4f}", f"{metrics.get('precision', 0):.4f}", f"{metrics.get('recall', 0):.4f}", f"{metrics.get('f1', 0):.4f}", f"{metrics.get('auc', 0):.4f}", f"{metrics.get('ap', 0):.4f}", timestamp, ]) def print_summary(results: Dict[int, Dict[str, float]], model_mapping: Optional[Dict], method_name: str = ""): """Print summary statistics. For training-free methods (AEROBLADE, WaRPAD, RIGID, ManifoldBias), AUC and AP are the primary metrics since accuracy depends on arbitrary thresholds. """ if not results: print("No results to summarize.") return is_training_free = method_name in TRAINING_FREE_METHODS accuracies = [m["accuracy"] for m in results.values()] f1_scores = [m["f1"] for m in results.values()] aucs = [m.get("auc", 0) for m in results.values()] aps = [m.get("ap", 0) for m in results.values()] print("\n" + "=" * 60) print("EVALUATION SUMMARY") if is_training_free: print(f"[Training-free method: {method_name}]") print("[Primary metrics: AUC and AP (accuracy uses arbitrary threshold)]") print("=" * 60) print(f"Number of models evaluated: {len(results)}") # For training-free methods, show AUC/AP first as primary metrics if is_training_free: print(f"\nAUC (primary):") print(f" Mean: {sum(aucs) / len(aucs):.4f}") print(f" Min: {min(aucs):.4f}") print(f" Max: {max(aucs):.4f}") print(f"\nAP (primary):") print(f" Mean: {sum(aps) / len(aps):.4f}") print(f" Min: {min(aps):.4f}") print(f" Max: {max(aps):.4f}") print(f"\nAccuracy (arbitrary threshold, for reference only):") print(f" Mean: {sum(accuracies) / len(accuracies):.4f}") else: print(f"\nAccuracy:") print(f" Mean: {sum(accuracies) / len(accuracies):.4f}") print(f" Min: {min(accuracies):.4f}") print(f" Max: {max(accuracies):.4f}") print(f"\nF1 Score:") print(f" Mean: {sum(f1_scores) / len(f1_scores):.4f}") print(f" Min: {min(f1_scores):.4f}") print(f" Max: {max(f1_scores):.4f}") print(f"\nAUC:") print(f" Mean: {sum(aucs) / len(aucs):.4f}") print(f" Min: {min(aucs):.4f}") print(f" Max: {max(aucs):.4f}") print(f"\nAP:") print(f" Mean: {sum(aps) / len(aps):.4f}") print(f" Min: {min(aps):.4f}") print(f" Max: {max(aps):.4f}") # Show worst performing models print("\n" + "-" * 60) if is_training_free: print("Bottom 10 Models (by AUC):") sorted_results = sorted(results.items(), key=lambda x: x[1].get("auc", 0)) for model_id, metrics in sorted_results[:10]: model_name = get_model_name(model_id, model_mapping) if model_mapping else f"Model_{model_id}" print(f" {model_name}: auc={metrics.get('auc', 0):.4f}, ap={metrics.get('ap', 0):.4f}") else: print("Bottom 10 Models (by accuracy):") sorted_results = sorted(results.items(), key=lambda x: x[1]["accuracy"]) for model_id, metrics in sorted_results[:10]: model_name = get_model_name(model_id, model_mapping) if model_mapping else f"Model_{model_id}" print(f" {model_name}: acc={metrics['accuracy']:.4f}, f1={metrics['f1']:.4f}") print("=" * 60) def parse_args(): parser = argparse.ArgumentParser( description="Evaluate legacy AI-generated image detection methods on ACID dataset." ) parser.add_argument( "--method", type=str, required=True, choices=["CNNDetection", "UnivFD", "LGrad", "HiFi", "RINE", "DeeCLIP", "DIRE", "WaRPAD", "RIGID", "AIDE", "AEROBLADE", "FatFormer", "ManifoldBias", "NPR", "AlignedForensics", "Effort"], help="Method to evaluate", ) parser.add_argument( "--acid-root", type=str, default="data_local/images/ai", help="Root directory of ACID fake images", ) parser.add_argument( "--real-root", type=str, default="data_local/images/real", help="Root directory of real images", ) parser.add_argument( "--real-samples", type=int, default=100, help="Number of real samples for evaluation", ) parser.add_argument( "--model-mapping", type=str, default="data_local/model_mapping.yaml", help="Path to model_mapping.yaml", ) parser.add_argument( "--output-dir", type=str, default=str(SCRIPT_DIR / "results"), help="Output directory for results", ) parser.add_argument( "--samples-per-model", type=int, default=100, help="Number of samples per model for evaluation", ) parser.add_argument( "--batch-size", type=int, default=32, help="Batch size for evaluation", ) parser.add_argument( "--num-workers", type=int, default=4, help="Number of data loading workers", ) parser.add_argument( "--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu", help="Device to use for inference", ) return parser.parse_args() def main(): args = parse_args() # Create output directory os.makedirs(args.output_dir, exist_ok=True) # Load model mapping if available model_mapping = None if os.path.exists(args.model_mapping): print(f"Loading model mapping from {args.model_mapping}") model_mapping = load_model_mapping(args.model_mapping) print(f"Loaded {len(model_mapping)} model mappings") # Initialize model print(f"\nInitializing {args.method}...") if args.method == "CNNDetection": weights_path = METHODS_DIR / "CNNDetection" / "weights" / "blur_jpg_prob0.5.pth" model_wrapper = CNNDetectionWrapper(str(weights_path), args.device) elif args.method == "UnivFD": weights_path = METHODS_DIR / "UniversalFakeDetect" / "pretrained_weights" / "fc_weights.pth" model_wrapper = UnivFDWrapper(str(weights_path), args.device) elif args.method == "LGrad": # LGrad provides multiple checkpoints: 1class, 2class, 4class # Default to 4class (trained on Progan car, cat, chair, horse) for best generalization weights_path = METHODS_DIR / "LGrad" / "CNNDetection" / "weights" / "LGrad-4class-Trainon-Progan_car_cat_chair_horse.pth" if not weights_path.exists(): # Try alternative names alt_paths = [ METHODS_DIR / "LGrad" / "CNNDetection" / "weights" / "LGrad-2class-Trainon-Progan_chair_horse.pth", METHODS_DIR / "LGrad" / "CNNDetection" / "weights" / "LGrad-1class-Trainon-Progan_horse.pth", ] for alt in alt_paths: if alt.exists(): weights_path = alt break model_wrapper = LGradWrapper(str(weights_path), args.device) elif args.method == "HiFi": weights_path = METHODS_DIR / "HiFi_IFDL" / "weights" model_wrapper = HiFiNetWrapper(str(weights_path), args.device) elif args.method == "RINE": weights_path = METHODS_DIR / "RINE" / "ckpt" / "model_4class_trainable.pth" model_wrapper = RINEWrapper(str(weights_path), args.device) elif args.method == "DeeCLIP": weights_path = METHODS_DIR / "DeeCLIP" / "weights" / "deeclip_weight_complete_with_lora_5.pth" model_wrapper = DeeCLIPWrapper(str(weights_path), args.device) elif args.method == "DIRE": # DIRE provides multiple checkpoints (lsun_adm, imagenet_adm, etc.) # Default to lsun_adm which is trained on LSUN-Bedroom ADM data weights_path = METHODS_DIR / "DIRE" / "weights" / "lsun_adm.pth" model_wrapper = DIREWrapper(str(weights_path), args.device) elif args.method == "WaRPAD": model_wrapper = WaRPADWrapper(device=args.device) elif args.method == "RIGID": model_wrapper = RIGIDWrapper(device=args.device) elif args.method == "AIDE": # AIDE provides multiple checkpoints (GenImage_train, progan_train, sd14_train) # Default to GenImage_train which is trained on GenImage dataset weights_path = METHODS_DIR / "AIDE" / "weights" / "AIDE_checkpoints" / "GenImage_train.pth" if not weights_path.exists(): # Try alternative checkpoints alt_paths = [ METHODS_DIR / "AIDE" / "weights" / "AIDE_checkpoints" / "progan_train.pth", METHODS_DIR / "AIDE" / "weights" / "AIDE_checkpoints" / "sd14_train.pth", ] for alt in alt_paths: if alt.exists(): weights_path = alt break model_wrapper = AIDEWrapper(str(weights_path), args.device) elif args.method == "AEROBLADE": # AEROBLADE is training-free, uses pretrained VAE autoencoders from HuggingFace # No weights need to be downloaded separately model_wrapper = AEROBLADEWrapper(device=args.device) elif args.method == "FatFormer": # FatFormer uses CLIP ViT-L/14 with forgery-aware adapters # Requires: 1) CLIP weights at pretrained/ViT-L-14.pt, 2) FatFormer checkpoint weights_path = METHODS_DIR / "FatFormer" / "pretrained" / "fatformer_4class_ckpt.pth" if not weights_path.exists(): raise FileNotFoundError( f"FatFormer checkpoint not found at {weights_path}. " "Download from: https://drive.google.com/file/d/1Q_Kgq4ygDf8XEHgAf-SgDN6Ru_IOTLkj/view" ) model_wrapper = FatFormerWrapper(str(weights_path), args.device) elif args.method == "ManifoldBias": # ManifoldBias is a training-free zero-shot method # Uses SD v1.4 (UNet, VAE), CLIP, and LLaVA for auto-captioning # Models are downloaded from HuggingFace on first use model_wrapper = ManifoldBiasWrapper(device=args.device) elif args.method == "NPR": # NPR detects upsampling artifacts in CNN-based generators # Default checkpoint: NPR.pth (trained on ProGAN 4-class) weights_path = METHODS_DIR / "NPR" / "NPR.pth" if not weights_path.exists(): # Try alternative checkpoint alt_path = METHODS_DIR / "NPR" / "model_epoch_last_3090.pth" if alt_path.exists(): weights_path = alt_path model_wrapper = NPRWrapper(str(weights_path), args.device) elif args.method == "AlignedForensics": # AlignedForensics uses aligned real/fake pairs for training # ResNet-50 with no downsampling in first layer (stride=1) # Multiple checkpoints available from Google Drive weights_path = METHODS_DIR / "AlignedForensics" / "weights" / "ours.pth" if not weights_path.exists(): # Try alternative checkpoints alt_paths = [ METHODS_DIR / "AlignedForensics" / "test_code" / "weights" / "ours-sync" / "weights.pth", METHODS_DIR / "AlignedForensics" / "weights" / "ours_sync.pth", METHODS_DIR / "AlignedForensics" / "weights" / "model_epoch_best.pth", ] for alt in alt_paths: if alt.exists(): weights_path = alt break model_wrapper = AlignedForensicsWrapper(str(weights_path), args.device) elif args.method == "Effort": # Effort uses CLIP ViT-L/14 with SVD orthogonal decomposition # GenImage checkpoint trained on Stable Diffusion v1.4 data weights_path = METHODS_DIR / "Effort" / "DeepfakeBench" / "training" / "weights" / "genimage_sd14.pth" if not weights_path.exists(): # Try alternative checkpoints alt_paths = [ METHODS_DIR / "Effort" / "DeepfakeBench" / "training" / "weights" / "chameleon_sd14.pth", METHODS_DIR / "Effort" / "DeepfakeBench" / "training" / "weights" / "faceforensics.pth", ] for alt in alt_paths: if alt.exists(): weights_path = alt break model_wrapper = EffortWrapper(str(weights_path), args.device) else: raise ValueError(f"Unknown method: {args.method}") print(f"Model initialized on {args.device}") # Get method-specific transform and target size (if applicable) # Some methods like WaRPAD require higher resolution input method_transform = None method_target_size = 224 # Default if args.method == "WaRPAD": method_transform = WaRPADWrapper.get_transform() method_target_size = WaRPADWrapper.get_target_size() print(f"Using WaRPAD-specific transform (target size: {method_target_size}x{method_target_size})") elif args.method == "Effort": method_transform = EffortWrapper.get_transform() method_target_size = EffortWrapper.get_target_size() print(f"Using Effort CLIP transform (target size: {method_target_size}x{method_target_size})") # Check if this is a training-free method is_training_free = args.method in TRAINING_FREE_METHODS # Evaluate on real images first (if real_root is provided) real_metrics = None real_dataset = None real_preds = [] real_probs = [] real_labels = [] if args.real_root and os.path.isdir(args.real_root): print(f"\n{'='*60}") print("EVALUATING ON REAL IMAGES") print(f"{'='*60}") print(f"Real image root: {args.real_root}") print(f"Number of samples: {args.real_samples}") real_dataset = create_real_dataset( args.real_root, args.real_samples, transform=method_transform, target_size=method_target_size ) print(f"Loaded {len(real_dataset)} real images") # For training-free methods, we need to store predictions to pair with fake images later if is_training_free: print("Collecting real image predictions for per-model AUC/AP calculation...") real_loader = DataLoader( real_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True, ) for images, labels, _ in tqdm(real_loader, desc="Processing real images"): preds, probs = model_wrapper.predict(images) real_preds.extend(preds) real_probs.extend(probs) real_labels.extend(labels.tolist()) real_metrics = compute_metrics(real_preds, real_labels, real_probs) else: real_metrics = evaluate_model( model_wrapper, real_dataset, args.batch_size, args.num_workers, ) print(f"\nReal Image Results:") print(f" Accuracy: {real_metrics['accuracy']:.4f}") print(f" Precision: {real_metrics['precision']:.4f}") print(f" Recall: {real_metrics['recall']:.4f}") print(f" F1: {real_metrics['f1']:.4f}") # Note: For real images, accuracy = proportion correctly classified as real (prediction=0) # High accuracy means model correctly identifies real images as real # Evaluate per model (fake images) print(f"\n{'='*60}") print("EVALUATING ON AI-GENERATED IMAGES (PER MODEL)") print(f"{'='*60}") print(f"ACID root: {args.acid_root}") print(f"Samples per model: {args.samples_per_model}") # Create datasets first (so we can save image paths) fake_datasets = create_per_model_datasets( args.acid_root, model_mapping, args.samples_per_model, transform=method_transform, target_size=method_target_size ) # Evaluate each model if is_training_free and real_preds: # For training-free methods, pair each AI model with real images for proper AUC/AP print(f"\n[Training-free method: pairing {len(real_preds)} real images with each AI model for AUC/AP]") results = evaluate_per_model_with_real( model_wrapper, fake_datasets, real_preds, real_probs, real_labels, args.batch_size, args.num_workers, ) else: # For trained methods, evaluate fake images only (threshold-based metrics are meaningful) results = {} for model_id, dataset in tqdm(fake_datasets.items(), desc="Evaluating per model"): if len(dataset) > 0: metrics = evaluate_model(model_wrapper, dataset, args.batch_size, args.num_workers) results[model_id] = metrics # Save results timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") output_path = os.path.join(args.output_dir, f"{args.method}_results_{timestamp}.csv") save_results(results, model_mapping, output_path, args.method) print(f"\nResults saved to {output_path}") # Save real image results separately if available if real_metrics: real_output_path = os.path.join(args.output_dir, f"{args.method}_real_results_{timestamp}.csv") with open(real_output_path, "w", newline="") as f: writer = csv.writer(f) writer.writerow(["method", "dataset", "accuracy", "precision", "recall", "f1", "auc", "timestamp"]) writer.writerow([ args.method, "real", f"{real_metrics.get('accuracy', 0):.4f}", f"{real_metrics.get('precision', 0):.4f}", f"{real_metrics.get('recall', 0):.4f}", f"{real_metrics.get('f1', 0):.4f}", f"{real_metrics.get('auc', 'nan'):.4f}" if isinstance(real_metrics.get('auc'), (int, float)) else "nan", timestamp, ]) print(f"Real results saved to {real_output_path}") # Save image paths for reproducibility image_paths_file = os.path.join(args.output_dir, f"{args.method}_image_paths_{timestamp}.json") save_image_paths( image_paths_file, fake_datasets, real_dataset, model_mapping, ) print(f"Image paths saved to {image_paths_file}") # Print summary print_summary(results, model_mapping, args.method) # Print combined summary if real_metrics: is_training_free = args.method in TRAINING_FREE_METHODS print(f"\n{'='*60}") print("COMBINED SUMMARY") print(f"{'='*60}") if is_training_free: # For training-free methods, show AUC/AP as primary metrics fake_aucs = [m.get("auc", 0) for m in results.values()] fake_aps = [m.get("ap", 0) for m in results.values()] mean_fake_auc = sum(fake_aucs) / len(fake_aucs) if fake_aucs else 0 mean_fake_ap = sum(fake_aps) / len(fake_aps) if fake_aps else 0 print(f"[Training-free method: primary metrics are AUC/AP]") print(f"Real Images AUC: {real_metrics.get('auc', 0):.4f}") print(f"Fake Images Mean AUC: {mean_fake_auc:.4f}") print(f"Real Images AP: {real_metrics.get('ap', 0):.4f}") print(f"Fake Images Mean AP: {mean_fake_ap:.4f}") else: fake_accuracies = [m["accuracy"] for m in results.values()] mean_fake_acc = sum(fake_accuracies) / len(fake_accuracies) if fake_accuracies else 0 print(f"Real Images Accuracy (correctly classified as real): {real_metrics['accuracy']:.4f}") print(f"Fake Images Accuracy (correctly classified as fake): {mean_fake_acc:.4f}") print(f"{'='*60}") if __name__ == "__main__": raise SystemExit("Internal wrappers: use scripts/eval/evaluate_pretrained_detectors.py or the dedicated DIRE/training-free evaluator.")