Download code/train_cnndetect.py from Shining31/WildGen: direct link, hf CLI and curl.
- Browser
- Download file 34.1 kB
-
https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/train_cnndetect.py
- Command line
-
hf download hf://datasets/Shining31/WildGen/code/train_cnndetect.py
-
curl -L -o train_cnndetect.py https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/train_cnndetect.py
34.1 kB
| #!/usr/bin/env python3 | |
| """ | |
| Training script for CNNDetection-style binary classification (Real vs Fake). | |
| Uses a ResNet50 backbone with a trainable FC layer for binary classification, | |
| following the CNNDetection architecture but with the same data sampling | |
| strategy as train.py. | |
| Reference: "CNN-generated images are surprisingly easy to spot... for now" | |
| Wang et al., CVPR 2020 | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import random | |
| import sys | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Dict, List, Tuple | |
| import yaml | |
| from PIL import Image | |
| import torch | |
| import torch.nn as nn | |
| import torch.optim as optim | |
| from torch.utils.data import Dataset, DataLoader | |
| import torchvision.transforms as T | |
| import torchvision.models as models | |
| from accelerate import Accelerator | |
| from tqdm import tqdm | |
| # ImageNet normalization statistics (same as CNNDetection) | |
| IMAGENET_MEAN = [0.485, 0.456, 0.406] | |
| IMAGENET_STD = [0.229, 0.224, 0.225] | |
| ALLOWED_EXTS = {".jpg", ".jpeg", ".png", ".webp"} | |
| class Sample: | |
| image_path: Path | |
| class_index: int | |
| class ImageClsDataset(Dataset): | |
| """Dataset for loading images organized by model ID folders.""" | |
| REAL_MODEL_ID = 0 # Reserved model ID for real images | |
| def from_scratch(cls, ai_root, model_mapping, transform: T.Compose, real_root: str = None): | |
| samples = dict() | |
| # Load real images first (model_id = 0) | |
| if real_root and os.path.isdir(real_root): | |
| real_files = [] | |
| for file in os.listdir(real_root): | |
| ext = Path(file).suffix.lower() | |
| if ext in ALLOWED_EXTS: | |
| real_files.append((os.path.join(real_root, file), cls.REAL_MODEL_ID)) | |
| if real_files: | |
| samples[cls.REAL_MODEL_ID] = real_files | |
| print(f"Loaded {len(real_files)} real images") | |
| # Load AI-generated images | |
| subfolders = os.listdir(ai_root) | |
| for subfolder in subfolders: | |
| if '.' in subfolder: | |
| continue | |
| try: | |
| idx = int(subfolder) | |
| except ValueError: | |
| continue | |
| if idx not in model_mapping.values(): | |
| print(subfolder, 'is not listed as a model.') | |
| else: | |
| samples[idx] = [] | |
| files = os.listdir(os.path.join(ai_root, subfolder)) | |
| for file in files: | |
| ext = Path(file).suffix.lower() | |
| if ext in ALLOWED_EXTS: | |
| samples[idx].append((os.path.join(ai_root, subfolder, file), idx)) | |
| return cls(samples, model_mapping, transform) | |
| def __init__(self, samples, model_mapping, transform): | |
| super().__init__() | |
| self.samples_dict = samples # Keep dict for subset operations | |
| self.model_mapping = model_mapping | |
| self.transform = transform | |
| # Create mapping from model_id to class index (0, 1, 2, ...) | |
| self.model_id_to_class = {mid: i for i, mid in enumerate(sorted(samples.keys()))} | |
| self.class_to_model_id = {i: mid for mid, i in self.model_id_to_class.items()} | |
| # Track which class index corresponds to real images (None if no real images) | |
| self.real_class_idx = self.model_id_to_class.get(self.REAL_MODEL_ID, None) | |
| # Flatten samples into a list for indexing: [(image_path, class_index), ...] | |
| self.samples = [] | |
| for model_id, items in samples.items(): | |
| class_idx = self.model_id_to_class[model_id] | |
| for img_path, _ in items: | |
| self.samples.append((img_path, class_idx)) | |
| def num_classes(self): | |
| return len(self.samples_dict) | |
| def __len__(self) -> int: | |
| return len(self.samples) | |
| def __getitem__(self, idx: int): | |
| img_path, label = self.samples[idx] | |
| try: | |
| img = Image.open(img_path).convert("RGB") | |
| except Exception as exc: | |
| raise RuntimeError(f"Unreadable benchmark image: {img_path}") from exc | |
| img = self.transform(img) | |
| return img, label | |
| def crop_by_num_samples(self, limitation, min_threshold=None, real_limit=None): | |
| """Subsample to limitation samples per model.""" | |
| if min_threshold is None: | |
| min_threshold = limitation | |
| subset = dict() | |
| for key, v in self.samples_dict.items(): | |
| if key == self.REAL_MODEL_ID: | |
| limit = real_limit if real_limit is not None else limitation | |
| if len(v) >= min_threshold: | |
| subset[key] = random.sample(v, k=min(limit, len(v))) | |
| else: | |
| if len(v) >= min_threshold: | |
| subset[key] = random.sample(v, k=min(limitation, len(v))) | |
| return ImageClsDataset(subset, self.model_mapping, self.transform) | |
| def subsample_from(self, n_samples: int, real_ratio: float = None): | |
| """Create a smaller dataset by taking first n_samples from each AI model.""" | |
| subset = dict() | |
| num_ai_models = len([k for k in self.samples_dict.keys() if k != self.REAL_MODEL_ID]) | |
| for key, v in self.samples_dict.items(): | |
| if key == self.REAL_MODEL_ID and real_ratio is not None: | |
| real_count = int(real_ratio * n_samples * num_ai_models) | |
| subset[key] = v[:real_count] | |
| else: | |
| subset[key] = v[:n_samples] | |
| return ImageClsDataset(subset, self.model_mapping, self.transform) | |
| def safe_split(self, ratio=0.9, real_test_count: int = None): | |
| """Split dataset into train and test sets.""" | |
| train, val = dict(), dict() | |
| for k, v in self.samples_dict.items(): | |
| v_copy = list(v) | |
| random.shuffle(v_copy) | |
| if k == self.REAL_MODEL_ID and real_test_count is not None: | |
| val[k] = v_copy[:real_test_count] | |
| train[k] = v_copy[real_test_count:] | |
| else: | |
| train[k] = v_copy[:int(len(v_copy) * ratio)] | |
| val[k] = v_copy[int(len(v_copy) * ratio):] | |
| return ImageClsDataset(train, self.model_mapping, self.transform), ImageClsDataset(val, self.model_mapping, self.transform) | |
| def get_split_config(self) -> Dict: | |
| """Export the current dataset configuration for reproducibility.""" | |
| config = {} | |
| for model_id, items in self.samples_dict.items(): | |
| config[str(model_id)] = [img_path for img_path, _ in items] | |
| return config | |
| def from_split_config(cls, config: Dict, model_mapping, transform: T.Compose): | |
| """Create dataset from a saved split configuration.""" | |
| samples = {} | |
| for model_id_str, paths in config.items(): | |
| model_id = int(model_id_str) | |
| samples[model_id] = [(path, model_id) for path in paths] | |
| return cls(samples, model_mapping, transform) | |
| class BinaryDatasetWrapper(Dataset): | |
| """Wrapper that converts multi-class labels to binary (real=0, fake=1).""" | |
| def __init__(self, base_dataset: ImageClsDataset): | |
| self.base_dataset = base_dataset | |
| self.real_class_idx = base_dataset.real_class_idx | |
| def __len__(self): | |
| return len(self.base_dataset) | |
| def __getitem__(self, idx): | |
| img, class_idx = self.base_dataset[idx] | |
| # Binary label: 0 for real, 1 for fake (AI-generated) | |
| if self.real_class_idx is not None: | |
| binary_label = 0.0 if class_idx == self.real_class_idx else 1.0 | |
| else: | |
| # If no real images, all are fake | |
| binary_label = 1.0 | |
| return img, binary_label, class_idx # Also return original class for per-model analysis | |
| def samples_dict(self): | |
| return self.base_dataset.samples_dict | |
| class CNNDetectModel(nn.Module): | |
| """ | |
| CNNDetection-style model: ResNet50 backbone + FC layer for binary classification. | |
| Architecture: | |
| Input -> ResNet50 (pretrained, all trainable) -> FC(2048, 1) -> Logit | |
| Reference: Wang et al., "CNN-generated images are surprisingly easy to spot... for now" | |
| """ | |
| def __init__(self, pretrained: bool = True, init_gain: float = 0.02): | |
| super().__init__() | |
| # Load pretrained ResNet50 | |
| if pretrained: | |
| self.backbone = models.resnet50(weights=models.ResNet50_Weights.IMAGENET1K_V1) | |
| else: | |
| self.backbone = models.resnet50(weights=None) | |
| # Replace the final FC layer for binary classification | |
| in_features = self.backbone.fc.in_features # 2048 for ResNet50 | |
| self.backbone.fc = nn.Linear(in_features, 1) | |
| # Initialize FC layer weights (following CNNDetection) | |
| nn.init.normal_(self.backbone.fc.weight, 0.0, init_gain) | |
| nn.init.zeros_(self.backbone.fc.bias) | |
| def forward(self, x): | |
| return self.backbone(x) | |
| def save_split_config(train_config: Dict, test_config: Dict, output_path: Path): | |
| """Save train/test split configuration to JSON file.""" | |
| split_data = { | |
| "train": train_config, | |
| "test": test_config, | |
| } | |
| with open(output_path, "w", encoding="utf-8") as f: | |
| json.dump(split_data, f, indent=2) | |
| print(f"Saved split config to: {output_path}") | |
| def load_split_config(split_path: Path) -> Tuple[Dict, Dict]: | |
| """Load train/test split configuration from JSON file.""" | |
| with open(split_path, "r", encoding="utf-8") as f: | |
| split_data = json.load(f) | |
| return split_data["train"], split_data["test"] | |
| def make_transforms(img_size: int = 224) -> Tuple[T.Compose, T.Compose]: | |
| """Create ImageNet-normalized transforms for training and testing.""" | |
| train_tf = T.Compose([ | |
| T.RandomResizedCrop(img_size, scale=(0.6, 1.0)), | |
| T.RandomHorizontalFlip(), | |
| T.ToTensor(), | |
| T.Normalize(IMAGENET_MEAN, IMAGENET_STD), | |
| ]) | |
| test_tf = T.Compose([ | |
| T.Resize(int(img_size * 1.15)), | |
| T.CenterCrop(img_size), | |
| T.ToTensor(), | |
| T.Normalize(IMAGENET_MEAN, IMAGENET_STD), | |
| ]) | |
| return train_tf, test_tf | |
| def train_one_epoch( | |
| model: nn.Module, | |
| loader: DataLoader, | |
| criterion: nn.Module, | |
| optimizer: optim.Optimizer, | |
| accelerator: Accelerator, | |
| device: torch.device, | |
| epoch: int = 0, | |
| total_epochs: int = 0 | |
| ) -> Tuple[float, float]: | |
| """Train for one epoch with BCE loss.""" | |
| model.train() | |
| running_loss = 0.0 | |
| correct = 0 | |
| total = 0 | |
| pbar = tqdm(loader, desc=f"Epoch {epoch}/{total_epochs}", disable=not accelerator.is_local_main_process) | |
| for images, labels, _ in pbar: # labels are binary floats, _ is original class | |
| images = images.to(device, non_blocking=True) | |
| labels = labels.to(device, non_blocking=True) | |
| optimizer.zero_grad(set_to_none=True) | |
| outputs = model(images).squeeze(-1) # [B, 1] -> [B] | |
| loss = criterion(outputs, labels) | |
| accelerator.backward(loss) | |
| optimizer.step() | |
| running_loss += loss.item() * images.size(0) | |
| preds = (torch.sigmoid(outputs) > 0.5).float() | |
| correct += (preds == labels).sum().item() | |
| total += labels.size(0) | |
| pbar.set_postfix(loss=f"{loss.item():.4f}", acc=f"{correct/total:.4f}") | |
| # Reduce metrics across processes | |
| loss_tensor = torch.tensor([running_loss], device=device) | |
| correct_tensor = torch.tensor([correct], device=device) | |
| total_tensor = torch.tensor([total], device=device) | |
| loss_sum = accelerator.reduce(loss_tensor, reduction="sum").item() | |
| correct_sum = accelerator.reduce(correct_tensor, reduction="sum").item() | |
| total_sum = accelerator.reduce(total_tensor, reduction="sum").item() | |
| avg_loss = loss_sum / max(1, total_sum) | |
| acc = correct_sum / max(1, total_sum) | |
| return avg_loss, acc | |
| def compute_f1_and_balanced_acc(real_correct: int, real_total: int, fake_correct: int, fake_total: int) -> Tuple[float, float, float]: | |
| """ | |
| Compute balanced accuracy and F1 score for the real class. | |
| Returns: | |
| balanced_acc: (real_acc + fake_acc) / 2 | |
| f1_real: F1 score for the real class | |
| f1_fake: F1 score for the fake class | |
| """ | |
| # Compute per-class accuracy | |
| real_acc = real_correct / max(1, real_total) | |
| fake_acc = fake_correct / max(1, fake_total) | |
| # Balanced accuracy | |
| balanced_acc = (real_acc + fake_acc) / 2 | |
| # For real class (label=0): | |
| # TP = real_correct (predicted real, actually real) | |
| # FN = real_total - real_correct (predicted fake, actually real) | |
| # FP = fake_total - fake_correct (predicted real, actually fake) | |
| # TN = fake_correct (predicted fake, actually fake) | |
| tp_real = real_correct | |
| fn_real = real_total - real_correct | |
| fp_real = fake_total - fake_correct | |
| precision_real = tp_real / max(1, tp_real + fp_real) | |
| recall_real = tp_real / max(1, tp_real + fn_real) | |
| f1_real = 2 * precision_real * recall_real / max(1e-8, precision_real + recall_real) | |
| # For fake class (label=1): | |
| tp_fake = fake_correct | |
| fn_fake = fake_total - fake_correct | |
| fp_fake = real_total - real_correct | |
| precision_fake = tp_fake / max(1, tp_fake + fp_fake) | |
| recall_fake = tp_fake / max(1, tp_fake + fn_fake) | |
| f1_fake = 2 * precision_fake * recall_fake / max(1e-8, precision_fake + recall_fake) | |
| return balanced_acc, f1_real, f1_fake | |
| def evaluate( | |
| model: nn.Module, | |
| loader: DataLoader, | |
| criterion: nn.Module, | |
| accelerator: Accelerator, | |
| device: torch.device, | |
| num_models: int = None, | |
| class_to_model_id: Dict = None, | |
| real_class_idx: int = None | |
| ) -> Dict: | |
| """ | |
| Evaluate model with binary classification metrics. | |
| Returns: | |
| Dict with keys: 'loss', 'accuracy', 'real_acc', 'fake_acc', 'balanced_acc', | |
| 'f1_real', 'f1_fake', 'per_model_detection_rate' | |
| """ | |
| model.eval() | |
| running_loss = 0.0 | |
| correct = 0 | |
| total = 0 | |
| # Track per-class metrics | |
| real_correct = 0 | |
| real_total = 0 | |
| fake_correct = 0 | |
| fake_total = 0 | |
| # Track per-model detection rates (for AI models only) | |
| if num_models is not None and class_to_model_id is not None: | |
| per_model_correct = {mid: 0 for mid in class_to_model_id.values() if mid != ImageClsDataset.REAL_MODEL_ID} | |
| per_model_total = {mid: 0 for mid in class_to_model_id.values() if mid != ImageClsDataset.REAL_MODEL_ID} | |
| else: | |
| per_model_correct = None | |
| per_model_total = None | |
| with torch.no_grad(): | |
| for images, labels, orig_classes in loader: | |
| images = images.to(device, non_blocking=True) | |
| labels = labels.to(device, non_blocking=True) | |
| orig_classes = orig_classes.to(device, non_blocking=True) | |
| outputs = model(images).squeeze(-1) | |
| loss = criterion(outputs, labels) | |
| running_loss += loss.item() * images.size(0) | |
| preds = (torch.sigmoid(outputs) > 0.5).float() | |
| correct += (preds == labels).sum().item() | |
| total += labels.size(0) | |
| # Per-class accuracy | |
| real_mask = (labels == 0) | |
| fake_mask = (labels == 1) | |
| real_correct += ((preds == labels) & real_mask).sum().item() | |
| real_total += real_mask.sum().item() | |
| fake_correct += ((preds == labels) & fake_mask).sum().item() | |
| fake_total += fake_mask.sum().item() | |
| # Per-model detection rate (for fake images only) | |
| if per_model_correct is not None and class_to_model_id is not None: | |
| for i in range(len(orig_classes)): | |
| orig_class = orig_classes[i].item() | |
| model_id = class_to_model_id.get(orig_class) | |
| if model_id is not None and model_id != ImageClsDataset.REAL_MODEL_ID: | |
| per_model_total[model_id] += 1 | |
| if preds[i] == labels[i]: | |
| per_model_correct[model_id] += 1 | |
| # Reduce metrics across processes | |
| loss_tensor = torch.tensor([running_loss], device=device) | |
| correct_tensor = torch.tensor([correct], device=device) | |
| total_tensor = torch.tensor([total], device=device) | |
| real_correct_tensor = torch.tensor([real_correct], device=device) | |
| real_total_tensor = torch.tensor([real_total], device=device) | |
| fake_correct_tensor = torch.tensor([fake_correct], device=device) | |
| fake_total_tensor = torch.tensor([fake_total], device=device) | |
| loss_sum = accelerator.reduce(loss_tensor, reduction="sum").item() | |
| correct_sum = accelerator.reduce(correct_tensor, reduction="sum").item() | |
| total_sum = accelerator.reduce(total_tensor, reduction="sum").item() | |
| real_correct_sum = accelerator.reduce(real_correct_tensor, reduction="sum").item() | |
| real_total_sum = accelerator.reduce(real_total_tensor, reduction="sum").item() | |
| fake_correct_sum = accelerator.reduce(fake_correct_tensor, reduction="sum").item() | |
| fake_total_sum = accelerator.reduce(fake_total_tensor, reduction="sum").item() | |
| avg_loss = loss_sum / max(1, total_sum) | |
| accuracy = correct_sum / max(1, total_sum) | |
| real_acc = real_correct_sum / max(1, real_total_sum) if real_total_sum > 0 else None | |
| fake_acc = fake_correct_sum / max(1, fake_total_sum) if fake_total_sum > 0 else None | |
| # Compute balanced accuracy and F1 scores | |
| balanced_acc, f1_real, f1_fake = None, None, None | |
| if real_total_sum > 0 and fake_total_sum > 0: | |
| balanced_acc, f1_real, f1_fake = compute_f1_and_balanced_acc( | |
| int(real_correct_sum), int(real_total_sum), | |
| int(fake_correct_sum), int(fake_total_sum) | |
| ) | |
| # Compute per-model detection rates | |
| per_model_detection_rate = None | |
| if per_model_correct is not None: | |
| per_model_detection_rate = {} | |
| for model_id in per_model_correct: | |
| if per_model_total[model_id] > 0: | |
| per_model_detection_rate[model_id] = per_model_correct[model_id] / per_model_total[model_id] | |
| return { | |
| 'loss': avg_loss, | |
| 'accuracy': accuracy, | |
| 'real_acc': real_acc, | |
| 'fake_acc': fake_acc, | |
| 'balanced_acc': balanced_acc, | |
| 'f1_real': f1_real, | |
| 'f1_fake': f1_fake, | |
| 'per_model_detection_rate': per_model_detection_rate, | |
| } | |
| def save_outputs(output_dir: Path, model: nn.Module, is_best: bool = False, is_final: bool = False): | |
| """Save model checkpoints.""" | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| if is_best: | |
| best_path = output_dir / "model_best.pth" | |
| torch.save(model.state_dict(), best_path) | |
| print(f"Saved best model to: {best_path}") | |
| if is_final: | |
| final_path = output_dir / "model_final.pth" | |
| torch.save(model.state_dict(), final_path) | |
| print(f"Saved final model to: {final_path}") | |
| def validation_epoch_interval(num_epochs: int, num_validations: int | None) -> int: | |
| """Return the epoch interval that keeps validation passes bounded.""" | |
| if num_validations is None or num_validations <= 0: | |
| return 1 | |
| return max(1, num_epochs // num_validations) | |
| def should_validate_epoch( | |
| epoch: int, | |
| num_epochs: int, | |
| num_validations: int | None, | |
| no_val_between_epochs: bool, | |
| ) -> bool: | |
| if no_val_between_epochs: | |
| return epoch == num_epochs | |
| interval = validation_epoch_interval(num_epochs, num_validations) | |
| return epoch == num_epochs or epoch % interval == 0 | |
| def train_with_sample_size( | |
| train_ds: ImageClsDataset, | |
| test_ds: ImageClsDataset, | |
| sample_size: int, | |
| num_epochs: int, | |
| args, | |
| accelerator: Accelerator, | |
| output_dir: Path, | |
| ): | |
| """Train a model with a specific sample size setting.""" | |
| accelerator.print(f"\n{'='*60}") | |
| accelerator.print(f"Training with sample_size={sample_size}, epochs={num_epochs}") | |
| accelerator.print(f"{'='*60}") | |
| # Create subsampled training set | |
| train_tf, test_tf = make_transforms(args.img_size) | |
| n_samples_per_ai = int(sample_size * args.train_ratio) | |
| sub_train_ds = train_ds.subsample_from(n_samples_per_ai, real_ratio=args.real_ratio) | |
| sub_train_ds.transform = train_tf | |
| test_ds.transform = test_tf | |
| # Wrap with binary labels | |
| binary_train_ds = BinaryDatasetWrapper(sub_train_ds) | |
| binary_test_ds = BinaryDatasetWrapper(test_ds) | |
| # Count samples | |
| real_model_id = ImageClsDataset.REAL_MODEL_ID | |
| real_train_count = len(sub_train_ds.samples_dict.get(real_model_id, [])) | |
| ai_train_count = sum(len(v) for k, v in sub_train_ds.samples_dict.items() if k != real_model_id) | |
| accelerator.print(f"Train samples: {len(binary_train_ds)} (Real: {real_train_count}, AI: {ai_train_count})") | |
| accelerator.print(f"Test samples: {len(binary_test_ds)}") | |
| pin_memory = torch.cuda.is_available() | |
| train_loader = DataLoader( | |
| binary_train_ds, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers, pin_memory=pin_memory | |
| ) | |
| test_loader = DataLoader( | |
| binary_test_ds, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=pin_memory | |
| ) | |
| device = accelerator.device | |
| model = CNNDetectModel(pretrained=True, init_gain=args.init_gain) | |
| criterion = nn.BCEWithLogitsLoss() | |
| # Train all parameters (full fine-tuning, like CNNDetection) | |
| optimizer = optim.Adam(model.parameters(), lr=args.lr) | |
| model, optimizer, train_loader, test_loader = accelerator.prepare(model, optimizer, train_loader, test_loader) | |
| best_acc = -1.0 | |
| results = [] | |
| # Get class to model_id mapping for per-model analysis | |
| class_to_model_id = sub_train_ds.class_to_model_id | |
| num_models = sub_train_ds.num_classes | |
| real_class_idx = sub_train_ds.real_class_idx | |
| best_per_model_detection = None | |
| for epoch in range(1, num_epochs + 1): | |
| train_loss, train_acc = train_one_epoch( | |
| model, train_loader, criterion, optimizer, accelerator, device, epoch, num_epochs | |
| ) | |
| validate_now = should_validate_epoch( | |
| epoch, num_epochs, args.num_validations, args.no_val_between_epochs | |
| ) | |
| if not validate_now: | |
| accelerator.print(f"Epoch {epoch:02d}/{num_epochs} | Train loss {train_loss:.4f} acc {train_acc:.4f}") | |
| results.append({ | |
| 'epoch': epoch, | |
| 'validated': False, | |
| 'train_loss': train_loss, | |
| 'train_acc': train_acc, | |
| 'test_loss': None, | |
| 'test_acc': None, | |
| 'real_acc': None, | |
| 'fake_acc': None, | |
| 'per_model_detection_rate': None, | |
| }) | |
| continue | |
| metrics = evaluate( | |
| model, test_loader, criterion, accelerator, device, | |
| num_models=num_models, class_to_model_id=class_to_model_id, real_class_idx=real_class_idx | |
| ) | |
| test_loss = metrics['loss'] | |
| test_acc = metrics['accuracy'] | |
| real_acc = metrics['real_acc'] | |
| fake_acc = metrics['fake_acc'] | |
| balanced_acc = metrics['balanced_acc'] | |
| f1_real = metrics['f1_real'] | |
| f1_fake = metrics['f1_fake'] | |
| per_model_detection = metrics['per_model_detection_rate'] | |
| # Build output string | |
| output_str = ( | |
| f"Epoch {epoch:02d}/{num_epochs} | Train loss {train_loss:.4f} acc {train_acc:.4f} | " | |
| f"Test loss {test_loss:.4f} acc {test_acc:.4f}" | |
| ) | |
| if real_acc is not None: | |
| output_str += f" real_acc {real_acc:.4f}" | |
| if fake_acc is not None: | |
| output_str += f" fake_acc {fake_acc:.4f}" | |
| if balanced_acc is not None: | |
| output_str += f" bal_acc {balanced_acc:.4f}" | |
| if f1_real is not None: | |
| output_str += f" f1_real {f1_real:.4f}" | |
| accelerator.print(output_str) | |
| is_best = test_acc > best_acc | |
| if is_best: | |
| best_acc = test_acc | |
| best_per_model_detection = per_model_detection | |
| # Save best model (only when validation is performed) | |
| results.append({ | |
| 'epoch': epoch, | |
| 'validated': True, | |
| 'train_loss': train_loss, | |
| 'train_acc': train_acc, | |
| 'test_loss': test_loss, | |
| 'test_acc': test_acc, | |
| 'real_acc': real_acc, | |
| 'fake_acc': fake_acc, | |
| 'balanced_acc': balanced_acc, | |
| 'f1_real': f1_real, | |
| 'f1_fake': f1_fake, | |
| 'per_model_detection_rate': per_model_detection, | |
| }) | |
| # Save final model | |
| accelerator.wait_for_everyone() | |
| if accelerator.is_main_process: | |
| unwrapped = accelerator.unwrap_model(model) | |
| save_outputs(output_dir, unwrapped, is_final=True) | |
| # Save results summary | |
| # Get final epoch metrics for summary | |
| final_metrics = results[-1] if results else {} | |
| if accelerator.is_main_process: | |
| results_path = output_dir / "results.json" | |
| with open(results_path, "w") as f: | |
| json.dump({ | |
| 'sample_size': sample_size, | |
| 'num_epochs': num_epochs, | |
| 'num_validations': args.num_validations, | |
| 'validation_interval': validation_epoch_interval(num_epochs, args.num_validations), | |
| 'best_accuracy': best_acc, | |
| 'final_accuracy': final_metrics.get('test_acc'), | |
| 'final_balanced_acc': final_metrics.get('balanced_acc'), | |
| 'final_f1_real': final_metrics.get('f1_real'), | |
| 'final_f1_fake': final_metrics.get('f1_fake'), | |
| 'final_real_acc': final_metrics.get('real_acc'), | |
| 'final_fake_acc': final_metrics.get('fake_acc'), | |
| 'best_per_model_detection_rate': best_per_model_detection, | |
| 'class_to_model_id': {str(k): v for k, v in class_to_model_id.items()}, | |
| 'epochs': results, | |
| }, f, indent=2) | |
| accelerator.print(f"Saved results to: {results_path}") | |
| return final_metrics['test_acc'] | |
| def parse_args(): | |
| parser = argparse.ArgumentParser(description="Train CNNDetection-style binary classifier (Real vs Fake).") | |
| parser.add_argument("--mapping", type=str, default="metadata/model_mapping.yaml", | |
| help="Path to model_mapping.yaml") | |
| parser.add_argument("--images-root", type=str, default="data_local/images/ai", | |
| help="Root directory containing {id} subfolders with images") | |
| parser.add_argument("--real-root", type=str, default="data_local/images/real", | |
| help="Root directory containing real images") | |
| parser.add_argument("--output-dir", type=str, default="./outputs_cnndetect", | |
| help="Directory to save model and results") | |
| parser.add_argument("--batch-size", type=int, default=64) | |
| parser.add_argument("--lr", type=float, default=1e-4, help="Learning rate (CNNDetection default: 1e-4)") | |
| parser.add_argument("--init-gain", type=float, default=0.02, help="FC layer weight initialization std") | |
| parser.add_argument("--num-workers", type=int, default=4) | |
| parser.add_argument("--img-size", type=int, default=224) | |
| parser.add_argument("--train-ratio", type=float, default=1.0, help="Train split ratio per class") | |
| parser.add_argument("--sample-sizes", type=str, default="900,90,45,18", | |
| help="Comma-separated sample sizes to train on (descending order)") | |
| parser.add_argument("--total-samples-per-model", type=int, default=9000, | |
| help="Total samples per model across all epochs") | |
| parser.add_argument("--real-ratio", type=float, default=0.1, | |
| help="Ratio of real images to total AI images in training") | |
| parser.add_argument("--real-test-count", type=int, default=100, | |
| help="Fixed number of real images in test set") | |
| parser.add_argument("--no-val-between-epochs", action="store_true", | |
| help="Skip validation between epochs, only evaluate at the end") | |
| parser.add_argument("--num-validations", type=int, default=None, | |
| help="Target validation passes per sample size. Default validates every epoch.") | |
| parser.add_argument("--split-file", type=str, required=True, | |
| help="Path to split config JSON. If provided, reuse this split") | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--mixed-precision", type=str, default="no", choices=["no", "fp16", "bf16"], | |
| help="Mixed precision mode for accelerate") | |
| return parser.parse_args() | |
| def main(): | |
| args = parse_args() | |
| accelerator = Accelerator(mixed_precision=args.mixed_precision) | |
| random.seed(args.seed) | |
| torch.manual_seed(args.seed) | |
| images_root = Path(args.images_root) | |
| output_dir = Path(args.output_dir) | |
| # Parse sample sizes | |
| sample_sizes = [int(s.strip()) for s in args.sample_sizes.split(",")] | |
| sample_sizes = sorted(sample_sizes, reverse=True) | |
| max_sample_size = sample_sizes[0] | |
| accelerator.print("=" * 60) | |
| accelerator.print("CNNDetection-style Binary Classification Training") | |
| accelerator.print("=" * 60) | |
| accelerator.print(f"Model: ResNet50 (pretrained, full fine-tuning) + FC(2048, 1)") | |
| accelerator.print(f"Task: Binary classification (Real vs Fake)") | |
| accelerator.print(f"Sample sizes to train: {sample_sizes}") | |
| accelerator.print(f"Total samples per model target: {args.total_samples_per_model}") | |
| accelerator.print(f"Real image ratio: {args.real_ratio}") | |
| accelerator.print(f"Real test count: {args.real_test_count}") | |
| accelerator.print("\nLoading mapping...") | |
| with open(args.mapping, "r", encoding="utf-8") as f: | |
| model_mapping = yaml.safe_load(f) | |
| accelerator.print("Preparing base dataset...") | |
| train_tf, test_tf = make_transforms(args.img_size) | |
| if not Path(args.split_file).is_file(): | |
| raise FileNotFoundError(args.split_file) | |
| with open(args.split_file, encoding="utf-8") as split_handle: | |
| release_split = json.load(split_handle) | |
| if release_split.get("protocol", {}).get("seed") != args.seed: | |
| raise ValueError("Build a release split for this seed before training") | |
| if args.split_file: | |
| accelerator.print(f"Loading split config from: {args.split_file}") | |
| train_config, test_config = load_split_config(Path(args.split_file)) | |
| base_train_ds = ImageClsDataset.from_split_config(train_config, model_mapping, train_tf) | |
| base_test_ds = ImageClsDataset.from_split_config(test_config, model_mapping, test_tf) | |
| accelerator.print(f"Loaded {len(base_train_ds)} train samples, {len(base_test_ds)} test samples") | |
| else: | |
| dataset = ImageClsDataset.from_scratch(images_root, model_mapping, train_tf, real_root=args.real_root) | |
| num_ai_models = len([k for k in dataset.samples_dict.keys() if k != ImageClsDataset.REAL_MODEL_ID]) | |
| max_real_train = int(args.real_ratio * (max_sample_size * args.train_ratio) * num_ai_models) | |
| real_limit = max_real_train + args.real_test_count | |
| accelerator.print(f"Real images needed: {real_limit} (train: {max_real_train}, test: {args.real_test_count})") | |
| subset = dataset.crop_by_num_samples(max_sample_size, min_threshold=1000, real_limit=real_limit) | |
| base_train_ds, base_test_ds = subset.safe_split(args.train_ratio, real_test_count=args.real_test_count) | |
| base_test_ds.transform = test_tf | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| split_path = output_dir / "split_config.json" | |
| if accelerator.is_main_process: | |
| save_split_config(base_train_ds.get_split_config(), base_test_ds.get_split_config(), split_path) | |
| accelerator.print(f"Base dataset: {base_train_ds.num_classes} classes, {len(base_train_ds)} train, {len(base_test_ds)} test") | |
| real_class_idx = base_train_ds.real_class_idx | |
| if real_class_idx is not None: | |
| accelerator.print(f"Real images included as class {real_class_idx}") | |
| else: | |
| accelerator.print("No real images - only fake detection accuracy will be computed") | |
| # Train for each sample size | |
| all_results = {} | |
| for sample_size in sample_sizes: | |
| num_epochs = args.total_samples_per_model // sample_size | |
| accelerator.print(f"\nSample size {sample_size}: {num_epochs} epochs") | |
| exp_output_dir = output_dir / f"exp_{sample_size}" | |
| final_acc = train_with_sample_size( | |
| base_train_ds, | |
| base_test_ds, | |
| sample_size, | |
| num_epochs, | |
| args, | |
| accelerator, | |
| exp_output_dir, | |
| ) | |
| all_results[sample_size] = { | |
| 'num_epochs': num_epochs, | |
| 'final_accuracy': final_acc, | |
| } | |
| # Save summary | |
| if accelerator.is_main_process: | |
| summary_path = output_dir / "summary.json" | |
| with open(summary_path, "w") as f: | |
| json.dump(all_results, f, indent=2) | |
| accelerator.print(f"\nSaved summary to: {summary_path}") | |
| accelerator.print("\nAll training completed!") | |
| accelerator.print("\nResults summary:") | |
| for sample_size, result in all_results.items(): | |
| accelerator.print(f" Sample size {sample_size}: {result['num_epochs']} epochs, final acc {result['final_accuracy']:.4f}") | |
| if __name__ == "__main__": | |
| try: | |
| main() | |
| except Exception as e: | |
| print(f"Error: {e}", file=sys.stderr) | |
| sys.exit(1) | |