File size: 32,781 Bytes
f9ed2b4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 | #!/usr/bin/env python3
"""
Training script for UnivFD-style multi-class classification (per-model prediction).
Uses a frozen CLIP ViT-L/14 backbone with a trainable FC layer,
following the UniversalFakeDetect architecture but with multi-class
output for model identification instead of binary real/fake.
"""
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
from accelerate import Accelerator
from tqdm import tqdm
try:
import clip
except ImportError:
raise ImportError("Please install clip: pip install git+https://github.com/openai/CLIP.git")
# CLIP normalization statistics
CLIP_MEAN = [0.48145466, 0.4578275, 0.40821073]
CLIP_STD = [0.26862954, 0.26130258, 0.27577711]
ALLOWED_EXTS = {".jpg", ".jpeg", ".png", ".webp"}
@dataclass
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
@classmethod
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)
self.real_class_indices = [
class_idx for model_id, class_idx in self.model_id_to_class.items()
if model_id == self.REAL_MODEL_ID or model_id < 0
]
# 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))
@property
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()
real_keys = sorted(k for k in self.samples_dict.keys() if k == self.REAL_MODEL_ID or k < 0)
num_ai_models = len([k for k in self.samples_dict.keys() if k not in real_keys])
real_counts = {}
if real_ratio is not None and real_keys:
total_real = int(real_ratio * n_samples * num_ai_models)
base_count = total_real // len(real_keys)
remainder = total_real % len(real_keys)
real_counts = {
key: base_count + (1 if i < remainder else 0)
for i, key in enumerate(real_keys)
}
for key, v in self.samples_dict.items():
if key in real_counts:
subset[key] = v[:real_counts[key]]
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
@classmethod
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 UnivFDMulticlassModel(nn.Module):
"""
UnivFD-style model for multi-class classification: Frozen CLIP backbone + trainable FC layer.
Architecture:
Input -> CLIP ViT-L/14 (frozen) -> FC(768, num_classes) -> Logits
"""
def __init__(self, num_classes: int, init_gain: float = 0.02):
super().__init__()
# Load CLIP model (will be moved to device later by accelerate)
self.clip_model, _ = clip.load("ViT-L/14", device="cpu")
self.clip_model.eval()
# Freeze CLIP backbone
for param in self.clip_model.parameters():
param.requires_grad = False
# Trainable FC layer for multi-class classification
self.fc = nn.Linear(768, num_classes)
nn.init.normal_(self.fc.weight, 0.0, init_gain)
nn.init.zeros_(self.fc.bias)
def forward(self, x):
# Extract features with frozen backbone
with torch.no_grad():
features = self.clip_model.encode_image(x)
# Apply trainable FC layer
return self.fc(features.float())
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_clip_transforms(img_size: int = 224) -> Tuple[T.Compose, T.Compose]:
"""Create CLIP-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(CLIP_MEAN, CLIP_STD),
])
test_tf = T.Compose([
T.Resize(int(img_size * 1.15)),
T.CenterCrop(img_size),
T.ToTensor(),
T.Normalize(CLIP_MEAN, CLIP_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 cross-entropy loss."""
model.train()
if hasattr(model, "clip_model"):
model.clip_model.eval()
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:
images = images.to(device, non_blocking=True)
labels = labels.to(device, non_blocking=True)
optimizer.zero_grad(set_to_none=True)
outputs = model(images)
loss = criterion(outputs, labels)
accelerator.backward(loss)
optimizer.step()
running_loss += loss.item() * images.size(0)
preds = outputs.argmax(dim=1)
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 evaluate(
model: nn.Module,
loader: DataLoader,
criterion: nn.Module,
accelerator: Accelerator,
device: torch.device,
real_class_indices: List[int] = None,
num_classes: int = None
) -> Dict:
"""
Evaluate model with multi-class classification metrics.
Returns:
Dict with keys: 'loss', 'per_model_acc', 'top5_acc', 'ai_vs_real_acc',
'real_recall', 'confusion_matrix'
"""
model.eval()
running_loss = 0.0
correct_per_model = 0
correct_top5 = 0
correct_ai_vs_real = 0
total = 0
# Track real class recall
real_correct = 0
real_total = 0
# Track confusion matrix: confusion_matrix[true_label, pred_label]
if num_classes is not None:
confusion_matrix = torch.zeros(num_classes, num_classes, device=device, dtype=torch.long)
else:
confusion_matrix = None
real_class_set = set(real_class_indices or [])
with torch.no_grad():
for images, labels in loader:
images = images.to(device, non_blocking=True)
labels = labels.to(device, non_blocking=True)
outputs = model(images)
loss = criterion(outputs, labels)
running_loss += loss.item() * images.size(0)
preds = outputs.argmax(dim=1)
# Per-model accuracy (top-1)
correct_per_model += (preds == labels).sum().item()
# Top-5 accuracy
if num_classes is not None and num_classes >= 5:
_, top5_preds = outputs.topk(5, dim=1)
top5_correct = top5_preds.eq(labels.view(-1, 1).expand_as(top5_preds))
correct_top5 += top5_correct.any(dim=1).sum().item()
else:
# If less than 5 classes, top-5 is same as checking if prediction exists
correct_top5 += (preds == labels).sum().item()
# Update confusion matrix
if num_classes is not None:
for t, p in zip(labels, preds):
confusion_matrix[t, p] += 1
# AI vs Real accuracy (binary classification)
if real_class_set:
labels_real_mask = torch.zeros_like(labels, dtype=torch.bool)
preds_real_mask = torch.zeros_like(preds, dtype=torch.bool)
for class_idx in real_class_set:
labels_real_mask |= labels == class_idx
preds_real_mask |= preds == class_idx
labels_binary = (~labels_real_mask).long()
preds_binary = (~preds_real_mask).long()
correct_ai_vs_real += (preds_binary == labels_binary).sum().item()
# Track real class recall
real_total += labels_real_mask.sum().item()
real_correct += ((preds == labels) & labels_real_mask).sum().item()
total += labels.size(0)
# Reduce metrics across processes
loss_tensor = torch.tensor([running_loss], device=device)
correct_per_model_tensor = torch.tensor([correct_per_model], device=device)
correct_top5_tensor = torch.tensor([correct_top5], device=device)
correct_ai_vs_real_tensor = torch.tensor([correct_ai_vs_real], 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)
loss_sum = accelerator.reduce(loss_tensor, reduction="sum").item()
correct_per_model_sum = accelerator.reduce(correct_per_model_tensor, reduction="sum").item()
correct_top5_sum = accelerator.reduce(correct_top5_tensor, reduction="sum").item()
correct_ai_vs_real_sum = accelerator.reduce(correct_ai_vs_real_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()
# Reduce confusion matrix across processes
if num_classes is not None:
confusion_matrix = accelerator.reduce(confusion_matrix, reduction="sum")
confusion_matrix_list = confusion_matrix.cpu().tolist()
else:
confusion_matrix_list = None
avg_loss = loss_sum / max(1, total_sum)
per_model_acc = correct_per_model_sum / max(1, total_sum)
top5_acc = correct_top5_sum / max(1, total_sum)
ai_vs_real_acc = correct_ai_vs_real_sum / max(1, total_sum) if real_class_set else None
real_recall = real_correct_sum / max(1, real_total_sum) if real_class_set and real_total_sum > 0 else None
return {
'loss': avg_loss,
'per_model_acc': per_model_acc,
'top5_acc': top5_acc,
'ai_vs_real_acc': ai_vs_real_acc,
'real_recall': real_recall,
'confusion_matrix': confusion_matrix_list,
}
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:
# Save only the FC layer weights (like UnivFD)
fc_path = output_dir / "fc_weights_best.pth"
torch.save(model.fc.state_dict(), fc_path)
print(f"Saved best FC weights to: {fc_path}")
if is_final:
fc_path = output_dir / "fc_weights_final.pth"
torch.save(model.fc.state_dict(), fc_path)
print(f"Saved final FC weights to: {fc_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_clip_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
# Count samples
real_model_ids = {k for k in sub_train_ds.samples_dict if k == ImageClsDataset.REAL_MODEL_ID or k < 0}
real_train_count = sum(len(v) for k, v in sub_train_ds.samples_dict.items() if k in real_model_ids)
ai_train_count = sum(len(v) for k, v in sub_train_ds.samples_dict.items() if k not in real_model_ids)
accelerator.print(f"Train samples: {len(sub_train_ds)} (Real: {real_train_count}, AI: {ai_train_count})")
accelerator.print(f"Test samples: {len(test_ds)}")
accelerator.print(f"Number of classes: {sub_train_ds.num_classes}")
pin_memory = torch.cuda.is_available()
train_loader = DataLoader(
sub_train_ds, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers, pin_memory=pin_memory
)
test_loader = DataLoader(
test_ds, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=pin_memory
)
device = accelerator.device
model = UnivFDMulticlassModel(num_classes=sub_train_ds.num_classes, init_gain=args.init_gain)
criterion = nn.CrossEntropyLoss()
# Only optimize FC layer parameters
optimizer = optim.AdamW(model.fc.parameters(), lr=args.lr, weight_decay=args.weight_decay)
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_classes = sub_train_ds.num_classes
real_class_indices = sub_train_ds.real_class_indices
best_confusion_matrix = None
best_top5_acc = -1.0
best_real_recall = -1.0
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,
'per_model_acc': None,
'top5_acc': None,
'ai_vs_real_acc': None,
'real_recall': None,
'confusion_matrix': None,
})
continue
metrics = evaluate(
model, test_loader, criterion, accelerator, device,
real_class_indices=real_class_indices, num_classes=num_classes
)
test_loss = metrics['loss']
per_model_acc = metrics['per_model_acc']
top5_acc = metrics['top5_acc']
ai_vs_real_acc = metrics['ai_vs_real_acc']
real_recall = metrics['real_recall']
confusion_matrix = metrics['confusion_matrix']
# 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} top1 {per_model_acc:.4f} top5 {top5_acc:.4f}"
)
if real_recall is not None:
output_str += f" real_recall {real_recall:.4f}"
if ai_vs_real_acc is not None:
output_str += f" ai-vs-real {ai_vs_real_acc:.4f}"
accelerator.print(output_str)
is_best = per_model_acc > best_acc
if is_best:
best_acc = per_model_acc
best_top5_acc = top5_acc
best_real_recall = real_recall if real_recall is not None else -1.0
best_confusion_matrix = confusion_matrix
# 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,
'per_model_acc': per_model_acc,
'top5_acc': top5_acc,
'ai_vs_real_acc': ai_vs_real_acc,
'real_recall': real_recall,
'confusion_matrix': confusion_matrix,
})
# 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),
'num_classes': num_classes,
'best_per_model_acc': best_acc,
'best_top5_acc': best_top5_acc,
'best_real_recall': best_real_recall if best_real_recall >= 0 else None,
'final_per_model_acc': final_metrics.get('per_model_acc'),
'final_top5_acc': final_metrics.get('top5_acc'),
'final_real_recall': final_metrics.get('real_recall'),
'best_confusion_matrix': best_confusion_matrix,
'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['per_model_acc'], final_metrics['top5_acc'], final_metrics['real_recall']
def parse_args():
parser = argparse.ArgumentParser(description="Train UnivFD-style multi-class classifier (per-model prediction).")
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_univfd_multiclass",
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 (UnivFD default: 1e-4)")
parser.add_argument("--weight-decay", type=float, default=0.0, help="Weight decay for AdamW")
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("--split-file", type=str, required=True,
help="Path to split config JSON. If provided, reuse this split")
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("--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("UnivFD-style Multi-class Classification Training")
accelerator.print("=" * 60)
accelerator.print(f"Model: CLIP ViT-L/14 (frozen) + FC layer (trainable)")
accelerator.print(f"Task: Multi-class classification (per-model prediction)")
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_clip_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_indices = base_train_ds.real_class_indices
if real_class_indices:
accelerator.print(f"Real images included as classes {real_class_indices}")
else:
accelerator.print("No real images - AI-vs-real accuracy will not 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, final_top5, final_recall = 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_per_model_acc': final_acc,
'final_top5_acc': final_top5,
'final_real_recall': final_recall,
}
# 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():
output_str = f" Sample size {sample_size}: {result['num_epochs']} epochs, top1 {result['final_per_model_acc']:.4f}, top5 {result['final_top5_acc']:.4f}"
if result['final_real_recall'] is not None:
output_str += f", real_recall {result['final_real_recall']:.4f}"
accelerator.print(output_str)
if __name__ == "__main__":
try:
main()
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
|