File size: 9,604 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
#!/usr/bin/env python3
'Evaluate final binary checkpoints under JPEG compression and resize perturbations.'

from __future__ import annotations

import argparse
import io
import json
import random
from pathlib import Path
from typing import Any

import torch
import torch.nn as nn
import torchvision.models as models
import torchvision.transforms as T
from PIL import Image
from sklearn.metrics import balanced_accuracy_score, f1_score, precision_score, recall_score
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm

try:
    import clip
except ImportError:
    clip = None


IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]
CLIP_MEAN = [0.48145466, 0.4578275, 0.40821073]
CLIP_STD = [0.26862954, 0.26130258, 0.27577711]


class JPEGCompression:
    def __init__(self, quality_low: int, quality_high: int):
        self.quality_low = quality_low
        self.quality_high = quality_high

    def __call__(self, img: Image.Image) -> Image.Image:
        quality = random.randint(self.quality_low, self.quality_high)
        buf = io.BytesIO()
        img.save(buf, format="JPEG", quality=quality)
        buf.seek(0)
        return Image.open(buf).convert("RGB")


class ResizeRoundtrip:
    def __init__(self, scale: float):
        self.scale = scale

    def __call__(self, img: Image.Image) -> Image.Image:
        width, height = img.size
        down = (max(1, int(width * self.scale)), max(1, int(height * self.scale)))
        return img.resize(down, Image.BICUBIC).resize((width, height), Image.BICUBIC)


class ComposePIL:
    def __init__(self, transforms: list[Any]):
        self.transforms = transforms

    def __call__(self, img: Image.Image) -> Image.Image:
        for transform in self.transforms:
            img = transform(img)
        return img


class BinarySplitDataset(Dataset):
    def __init__(self, rows: list[dict[str, Any]], transform: T.Compose, pre_transform: Any = None):
        self.rows = rows
        self.transform = transform
        self.pre_transform = pre_transform

    def __len__(self) -> int:
        return len(self.rows)

    def __getitem__(self, idx: int):
        row = self.rows[idx]
        try:
            image = Image.open(row["path"]).convert("RGB")
            if self.pre_transform is not None:
                image = self.pre_transform(image)
            image = self.transform(image)
        except Exception as exc:
            raise RuntimeError(f"Unreadable benchmark image: {row['path']}") from exc
        return image, float(row["label"]), row["source"]


class UnivFDModel(nn.Module):
    def __init__(self, device: str = "cpu"):
        super().__init__()
        if clip is None:
            raise ImportError("Please install clip for UnivFD experiments")
        self.clip_model, _ = clip.load("ViT-L/14", device=device)
        self.clip_model.eval()
        for param in self.clip_model.parameters():
            param.requires_grad = False
        self.fc = nn.Linear(768, 1)

    def forward(self, x):
        with torch.no_grad():
            features = self.clip_model.encode_image(x)
        return self.fc(features.float())


class CNNDetectModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.backbone = models.resnet50(weights=None)
        self.backbone.fc = nn.Linear(self.backbone.fc.in_features, 1)

    def forward(self, x):
        return self.backbone(x)


def make_transform(model_type: str, img_size: int = 224) -> T.Compose:
    mean, std = (CLIP_MEAN, CLIP_STD) if model_type == "univfd" else (IMAGENET_MEAN, IMAGENET_STD)
    return T.Compose(
        [
            T.Resize(int(img_size * 1.15)),
            T.CenterCrop(img_size),
            T.ToTensor(),
            T.Normalize(mean, std),
        ]
    )


def build_model(model_type: str, device: str):
    if model_type == "univfd":
        return UnivFDModel(device=device)
    if model_type == "cnndetect":
        return CNNDetectModel()
    raise ValueError(model_type)


def load_checkpoint(model: nn.Module, model_type: str, checkpoint: Path) -> None:
    state = torch.load(checkpoint, map_location="cpu")
    if model_type == "univfd":
        model.fc.load_state_dict(state)
    else:
        model.load_state_dict(state)


def load_test_rows(split_file: Path) -> list[dict[str, Any]]:
    with split_file.open("r", encoding="utf-8") as f:
        split = json.load(f)
    rows = []
    for model_id, paths in split["test"].items():
        label = 0 if int(model_id) == 0 else 1
        source = "real" if label == 0 else str(model_id)
        rows.extend({"path": path, "label": label, "source": source} for path in paths)
    return rows


def compute_metrics(labels: list[int], preds: list[int]) -> dict[str, Any]:
    real_total = sum(1 for label in labels if label == 0)
    fake_total = sum(1 for label in labels if label == 1)
    real_correct = sum(1 for label, pred in zip(labels, preds) if label == 0 and pred == 0)
    fake_correct = sum(1 for label, pred in zip(labels, preds) if label == 1 and pred == 1)
    return {
        "balanced_accuracy": float(balanced_accuracy_score(labels, preds)),
        "accuracy": float(sum(int(p == y) for p, y in zip(preds, labels)) / max(1, len(labels))),
        "f1_real": float(f1_score(labels, preds, pos_label=0, zero_division=0)),
        "f1_fake": float(f1_score(labels, preds, pos_label=1, zero_division=0)),
        "precision_real": float(precision_score(labels, preds, pos_label=0, zero_division=0)),
        "recall_real": float(recall_score(labels, preds, pos_label=0, zero_division=0)),
        "precision_fake": float(precision_score(labels, preds, pos_label=1, zero_division=0)),
        "recall_fake": float(recall_score(labels, preds, pos_label=1, zero_division=0)),
        "real_accuracy": real_correct / max(1, real_total),
        "fake_accuracy": fake_correct / max(1, fake_total),
        "num_real": real_total,
        "num_fake": fake_total,
    }


@torch.no_grad()
def evaluate(model: nn.Module, loader: DataLoader, device: torch.device) -> dict[str, Any]:
    labels: list[int] = []
    preds: list[int] = []
    model.eval()
    for images, batch_labels, _sources in tqdm(loader, desc="Evaluating", leave=False):
        images = images.to(device, non_blocking=True)
        logits = model(images).squeeze(-1)
        batch_preds = (torch.sigmoid(logits) > 0.5).long().cpu().tolist()
        preds.extend(int(pred) for pred in batch_preds)
        labels.extend(int(label) for label in batch_labels.tolist())
    return compute_metrics(labels, preds)


def main() -> None:
    parser = argparse.ArgumentParser(description="Evaluate binary checkpoint robustness.")
    parser.add_argument("--model-type", choices=["univfd", "cnndetect"], required=True)
    parser.add_argument("--checkpoint", type=Path, required=True)
    parser.add_argument("--split-file", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--batch-size", type=int, default=64)
    parser.add_argument("--num-workers", type=int, default=4)
    parser.add_argument("--quality-low", type=int, default=30)
    parser.add_argument("--quality-high", type=int, default=95)
    parser.add_argument("--resize-scale", type=float, default=0.5)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu")
    args = parser.parse_args()
    if args.checkpoint.name not in {"fc_weights_final.pth", "model_final.pth"}:
        parser.error("Configured robustness protocol requires a final-epoch checkpoint")

    random.seed(args.seed)
    torch.manual_seed(args.seed)
    device = torch.device(args.device)
    rows = load_test_rows(args.split_file)
    model = build_model(args.model_type, args.device)
    load_checkpoint(model, args.model_type, args.checkpoint)
    model.to(device)
    transform = make_transform(args.model_type)
    variants = {
        "clean": None,
        "jpeg": JPEGCompression(args.quality_low, args.quality_high),
        "resize": ResizeRoundtrip(args.resize_scale),
        "jpeg_resize": ComposePIL([JPEGCompression(args.quality_low, args.quality_high), ResizeRoundtrip(args.resize_scale)]),
    }

    results: dict[str, Any] = {}
    pin_memory = torch.cuda.is_available()
    for variant_name, pre_transform in variants.items():
        loader = DataLoader(
            BinarySplitDataset(rows, transform, pre_transform=pre_transform),
            batch_size=args.batch_size,
            shuffle=False,
            num_workers=args.num_workers,
            pin_memory=pin_memory,
        )
        results[variant_name] = evaluate(model, loader, device)
        print(f"{variant_name}: bal_acc={results[variant_name]['balanced_accuracy']:.4f}")

    output = {
        "model_type": args.model_type,
        "checkpoint": str(args.checkpoint),
        "split_file": str(args.split_file),
        "quality_range": [args.quality_low, args.quality_high],
        "resize_scale": args.resize_scale,
        "results": results,
    }
    args.output.parent.mkdir(parents=True, exist_ok=True)
    with args.output.open("w", encoding="utf-8") as f:
        json.dump(output, f, indent=2, ensure_ascii=False)
    print(json.dumps(output, indent=2))


if __name__ == "__main__":
    main()