Spaces:
Sleeping
Sleeping
Download mdmf_inference.py from kchromatic3/mdmf-api: direct link, hf CLI and curl.
- Browser
- Download file 21 kB
-
https://huggingface.co/spaces/kchromatic3/mdmf-api/resolve/main/mdmf_inference.py
- Command line
-
hf download hf://spaces/kchromatic3/mdmf-api/mdmf_inference.py
-
curl -L -o mdmf_inference.py https://huggingface.co/spaces/kchromatic3/mdmf-api/resolve/main/mdmf_inference.py
21 kB
| """ | |
| MDMF single-image inference: real/fake prediction + MIL-CAM heatmap. | |
| Two trained variants: | |
| - "imagenet": trained on ProGAN/ImageNet256 (MDMF paper main result) | |
| - "sdv14": trained on SDv1.4 / GenImage (cross-generator benchmark) | |
| CLI: | |
| python mdmf_inference.py --variant imagenet --image img.png --output_dir out/ | |
| python mdmf_inference.py --variant sdv14 --image img.png --output_dir out/ | |
| Library: | |
| from mdmf_inference import MDMFInference | |
| engine = MDMFInference(variant="imagenet") | |
| result = engine.predict("img.png", output_dir="out/") | |
| # result = {"label": "fake"|"real", "score": float, "threshold": float, | |
| # "patch_scores": 7x7 list, "outputs": {...paths...}} | |
| """ | |
| import os | |
| import sys | |
| import json | |
| import math | |
| import pickle | |
| import argparse | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| from torch import nn | |
| from torchvision import transforms | |
| from PIL import Image | |
| import cv2 | |
| import matplotlib.pyplot as plt | |
| from matplotlib.patches import Rectangle | |
| PACKAGE_DIR = Path(__file__).resolve().parent | |
| # ============================================================================== | |
| # Variant registry. | |
| # | |
| # Each variant packages a (checkpoint, ref_artifacts, threshold) triple. | |
| # | |
| # threshold = median of per-dataset best_thresholds reported in the corresponding | |
| # test_results.json. For imagenet this matches the sklearn-ROC balanced-accuracy | |
| # optimum (~-7.70); for sdv14 it's the median over the 8 GenImage generators. | |
| # | |
| # imagenet: MDMF paper checkpoint β ImageNet256, 3k ProGAN-style refs. | |
| # threshold -7.698649 β ~93% real acc / ~88% fake acc on ImageNet256 | |
| # + 9 generators. | |
| # sdv14: GenImage Origin_AdamW_7kref_2 checkpoint β 6938 GenImage refs. | |
| # threshold -4.8285 β ~90% real acc / ~88% fake acc on GenImage. | |
| # ============================================================================== | |
| VARIANTS = { | |
| "imagenet": { | |
| "checkpoint": str(PACKAGE_DIR / "checkpoints" / "imagenet.pth"), | |
| "ref_artifacts": str(PACKAGE_DIR / "embeddings" / "imagenet_ref_artifacts.pkl"), | |
| "ref_embeddings": str(PACKAGE_DIR / "embeddings" / "imagenet_ref_embeddings.pkl"), | |
| "threshold": -7.698649, | |
| "description": "MDMF paper β ImageNet256 / 3k ProGAN refs", | |
| }, | |
| "sdv14": { | |
| "checkpoint": str(PACKAGE_DIR / "checkpoints" / "sdv14.pth"), | |
| "ref_artifacts": str(PACKAGE_DIR / "embeddings" / "sdv14_ref_artifacts.pkl"), | |
| "ref_embeddings": str(PACKAGE_DIR / "embeddings" / "sdv14_ref_embeddings.pkl"), | |
| "threshold": -4.8285, | |
| "description": "SDv1.4 / GenImage β 7k refs", | |
| }, | |
| } | |
| DEFAULT_VARIANT = "imagenet" | |
| # ============================================================================== | |
| # Model β copied from MDMF/src/test_MDMF.py (MMD_MIL_Detector) | |
| # ============================================================================== | |
| class MMD_MIL_Detector(nn.Module): | |
| def __init__(self, embed_dim=1024, hidden_dim=256, dropout=0.3, init_sigma=1.0): | |
| super().__init__() | |
| self.embed_dim = embed_dim | |
| self.log_sigma = nn.Parameter( | |
| torch.log(torch.tensor([init_sigma])), requires_grad=True | |
| ) | |
| self.score_head = nn.Sequential( | |
| nn.Linear(embed_dim, hidden_dim), | |
| nn.ReLU(), | |
| nn.Dropout(dropout), | |
| nn.Linear(hidden_dim, hidden_dim // 2), | |
| nn.ReLU(), | |
| nn.Dropout(dropout), | |
| nn.Linear(hidden_dim // 2, 1), | |
| nn.Tanh(), | |
| ) | |
| def get_sigma(self): | |
| return torch.exp(self.log_sigma.clamp(min=-3.0, max=3.0)) | |
| def compute_logits(self, embeddings, mask=None): | |
| B, K, D = embeddings.shape | |
| embeddings = F.normalize(embeddings, p=2, dim=-1) | |
| flat = embeddings.view(B * K, D) | |
| logits = self.score_head(flat).view(B, K) | |
| if mask is not None: | |
| logits = logits.masked_fill(~mask, 0.0) | |
| return logits | |
| # ============================================================================== | |
| # DINOv2 helpers | |
| # ============================================================================== | |
| def get_patch_tokens(backbone, x): | |
| if hasattr(backbone, "forward_features"): | |
| out = backbone.forward_features(x) | |
| else: | |
| out = backbone(x) | |
| if isinstance(out, dict): | |
| tokens = None | |
| for key in ["x_norm_patchtokens", "patch_tokens", "tokens"]: | |
| if key in out: | |
| tokens = out[key] | |
| break | |
| if tokens is None: | |
| for key in ["x_norm", "x"]: | |
| if key in out: | |
| t = out[key] | |
| if t.dim() == 3 and t.size(1) > 1: | |
| tokens = t[:, 1:, :] | |
| break | |
| if tokens is None: | |
| raise RuntimeError( | |
| f"Cannot find patch tokens in output keys: {list(out.keys())}" | |
| ) | |
| else: | |
| if isinstance(out, (list, tuple)): | |
| out = out[0] | |
| if not torch.is_tensor(out): | |
| raise RuntimeError(f"Unsupported backbone output type: {type(out)}") | |
| if out.dim() == 3 and out.size(1) > 1: | |
| tokens = out[:, 1:, :] | |
| else: | |
| raise RuntimeError(f"Cannot interpret backbone output shape {out.shape}") | |
| return tokens | |
| def pool_tokens_to_patch_size(tokens, patch_size, image_size=224): | |
| B, N, D = tokens.shape | |
| H_t = int(math.sqrt(N)) | |
| if H_t * H_t != N: | |
| raise ValueError(f"Token count {N} is not a perfect square") | |
| grid_size = image_size // patch_size | |
| if grid_size < 1: | |
| raise ValueError(f"Patch size {patch_size} too large") | |
| tokens_spatial = tokens.view(B, H_t, H_t, D).permute(0, 3, 1, 2) | |
| pooled = F.adaptive_avg_pool2d(tokens_spatial, output_size=(grid_size, grid_size)) | |
| pooled = pooled.permute(0, 2, 3, 1).contiguous().view(B, grid_size * grid_size, D) | |
| return pooled | |
| # ============================================================================== | |
| # Scoring β -logit(xy) scorer from mil_detector/ImageNet/test_mil_mmd_v3.py. | |
| # ============================================================================== | |
| def precompute_ref_norm2(ref_X): | |
| return (ref_X ** 2).sum(dim=1, keepdim=True) | |
| def score_logit_xy_batch(ref_X, ref_norm2, Y, sigma, epsilon=1e-8): | |
| """Score = -log(xy / (1-xy)) where xy = mean_i exp(-||ref_i - y||^2 / (2 sigma^2)).""" | |
| sigma = sigma + epsilon | |
| Y_norm2 = (Y ** 2).sum(dim=1, keepdim=True) | |
| dist = ref_norm2 + Y_norm2.t() - 2.0 * (ref_X @ Y.t()) | |
| kxy = torch.exp(-dist / (2.0 * sigma ** 2)) | |
| xy = kxy.mean(dim=0).clamp(min=1e-6, max=1 - 1e-6) | |
| return -(torch.log(xy) - torch.log(1.0 - xy)) | |
| # ============================================================================== | |
| # Visualization β ported from mil_detector/visualization/compare_global_vs_pfs_detailed.py | |
| # ============================================================================== | |
| def create_heatmap_from_cam(cam, grid_size, target_size=(224, 224)): | |
| if cam.size == 1: | |
| return np.ones(target_size) * cam.item() | |
| heatmap_2d = cam.reshape(grid_size, grid_size) | |
| return cv2.resize(heatmap_2d, (target_size[1], target_size[0]), | |
| interpolation=cv2.INTER_CUBIC) | |
| def _add_patch_grid(ax, grid_size, image_size=224, linewidth=2.0): | |
| patch_pixel_size = image_size / grid_size | |
| for i in range(grid_size): | |
| for j in range(grid_size): | |
| x = j * patch_pixel_size | |
| y = i * patch_pixel_size | |
| rect = Rectangle((x, y), patch_pixel_size, patch_pixel_size, | |
| linewidth=linewidth, edgecolor='white', | |
| facecolor='none', alpha=0.8) | |
| ax.add_patch(rect) | |
| def save_original(image_np, path, dpi=300): | |
| fig, ax = plt.subplots(figsize=(6, 6)) | |
| ax.imshow(image_np) | |
| ax.axis('off') | |
| plt.subplots_adjust(left=0, right=1, top=1, bottom=0) | |
| plt.savefig(path, dpi=dpi, bbox_inches='tight', pad_inches=0) | |
| plt.close() | |
| def save_heatmap(heatmap, path, cmap='jet', dpi=300): | |
| fig, ax = plt.subplots(figsize=(6, 6)) | |
| im = ax.imshow(heatmap, cmap=cmap, vmin=0, vmax=1) | |
| ax.axis('off') | |
| cbar = plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04) | |
| cbar.ax.tick_params(labelsize=10) | |
| plt.subplots_adjust(left=0, right=0.9, top=1, bottom=0) | |
| plt.savefig(path, dpi=dpi, bbox_inches='tight', pad_inches=0) | |
| plt.close() | |
| def save_overlay_with_grid(image_np, heatmap, grid_size, path, | |
| heatmap_weight=0.6, dpi=300): | |
| fig, ax = plt.subplots(figsize=(6, 6), dpi=dpi) | |
| ax.imshow(image_np) | |
| _add_patch_grid(ax, grid_size, image_size=224, linewidth=2.0) | |
| ax.axis('off') | |
| plt.subplots_adjust(left=0, right=1, top=1, bottom=0) | |
| fig.canvas.draw() | |
| buf = np.frombuffer(fig.canvas.buffer_rgba(), dtype=np.uint8) | |
| h, w = fig.canvas.get_width_height() | |
| image_with_grid = buf.reshape(h, w, 4)[:, :, :3] | |
| plt.close(fig) | |
| if image_with_grid.shape[:2] != (224, 224): | |
| image_with_grid = cv2.resize(image_with_grid, (224, 224)) | |
| heat = np.clip(heatmap.astype(np.float32), 0.0, 1.0) | |
| heat_u8 = np.clip(heat * 255.0, 0, 255).astype(np.uint8) | |
| heatmap_colored = cv2.applyColorMap(heat_u8, cv2.COLORMAP_JET) | |
| heatmap_colored = cv2.cvtColor(heatmap_colored, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0 | |
| image_with_grid_normalized = image_with_grid.astype(np.float32) / 255.0 | |
| overlay = heatmap_weight * heatmap_colored + (1 - heatmap_weight) * image_with_grid_normalized | |
| overlay = np.clip(overlay * 255.0, 0, 255).astype(np.uint8) | |
| fig, ax = plt.subplots(figsize=(6, 6)) | |
| ax.imshow(overlay) | |
| ax.axis('off') | |
| plt.subplots_adjust(left=0, right=1, top=1, bottom=0) | |
| plt.savefig(path, dpi=dpi, bbox_inches='tight', pad_inches=0) | |
| plt.close() | |
| def save_patch_scores_txt(mil_cam, grid_size, path): | |
| scores_2d = mil_cam.reshape(grid_size, grid_size) | |
| with open(path, 'w') as f: | |
| f.write(f"# Patch Scores Matrix ({grid_size}x{grid_size})\n") | |
| f.write(f"# Score range: [{mil_cam.min():.4f}, {mil_cam.max():.4f}]\n") | |
| f.write(f"# Mean: {mil_cam.mean():.4f}, Std: {mil_cam.std():.4f}\n") | |
| f.write("#" + "=" * 68 + "\n\n") | |
| f.write(f"Z{grid_size} = np.array([\n") | |
| for i in range(grid_size): | |
| f.write(" [") | |
| for j in range(grid_size): | |
| s = scores_2d[i, j] | |
| f.write(f"{s:.4f}" + ("" if j == grid_size - 1 else ", ")) | |
| f.write("],\n") | |
| f.write("], dtype=float)\n") | |
| # ============================================================================== | |
| # Engine | |
| # ============================================================================== | |
| class MDMFInference: | |
| def __init__( | |
| self, | |
| variant: str = DEFAULT_VARIANT, | |
| checkpoint_path: str = None, | |
| ref_artifacts_path: str = None, | |
| ref_embeddings_path: str = None, | |
| threshold: float = None, | |
| device: str = None, | |
| verbose: bool = True, | |
| ): | |
| if variant not in VARIANTS: | |
| raise ValueError( | |
| f"Unknown variant '{variant}'. Known: {list(VARIANTS)}" | |
| ) | |
| cfg = VARIANTS[variant] | |
| self.variant = variant | |
| self.checkpoint_path = checkpoint_path or cfg["checkpoint"] | |
| self.ref_artifacts_path = ref_artifacts_path or cfg["ref_artifacts"] | |
| self.ref_embeddings_path = ref_embeddings_path or cfg["ref_embeddings"] | |
| self.threshold = cfg["threshold"] if threshold is None else float(threshold) | |
| self.verbose = verbose | |
| if device is None: | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| self.device = torch.device(device) | |
| self._log(f"variant={variant} ({cfg['description']}) device={self.device}") | |
| self._load_model() | |
| self._load_backbone() | |
| self._load_reference() | |
| self.transform = transforms.Compose([ | |
| transforms.Resize((224, 224)), | |
| transforms.ToTensor(), | |
| transforms.Normalize(mean=[0.485, 0.456, 0.406], | |
| std=[0.229, 0.224, 0.225]), | |
| ]) | |
| def _log(self, msg): | |
| if self.verbose: | |
| print(f"[MDMF] {msg}") | |
| def _load_model(self): | |
| self._log(f"Loading checkpoint {self.checkpoint_path}") | |
| ckpt = torch.load(self.checkpoint_path, map_location=self.device, weights_only=False) | |
| cfg = ckpt['config'] | |
| self.patch_size = int(cfg.get('patch_size', 32)) | |
| self.model = MMD_MIL_Detector( | |
| embed_dim=cfg['embed_dim'], | |
| hidden_dim=cfg['hidden_dim'], | |
| dropout=cfg['dropout'], | |
| init_sigma=cfg['init_sigma'], | |
| ).to(self.device) | |
| self.model.load_state_dict(ckpt['model_state_dict']) | |
| self.model.eval() | |
| self.sigma = self.model.get_sigma().detach() | |
| self._log(f"sigma={self.sigma.item():.4f}, patch_size={self.patch_size}") | |
| def _load_backbone(self): | |
| self._log("Loading DINOv2 ViT-L/14 backbone (first time downloads)") | |
| self.backbone = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14', | |
| verbose=False).to(self.device) | |
| self.backbone.eval() | |
| def _load_reference(self): | |
| """ | |
| Prefers artifacts (tiny precomputed pkl) over raw embeddings. | |
| Fallback paths: | |
| 1. artifacts exist AND sigma matches β load artifacts | |
| 2. raw embeddings exist β rebuild artifacts, save, load | |
| 3. neither β error | |
| """ | |
| art = None | |
| if os.path.exists(self.ref_artifacts_path): | |
| self._log(f"Loading ref artifacts: {self.ref_artifacts_path}") | |
| with open(self.ref_artifacts_path, 'rb') as f: | |
| art = pickle.load(f) | |
| if abs(float(art.get('sigma', -1)) - float(self.sigma.item())) > 1e-5: | |
| self._log( | |
| f" sigma mismatch (artifacts={art.get('sigma')} vs model=" | |
| f"{self.sigma.item()}) β rebuilding" | |
| ) | |
| art = None | |
| if art is None: | |
| if not os.path.exists(self.ref_embeddings_path): | |
| raise FileNotFoundError( | |
| f"Neither ref_artifacts ({self.ref_artifacts_path}) nor raw " | |
| f"ref_embeddings ({self.ref_embeddings_path}) are present. " | |
| f"Supply one of them." | |
| ) | |
| art = self._build_artifacts(self.ref_embeddings_path) | |
| os.makedirs(os.path.dirname(self.ref_artifacts_path), exist_ok=True) | |
| with open(self.ref_artifacts_path, 'wb') as f: | |
| pickle.dump(art, f) | |
| self._log(f" saved artifacts: {self.ref_artifacts_path}") | |
| self.ref_logits = torch.from_numpy(art['ref_logits']).float().to(self.device) | |
| self.ref_norm2 = precompute_ref_norm2(self.ref_logits) | |
| self._log(f"ref_logits shape: {tuple(self.ref_logits.shape)}") | |
| def _build_artifacts(self, raw_path): | |
| self._log(f"Building ref artifacts from {raw_path}") | |
| with open(raw_path, 'rb') as f: | |
| data = pickle.load(f) | |
| ref_embeddings = data['embeddings'] | |
| ref_labels = data['labels'] | |
| real_idx = [i for i, l in enumerate(ref_labels) if l == 0] | |
| ref_embeddings = [ref_embeddings[i] for i in real_idx] | |
| self._log(f" {len(ref_embeddings)} real ref samples (filtered from {len(ref_labels)})") | |
| logits_list = [] | |
| with torch.no_grad(): | |
| for emb in ref_embeddings: | |
| emb_tensor = torch.from_numpy(emb).float().unsqueeze(0).to(self.device) | |
| logits_list.append(self.model.compute_logits(emb_tensor).squeeze(0)) | |
| ref_logits = torch.stack(logits_list, dim=0) | |
| return { | |
| 'ref_logits': ref_logits.cpu().numpy(), | |
| 'sigma': float(self.sigma.item()), | |
| 'patch_size': self.patch_size, | |
| 'num_ref': int(ref_logits.shape[0]), | |
| 'variant': self.variant, | |
| } | |
| def predict(self, image_path: str, output_dir: str = None) -> dict: | |
| image_pil = Image.open(image_path).convert('RGB') | |
| image_vis = image_pil.resize((224, 224), Image.BILINEAR) | |
| image_np = np.array(image_vis) | |
| image_tensor = self.transform(image_pil).unsqueeze(0).to(self.device) | |
| with torch.no_grad(): | |
| patch_tokens = get_patch_tokens(self.backbone, image_tensor) | |
| patch_embeddings = pool_tokens_to_patch_size( | |
| patch_tokens, self.patch_size, image_size=224 | |
| ) | |
| patch_embeddings = patch_embeddings.detach().requires_grad_(True) | |
| patch_logits = self.model.compute_logits(patch_embeddings) | |
| self.model.zero_grad() | |
| patch_logits.mean().backward() | |
| grads = patch_embeddings.grad[0] | |
| patch_logits_np = patch_logits[0].detach().cpu().numpy() | |
| grad_magnitude = grads.norm(dim=1).detach().cpu().numpy() | |
| mil_cam_raw = np.abs(patch_logits_np) * grad_magnitude | |
| mil_cam_raw = np.maximum(mil_cam_raw, 0) | |
| s = mil_cam_raw.mean() + 4 * mil_cam_raw.std() | |
| mil_cam = np.clip(mil_cam_raw / (s + 1e-6), 0, 1) | |
| grid_size = 224 // self.patch_size | |
| mil_heatmap = create_heatmap_from_cam(mil_cam, grid_size, (224, 224)) | |
| test_logits = patch_logits.detach() | |
| score = score_logit_xy_batch( | |
| self.ref_logits, self.ref_norm2, test_logits, self.sigma | |
| ).item() | |
| label = "fake" if score > self.threshold else "real" | |
| result = { | |
| "image_path": os.path.abspath(image_path), | |
| "variant": self.variant, | |
| "label": label, | |
| "score": float(score), | |
| "threshold": float(self.threshold), | |
| "patch_scores": mil_cam.reshape(grid_size, grid_size).tolist(), | |
| } | |
| if output_dir is not None: | |
| os.makedirs(output_dir, exist_ok=True) | |
| paths = { | |
| "original": os.path.join(output_dir, "01_original.png"), | |
| "mil_heatmap": os.path.join(output_dir, "04_mil_heatmap.png"), | |
| "mil_overlay_grid": os.path.join(output_dir, "05a_mil_overlay_grid.png"), | |
| "patch_scores_txt": os.path.join(output_dir, "09_mil_patch_scores.txt"), | |
| "result_json": os.path.join(output_dir, "result.json"), | |
| } | |
| save_original(image_np, paths["original"]) | |
| save_heatmap(mil_heatmap, paths["mil_heatmap"]) | |
| save_overlay_with_grid(image_np, mil_heatmap, grid_size, | |
| paths["mil_overlay_grid"], heatmap_weight=0.6) | |
| save_patch_scores_txt(mil_cam, grid_size, paths["patch_scores_txt"]) | |
| with open(paths["result_json"], 'w') as f: | |
| json.dump(result, f, indent=2) | |
| result["outputs"] = paths | |
| return result | |
| # ============================================================================== | |
| # CLI | |
| # ============================================================================== | |
| def main(): | |
| variant_help = "Model variant: " + ", ".join( | |
| f"'{k}' ({v['description']}, thres={v['threshold']})" | |
| for k, v in VARIANTS.items() | |
| ) | |
| parser = argparse.ArgumentParser(description="MDMF single-image inference") | |
| parser.add_argument("--variant", choices=list(VARIANTS.keys()), | |
| default=DEFAULT_VARIANT, help=variant_help) | |
| parser.add_argument("--image", required=True, help="Path to input image") | |
| parser.add_argument("--output_dir", required=True, help="Output directory for heatmap + json") | |
| parser.add_argument("--checkpoint", default=None, | |
| help="Override checkpoint path (otherwise uses variant default)") | |
| parser.add_argument("--ref_artifacts", default=None, | |
| help="Override ref_artifacts path (otherwise uses variant default)") | |
| parser.add_argument("--ref_embeddings", default=None, | |
| help="Raw ref embeddings β only needed when artifacts need to be built") | |
| parser.add_argument("--threshold", type=float, default=None, | |
| help="Override decision threshold (default: variant-specific)") | |
| parser.add_argument("--device", default=None) | |
| args = parser.parse_args() | |
| engine = MDMFInference( | |
| variant=args.variant, | |
| checkpoint_path=args.checkpoint, | |
| ref_artifacts_path=args.ref_artifacts, | |
| ref_embeddings_path=args.ref_embeddings, | |
| threshold=args.threshold, | |
| device=args.device, | |
| ) | |
| result = engine.predict(args.image, output_dir=args.output_dir) | |
| print(json.dumps({k: v for k, v in result.items() if k != "patch_scores"}, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |