Spaces:
Sleeping
Sleeping
Update mdmf_inference.py
Browse files38 unmodified lines3940414243444546474849505152535455565713 unmodified lines717273747576777879808126 unmodified lines10810911011111211311411511644 unmodified lines1611621631641651661671681691 unmodified line1711721731741751761773 unmodified lines18118218318418518618718818998 unmodified lines2882892902912922937 unmodified lines30130230330430530630730830931031132 unmodified lines34434534634734834935035135235335435535610 unmodified lines36736836937037137237337430 unmodified lines40540640740840941041117 unmodified lines42943043143243343443510 unmodified lines44644744844945045140 unmodified lines4924934944954964974 unmodified lines50250350450550650750850951051138 unmodified linesPACKAGE_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": {13 unmodified lines}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__()26 unmodified lines# ==============================================================================# DINOv2 helpers# ==============================================================================def get_patch_tokens(backbone, x):if hasattr(backbone, "forward_features"):out = backbone.forward_features(x)44 unmodified lines# ==============================================================================# Scoring β -logit(xy) scorer from mil_detector/ImageNet/test_mil_mmd_v3.py.# ==============================================================================@torch.no_grad()def precompute_ref_norm2(ref_X):return (ref_X ** 2).sum(dim=1, keepdim=True)1 unmodified line@torch.no_grad()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 + epsilonY_norm2 = (Y ** 2).sum(dim=1, keepdim=True)dist = ref_norm2 + Y_norm2.t() - 2.0 * (ref_X @ Y.t())3 unmodified lines# ==============================================================================# 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()98 unmodified linesthreshold: float = None,device: str = None,verbose: bool = True,):if variant not in VARIANTS:raise ValueError(7 unmodified linesself.threshold = cfg["threshold"] if threshold is None else float(threshold)self.verbose = verboseif 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()32 unmodified linesself.backbone.eval()def _load_reference(self):"""Prefers artifacts (tiny precomputed pkl) over raw embeddings.Fallback paths:1. artifacts exist AND sigma matches β load artifacts2. raw embeddings exist β rebuild artifacts, save, load3. neither β error"""art = Noneif os.path.exists(self.ref_artifacts_path):self._log(f"Loading ref artifacts: {self.ref_artifacts_path}")10 unmodified linesif 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)30 unmodified lines'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)17 unmodified linesmil_cam_raw = np.abs(patch_logits_np) * grad_magnitudemil_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_sizemil_heatmap = create_heatmap_from_cam(mil_cam, grid_size, (224, 224))10 unmodified lines"label": label,"score": float(score),"threshold": float(self.threshold),"patch_scores": mil_cam.reshape(grid_size, grid_size).tolist(),}40 unmodified lineshelp="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()4 unmodified linesref_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()38 unmodified lines3940414243444513 unmodified lines596061626364656667686970717273747526 unmodified lines10210310410510610710810944 unmodified lines1541551561571581591601611 unmodified line1631641651661671683 unmodified lines17217317417517617717817998 unmodified lines2782792802812822832847 unmodified lines29229329429529629729829930030130230330430530632 unmodified lines33934034134234334410 unmodified lines35535635735835936036130 unmodified lines39239339439539639739839940040140240340440540640740817 unmodified lines42642742842943043143243310 unmodified lines44444544644744844945040 unmodified lines4914924934944954964974984995004 unmodified lines50550650750850951051151251351451538 unmodified linesPACKAGE_DIR = Path(__file__).resolve().parent# ==============================================================================# Variant registry. (unchanged)# ==============================================================================VARIANTS = {"imagenet": {13 unmodified lines}DEFAULT_VARIANT = "imagenet"# NEW: default heatmap normalization constant. The raw mil_cam values are# clamped to mean + DEFAULT_HEATMAP_CLAMP_STD * std before normalizing into# [0, 1]. Lower values β more diffuse / more activation visible. Higher values# β only the absolute hottest patches show. The paper's reference visualizations# (Figures 5β9) are roughly equivalent to clamp=4.DEFAULT_HEATMAP_CLAMP_STD = 4.0# ==============================================================================# Model β copied from MDMF/src/test_MDMF.py (MMD_MIL_Detector). Unchanged.# ==============================================================================class MMD_MIL_Detector(nn.Module):def __init__(self, embed_dim=1024, hidden_dim=256, dropout=0.3, init_sigma=1.0):super().__init__()26 unmodified lines# ==============================================================================# DINOv2 helpers β unchanged# ==============================================================================def get_patch_tokens(backbone, x):if hasattr(backbone, "forward_features"):out = backbone.forward_features(x)44 unmodified lines# ==============================================================================# Scoring β unchanged# ==============================================================================@torch.no_grad()def precompute_ref_norm2(ref_X):return (ref_X ** 2).sum(dim=1, keepdim=True)1 unmodified line@torch.no_grad()def score_logit_xy_batch(ref_X, ref_norm2, Y, sigma, epsilon=1e-8):sigma = sigma + epsilonY_norm2 = (Y ** 2).sum(dim=1, keepdim=True)dist = ref_norm2 + Y_norm2.t() - 2.0 * (ref_X @ Y.t())3 unmodified lines# ==============================================================================# Visualization helpers β unchanged# ==============================================================================def create_heatmap_from_cam(cam, grid_size, target_size=(224, 224)):if cam.size == 1:return np.ones(target_size) * cam.item()98 unmodified linesthreshold: float = None,device: str = None,verbose: bool = True,heatmap_clamp_std: float = DEFAULT_HEATMAP_CLAMP_STD, # NEW):if variant not in VARIANTS:raise ValueError(7 unmodified linesself.threshold = cfg["threshold"] if threshold is None else float(threshold)self.verbose = verbose# NEW: store the default heatmap clamp; predict() can override per-call.self.heatmap_clamp_std = float(heatmap_clamp_std)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._log(f"heatmap_clamp_std={self.heatmap_clamp_std}")self._load_model()self._load_backbone()self._load_reference()32 unmodified linesself.backbone.eval()def _load_reference(self):art = Noneif os.path.exists(self.ref_artifacts_path):self._log(f"Loading ref artifacts: {self.ref_artifacts_path}")10 unmodified linesif 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.")art = self._build_artifacts(self.ref_embeddings_path)os.makedirs(os.path.dirname(self.ref_artifacts_path), exist_ok=True)30 unmodified lines'variant': self.variant,}def predict(self,image_path: str,output_dir: str = None,heatmap_clamp_std: float = None, # NEW: per-call override) -> dict:# Resolve clamp value: per-call override > engine default.clamp_std = (self.heatmap_clamp_stdif heatmap_clamp_std is Noneelse float(heatmap_clamp_std))image_pil = Image.open(image_path).convert('RGB')image_vis = image_pil.resize((224, 224), Image.BILINEAR)image_np = np.array(image_vis)17 unmodified linesmil_cam_raw = np.abs(patch_logits_np) * grad_magnitudemil_cam_raw = np.maximum(mil_cam_raw, 0)# NEW: clamp_std is now configurable rather than hardcoded to 4.s = mil_cam_raw.mean() + clamp_std * mil_cam_raw.std()mil_cam = np.clip(mil_cam_raw / (s + 1e-6), 0, 1)grid_size = 224 // self.patch_sizemil_heatmap = create_heatmap_from_cam(mil_cam, grid_size, (224, 224))10 unmodified lines"label": label,"score": float(score),"threshold": float(self.threshold),"heatmap_clamp_std": float(clamp_std), # NEW: surfaced for debugging"patch_scores": mil_cam.reshape(grid_size, grid_size).tolist(),}40 unmodified lineshelp="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)")# NEW: expose heatmap clamp on the CLI too.parser.add_argument("--heatmap_clamp_std", type=float, default=DEFAULT_HEATMAP_CLAMP_STD,help=f"Heatmap normalization (mean + N*std). Lower β more diffuse, "f"higher β only hottest patches show. Default {DEFAULT_HEATMAP_CLAMP_STD}.")parser.add_argument("--device", default=None)args = parser.parse_args()4 unmodified linesref_embeddings_path=args.ref_embeddings,threshold=args.threshold,device=args.device,heatmap_clamp_std=args.heatmap_clamp_std,)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()
mdmf_inference.py+38-34