File size: 34,262 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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
#!/usr/bin/env python3
"""

Training script for UnivFD-style binary classification (Real vs Fake).



Uses a frozen CLIP ViT-L/14 backbone with a trainable FC layer,

following the UniversalFakeDetect architecture but with the same

data sampling strategy as train.py.

"""
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)

        # 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()
        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

    @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 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

    @property
    def samples_dict(self):
        return self.base_dataset.samples_dict


class UnivFDModel(nn.Module):
    """

    UnivFD-style model: Frozen CLIP backbone + trainable FC layer.



    Architecture:

        Input -> CLIP ViT-L/14 (frozen) -> FC(768, 1) -> Logit

    """

    def __init__(self, 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
        self.fc = nn.Linear(768, 1)
        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 BCE 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:  # 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 scores for both real and fake classes.



    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)
    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:
        # 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

    # 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 = UnivFDModel(init_gain=args.init_gain)
    criterion = nn.BCEWithLogitsLoss()

    # 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_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,
                'balanced_acc': None,
                'f1_real': None,
                'f1_fake': 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 UnivFD-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_univfd",
                       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("--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("UnivFD-style Binary Classification Training")
    accelerator.print("=" * 60)
    accelerator.print(f"Model: CLIP ViT-L/14 (frozen) + FC layer (trainable)")
    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_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_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)