Download code/scripts/eval/evaluate_robustness.py from Shining31/WildGen: direct link, hf CLI and curl.
- Browser
- Download file 9.6 kB
-
https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/scripts/eval/evaluate_robustness.py
- Command line
-
hf download hf://datasets/Shining31/WildGen/code/scripts/eval/evaluate_robustness.py
-
curl -L -o evaluate_robustness.py https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/scripts/eval/evaluate_robustness.py
9.6 kB
| #!/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, | |
| } | |
| 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() | |