Download code/scripts/launch/train_joint_adaptation.py from Shining31/WildGen: direct link, hf CLI and curl.
- Browser
- Download file 13.7 kB
-
https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/scripts/launch/train_joint_adaptation.py
- Command line
-
hf download hf://datasets/Shining31/WildGen/code/scripts/launch/train_joint_adaptation.py
-
curl -L -o train_joint_adaptation.py https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/scripts/launch/train_joint_adaptation.py
13.7 kB
| #!/usr/bin/env python3 | |
| 'Evaluate a frozen checkpoint or fit a detector on joint source/target-domain samples.' | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import random | |
| import sys | |
| from pathlib import Path | |
| from typing import Any | |
| import torch | |
| import torch.nn as nn | |
| import torch.optim as optim | |
| 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 ManifestDataset(Dataset): | |
| def __init__(self, rows: list[dict[str, Any]], transform: T.Compose): | |
| self.rows = rows | |
| self.transform = 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") | |
| image = self.transform(image) | |
| except Exception as exc: | |
| raise RuntimeError(f"Unreadable benchmark image: {row['path']}") from exc | |
| return image, float(row["label"]), row.get("source", "unknown") | |
| class UnivFDModel(nn.Module): | |
| def __init__(self, device: str = "cpu", init_gain: float = 0.02): | |
| 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) | |
| nn.init.normal_(self.fc.weight, 0.0, init_gain) | |
| nn.init.zeros_(self.fc.bias) | |
| 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, init_gain: float = 0.02): | |
| super().__init__() | |
| self.backbone = models.resnet50(weights=models.ResNet50_Weights.IMAGENET1K_V1) | |
| self.backbone.fc = nn.Linear(self.backbone.fc.in_features, 1) | |
| 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 make_transforms(model_type: str, img_size: int = 224) -> tuple[T.Compose, T.Compose]: | |
| mean, std = (CLIP_MEAN, CLIP_STD) if model_type == "univfd" else (IMAGENET_MEAN, IMAGENET_STD) | |
| train_tf = T.Compose( | |
| [ | |
| T.RandomResizedCrop(img_size, scale=(0.6, 1.0)), | |
| T.RandomHorizontalFlip(), | |
| T.ToTensor(), | |
| T.Normalize(mean, std), | |
| ] | |
| ) | |
| test_tf = T.Compose( | |
| [ | |
| T.Resize(int(img_size * 1.15)), | |
| T.CenterCrop(img_size), | |
| T.ToTensor(), | |
| T.Normalize(mean, std), | |
| ] | |
| ) | |
| return train_tf, test_tf | |
| def build_model(model_type: str, device: str) -> nn.Module: | |
| if model_type == "univfd": | |
| return UnivFDModel(device=device) | |
| if model_type == "cnndetect": | |
| return CNNDetectModel() | |
| raise ValueError(f"Unsupported model_type: {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 save_checkpoint(model: nn.Module, model_type: str, path: Path) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| if model_type == "univfd": | |
| torch.save(model.fc.state_dict(), path) | |
| else: | |
| torch.save(model.state_dict(), path) | |
| def compute_metrics(labels: list[int], preds: list[int], sources: list[str]) -> dict[str, Any]: | |
| if not labels: | |
| return {} | |
| 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) | |
| per_source: dict[str, dict[str, int | float]] = {} | |
| for label, pred, source in zip(labels, preds, sources): | |
| if label != 1: | |
| continue | |
| stats = per_source.setdefault(source, {"correct": 0, "total": 0, "detection_rate": 0.0}) | |
| stats["total"] = int(stats["total"]) + 1 | |
| stats["correct"] = int(stats["correct"]) + int(pred == label) | |
| for stats in per_source.values(): | |
| stats["detection_rate"] = int(stats["correct"]) / max(1, int(stats["total"])) | |
| return { | |
| "balanced_accuracy": float(balanced_accuracy_score(labels, preds)), | |
| "accuracy": float(sum(int(p == y) for p, y in zip(preds, labels)) / 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, | |
| "per_fake_source": per_source, | |
| } | |
| def evaluate(model: nn.Module, loader: DataLoader, device: torch.device) -> dict[str, Any]: | |
| model.eval() | |
| labels: list[int] = [] | |
| preds: list[int] = [] | |
| sources: list[str] = [] | |
| for images, batch_labels, batch_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()) | |
| sources.extend(str(source) for source in batch_sources) | |
| return compute_metrics(labels, preds, sources) | |
| def train_one_epoch( | |
| model: nn.Module, | |
| loader: DataLoader, | |
| criterion: nn.Module, | |
| optimizer: optim.Optimizer, | |
| device: torch.device, | |
| epoch: int, | |
| num_epochs: int, | |
| ) -> dict[str, float]: | |
| model.train() | |
| if hasattr(model, "clip_model"): | |
| model.clip_model.eval() | |
| running_loss = 0.0 | |
| correct = 0 | |
| total = 0 | |
| for images, labels, _sources in tqdm(loader, desc=f"Epoch {epoch}/{num_epochs}", leave=False): | |
| images = images.to(device, non_blocking=True) | |
| labels = labels.to(device, non_blocking=True) | |
| optimizer.zero_grad(set_to_none=True) | |
| logits = model(images).squeeze(-1) | |
| loss = criterion(logits, labels) | |
| loss.backward() | |
| optimizer.step() | |
| running_loss += loss.item() * labels.numel() | |
| preds = (torch.sigmoid(logits) > 0.5).float() | |
| correct += (preds == labels).sum().item() | |
| total += labels.numel() | |
| return {"train_loss": running_loss / max(1, total), "train_acc": correct / max(1, total)} | |
| def validation_interval(num_epochs: int, num_validations: int) -> int: | |
| return max(1, num_epochs // max(1, num_validations)) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description="Train/evaluate a transfer binary adaptation job.") | |
| parser.add_argument("--model-type", choices=["univfd", "cnndetect"], required=True) | |
| parser.add_argument("--manifest", type=Path, required=True) | |
| parser.add_argument("--output-dir", type=Path, required=True) | |
| parser.add_argument("--checkpoint", type=Path, default=None) | |
| parser.add_argument("--strategy", choices=["zero_shot", "warm_start"], required=True) | |
| parser.add_argument("--epochs", type=int, default=None) | |
| parser.add_argument("--total-samples-per-source", type=int, default=9000) | |
| parser.add_argument("--num-validations", type=int, default=10) | |
| parser.add_argument("--batch-size", type=int, default=64) | |
| parser.add_argument("--num-workers", type=int, default=4) | |
| parser.add_argument("--lr", type=float, default=1e-4) | |
| 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 is not None and args.checkpoint.name not in {"fc_weights_final.pth", "model_final.pth"}: | |
| parser.error("Configured protocol requires a final-epoch checkpoint") | |
| random.seed(args.seed) | |
| torch.manual_seed(args.seed) | |
| with args.manifest.open("r", encoding="utf-8") as f: | |
| manifest = json.load(f) | |
| train_rows = manifest.get("train", []) | |
| test_rows = manifest.get("test", []) | |
| k_per_source = int(manifest.get("k_per_source", 0)) | |
| if args.epochs is None: | |
| args.epochs = 0 if args.strategy == "zero_shot" or k_per_source == 0 else max(1, args.total_samples_per_source // k_per_source) | |
| device = torch.device(args.device) | |
| train_tf, test_tf = make_transforms(args.model_type) | |
| model = build_model(args.model_type, args.device).to(device) | |
| if args.checkpoint is not None: | |
| load_checkpoint(model, args.model_type, args.checkpoint) | |
| model.to(device) | |
| elif args.strategy in {"zero_shot", "warm_start"}: | |
| raise ValueError(f"{args.strategy} requires --checkpoint") | |
| pin_memory = torch.cuda.is_available() | |
| test_loader = DataLoader( | |
| ManifestDataset(test_rows, test_tf), | |
| batch_size=args.batch_size, | |
| shuffle=False, | |
| num_workers=args.num_workers, | |
| pin_memory=pin_memory, | |
| ) | |
| history: list[dict[str, Any]] = [] | |
| best_metrics: dict[str, Any] | None = None | |
| if args.strategy != "zero_shot" and args.epochs > 0: | |
| if not train_rows: | |
| raise ValueError("Training strategy requires non-empty manifest train rows") | |
| train_loader = DataLoader( | |
| ManifestDataset(train_rows, train_tf), | |
| batch_size=args.batch_size, | |
| shuffle=True, | |
| num_workers=args.num_workers, | |
| pin_memory=pin_memory, | |
| ) | |
| criterion = nn.BCEWithLogitsLoss() | |
| if args.model_type == "univfd": | |
| optimizer = optim.AdamW(model.fc.parameters(), lr=args.lr, weight_decay=0.0) | |
| else: | |
| optimizer = optim.Adam(model.parameters(), lr=args.lr) | |
| interval = validation_interval(args.epochs, args.num_validations) | |
| best_balanced_acc = -1.0 | |
| for epoch in range(1, args.epochs + 1): | |
| train_metrics = train_one_epoch(model, train_loader, criterion, optimizer, device, epoch, args.epochs) | |
| validate_now = epoch == args.epochs or epoch % interval == 0 | |
| record: dict[str, Any] = {"epoch": epoch, "validated": validate_now, **train_metrics} | |
| if validate_now: | |
| metrics = evaluate(model, test_loader, device) | |
| record.update(metrics) | |
| if metrics.get("balanced_accuracy", -1.0) > best_balanced_acc: | |
| best_balanced_acc = float(metrics["balanced_accuracy"]) | |
| best_metrics = metrics | |
| print( | |
| f"Epoch {epoch}/{args.epochs}: train_acc={train_metrics['train_acc']:.4f} " | |
| f"bal_acc={metrics.get('balanced_accuracy', 0):.4f}" | |
| ) | |
| else: | |
| print(f"Epoch {epoch}/{args.epochs}: train_acc={train_metrics['train_acc']:.4f}") | |
| history.append(record) | |
| save_checkpoint( | |
| model, | |
| args.model_type, | |
| args.output_dir / ("fc_weights_final.pth" if args.model_type == "univfd" else "model_final.pth"), | |
| ) | |
| final_metrics = evaluate(model, test_loader, device) | |
| if best_metrics is None: | |
| best_metrics = final_metrics | |
| result = { | |
| "model_type": args.model_type, | |
| "strategy": args.strategy, | |
| "checkpoint": str(args.checkpoint) if args.checkpoint else None, | |
| "manifest": str(args.manifest), | |
| "manifest_name": manifest.get("name"), | |
| "k_per_source": k_per_source, | |
| "real_ratio": manifest.get("real_ratio"), | |
| "epochs": args.epochs, | |
| "train_count": len(train_rows), | |
| "test_count": len(test_rows), | |
| "diagnostic_best_metrics": best_metrics, | |
| "reporting_policy": "final_epoch", | |
| "final_metrics": final_metrics, | |
| "history": history, | |
| } | |
| args.output_dir.mkdir(parents=True, exist_ok=True) | |
| with (args.output_dir / "results.json").open("w", encoding="utf-8") as f: | |
| json.dump(result, f, indent=2, ensure_ascii=False) | |
| print(json.dumps({k: result[k] for k in ["model_type", "strategy", "k_per_source", "final_metrics"]}, indent=2)) | |
| if __name__ == "__main__": | |
| try: | |
| main() | |
| except Exception as exc: | |
| print(f"Error: {exc}", file=sys.stderr) | |
| raise | |