From 83ad9467fb9855b64abcd300adeda3f2bf999eaa Mon Sep 17 00:00:00 2001 From: yxteo2 Date: Sun, 13 Sep 2026 15:21:29 +0800 Subject: [PATCH 1/2] Unify inference preprocessing and fix center-crop mask alignment across detectors --- README.md | 5 + anomaly_detection/pipeline.py | 29 +----- anomaly_detection/predict.py | 60 ++++++++---- anomaly_detection/preprocessing.py | 92 ++++++++++++++++++ docs/detector_choices.md | 6 +- docs/inference.md | 93 ++++++++++++++++++ inference.py | 54 ++--------- ssn_inference.py | 57 ++--------- tests/test_inference_preprocessing.py | 133 ++++++++++++++++++++++++++ 9 files changed, 386 insertions(+), 143 deletions(-) create mode 100644 anomaly_detection/preprocessing.py create mode 100644 docs/inference.md create mode 100644 tests/test_inference_preprocessing.py diff --git a/README.md b/README.md index 1b0cdf0..8a38671 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ losses, fitting behavior, runnable examples and differences from the papers. | `anomaly_detection/pipeline.py` | Shared experiment lifecycle | | `anomaly_detection/smoke.py` | Synthetic training/reload and CUDA peak-memory checks | | `anomaly_detection/predict.py` | Shared checkpoint reload and single-image prediction | +| `anomaly_detection/preprocessing.py` | Shared resize, center crop, normalization and mask geometry | | `anomaly_detection/training/accumulation.py` | Sample-weighted gradient accumulation | | `configs/` | Ready-to-edit YAML experiments for all five detectors | | `docs/yaml_training.md` | YAML options, supported combinations and extension guide | @@ -120,6 +121,10 @@ Existing run folders require a new `--run_name` or explicit `--overwrite`. ## Inference +For all five YAML-built detectors, use the shared command in the +[inference and preprocessing guide](docs/inference.md). It reads the saved +training crop settings and optionally returns source-size maps with valid-region masks. + New checkpoints automatically provide their model configuration. Inference also automatically loads `calibration.json` from the checkpoint directory: diff --git a/anomaly_detection/pipeline.py b/anomaly_detection/pipeline.py index 1b1296a..16380f4 100644 --- a/anomaly_detection/pipeline.py +++ b/anomaly_detection/pipeline.py @@ -9,7 +9,7 @@ import numpy as np import torch import yaml -from torchvision.transforms import v2 as T +from anomaly_detection.preprocessing import make_det_tf, make_train_tf from anomaly_detection.builder import build_model, build_trainer from anomaly_detection.config import as_yaml_config, resolve_config @@ -20,33 +20,6 @@ ) -# ----------------------------- -# Transforms (torchvision v2) -# ----------------------------- -def make_train_tf(pre_h: int, pre_w: int, h: int, w: int): - return T.Compose([ - T.ToImage(), - T.Resize((pre_h, pre_w), antialias=True), - T.CenterCrop((h, w)), - T.RandomHorizontalFlip(p=0.5), - T.RandomVerticalFlip(p=0.5), - T.ToDtype(torch.float32, scale=True), - T.Normalize(mean=[0.485, 0.456, 0.406], - std=[0.229, 0.224, 0.225]), - ]) - - -def make_det_tf(pre_h: int, pre_w: int, h: int, w: int): - return T.Compose([ - T.ToImage(), - T.Resize((pre_h, pre_w), antialias=True), - T.CenterCrop((h, w)), - T.ToDtype(torch.float32, scale=True), - T.Normalize(mean=[0.485, 0.456, 0.406], - std=[0.229, 0.224, 0.225]), - ]) - - # ----------------------------- # Pipeline # ----------------------------- diff --git a/anomaly_detection/predict.py b/anomaly_detection/predict.py index 09317d0..0de11d0 100644 --- a/anomaly_detection/predict.py +++ b/anomaly_detection/predict.py @@ -1,40 +1,59 @@ """Reload any YAML-built detector and predict one image using saved transforms.""" import argparse -import math from pathlib import Path -from PIL import Image import torch from anomaly_detection.builder import build_model -from anomaly_detection.pipeline import make_det_tf +from anomaly_detection.preprocessing import InferencePreprocessing def load_model(checkpoint_path, device="cpu"): + if device == "cuda" and not torch.cuda.is_available(): + raise RuntimeError("CUDA was requested, but is unavailable.") saved = torch.load(checkpoint_path, map_location="cpu", weights_only=True) + if not isinstance(saved, dict) or not saved.get("experiment_cfg") or "model_state_dict" not in saved: + raise ValueError("Shared inference requires a full YAML-training checkpoint with experiment_cfg and model_state_dict. " + "For legacy FastFlow/SSN checkpoints, use the model-specific inference script with explicit settings.") cfg = {**saved["experiment_cfg"], "pretrained_backbone": False} model = build_model(cfg) model.load_state_dict(saved["model_state_dict"], strict=True) return model.to(device).eval(), cfg -@torch.no_grad() -def predict_image(checkpoint_path, image_path, device="cpu"): - model, cfg = load_model(checkpoint_path, device) - h, w = cfg["image_size"] - transform = make_det_tf(math.ceil(h / cfg["crop_scale"]), math.ceil(w / cfg["crop_scale"]), h, w) - with Image.open(image_path) as source: - tensor = transform(source.convert("RGB")).unsqueeze(0).to(device) - result = model(tensor) - if cfg["model"] == "fastflow": - # Match FastFlowEvaluator's default top-one-percent aggregation. - maps = result - flat = maps.flatten(1) - scores = flat.topk(max(1, int(0.01 * flat.shape[1])), dim=1).values.mean(1) - else: - maps, scores = result - return {"anomaly_map": maps.cpu(), "score": scores.cpu()} +class AnomalyInferenceEngine(InferencePreprocessing): + """Load once and reuse across images, for all five YAML-built detectors.""" + def __init__(self, checkpoint_path, device="cpu"): + self.model, self.cfg = load_model(checkpoint_path, device) + self.device = torch.device(device) + self.setup_preprocessing(self.cfg["image_size"], self.cfg["crop_scale"]) + + @torch.inference_mode() + def predict(self, image_path, restore_original=False): + tensor, original = self.preprocess(image_path) + result = self.model(tensor.to(self.device)) + if self.cfg["model"] == "fastflow": + # Match FastFlowEvaluator's default top-one-percent aggregation. + maps = result + flat = maps.flatten(1) + scores = flat.topk(max(1, int(0.01 * flat.shape[1])), dim=1).values.mean(1) + else: + maps, scores = result + if tuple(maps.shape) != (1, 1, self.h, self.w) or scores.numel() != 1: + raise RuntimeError("Unexpected detector output dimensions.") + if not torch.isfinite(maps).all() or not torch.isfinite(scores).all(): + raise RuntimeError("Detector produced non-finite predictions.") + prediction = {"anomaly_map": maps.cpu(), "score": scores.cpu(), + "geometry": self.geometry(original.shape[:2])} + if restore_original: + restored, valid = self.restore_map(maps[0, 0], original.shape[:2]) + prediction.update(original_anomaly_map=restored, valid_region=valid) + return prediction + + +def predict_image(checkpoint_path, image_path, device="cpu", restore_original=False): + return AnomalyInferenceEngine(checkpoint_path, device).predict(image_path, restore_original) def main(): @@ -43,11 +62,12 @@ def main(): parser.add_argument("--image", required=True) parser.add_argument("--output", required=True, help="Output .pt file containing map and raw anomaly score.") parser.add_argument("--device", choices=("cpu", "cuda"), default="cpu") + parser.add_argument("--restore-original", action="store_true", help="Also save source-size display map and valid region; cropped-away borders are NaN.") args = parser.parse_args() output = Path(args.output) if output.exists(): raise FileExistsError(output) - prediction = predict_image(args.checkpoint, args.image, args.device) + prediction = predict_image(args.checkpoint, args.image, args.device, args.restore_original) output.parent.mkdir(parents=True, exist_ok=True) torch.save(prediction, output) print(f"Raw anomaly score: {prediction['score'].item():.6f}; saved {output}") diff --git a/anomaly_detection/preprocessing.py b/anomaly_detection/preprocessing.py new file mode 100644 index 0000000..0898f8e --- /dev/null +++ b/anomaly_detection/preprocessing.py @@ -0,0 +1,92 @@ +"""Shared train/evaluation transforms and inference crop geometry. + +Images are RGB, resized with antialiased bilinear interpolation, center-cropped, +scaled to [0, 1], then ImageNet-normalized. Masks use torchvision's mask kernel. +DINO patch padding belongs to the model, never this preprocessing stage. +""" + +import math + +import numpy as np +from PIL import Image +import torch +from torchvision import tv_tensors +from torchvision.transforms import v2 as T +from torchvision.transforms.v2 import functional as TF + + +def make_det_tf(pre_h, pre_w, h, w): + return _transform(pre_h, pre_w, h, w, augment=False) + + +def make_train_tf(pre_h, pre_w, h, w): + return _transform(pre_h, pre_w, h, w, augment=True) + + +def _transform(pre_h, pre_w, h, w, augment): + operations = [T.ToImage(), T.Resize((pre_h, pre_w), antialias=True), T.CenterCrop((h, w))] + if augment: + operations.extend([T.RandomHorizontalFlip(p=0.5), T.RandomVerticalFlip(p=0.5)]) + return T.Compose(operations + [T.ToDtype(torch.float32, scale=True), + T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) + + +class InferencePreprocessing: + """Reusable geometry mixin for the shared and legacy inference engines.""" + + def setup_preprocessing(self, image_size, crop_scale): + if len(image_size) != 2 or any(type(v) is not int or v <= 0 for v in image_size): + raise ValueError("image_size must contain two positive integers.") + if not math.isfinite(crop_scale) or not 0 < crop_scale <= 1: + raise ValueError("crop_scale must be in (0, 1].") + self.image_size = tuple(image_size) + self.crop_scale = float(crop_scale) + self.h, self.w = self.image_size + self.pre_h, self.pre_w = (math.ceil(v / crop_scale) for v in self.image_size) + # Match torchvision CenterCrop exactly, including round-to-even ties. + self.crop_top = int(round((self.pre_h - self.h) / 2.0)) + self.crop_left = int(round((self.pre_w - self.w) / 2.0)) + self.transform = make_det_tf(self.pre_h, self.pre_w, self.h, self.w) + + def preprocess(self, image_path): + with Image.open(image_path) as source: + rgb = source.convert("RGB") + original = np.array(rgb) + tensor = self.transform(rgb).unsqueeze(0) + return tensor, original + + def gt_mask_to_crop(self, gt_mask_orig, orig_rgb): + """Use the same mask resize/crop kernels as MVTecDataset evaluation.""" + if tuple(gt_mask_orig.shape) != tuple(orig_rgb.shape[:2]): + raise ValueError("Ground-truth mask must match the original image dimensions.") + mask = tv_tensors.Mask(torch.from_numpy((gt_mask_orig > 0).astype(np.uint8))) + mask = T.Resize((self.pre_h, self.pre_w), antialias=True)(mask) + mask = T.CenterCrop(self.image_size)(mask) + return mask.as_subclass(torch.Tensor).numpy().astype(np.uint8) * 255 + + def uncrop_mask_to_original(self, orig_rgb, mask_hw): + """Restore a binary crop mask for display; excluded borders stay zero.""" + if tuple(mask_hw.shape) != self.image_size: + raise ValueError("Mask dimensions must match the configured crop.") + canvas = torch.zeros((self.pre_h, self.pre_w), dtype=torch.uint8) + canvas[self.crop_top:self.crop_top + self.h, self.crop_left:self.crop_left + self.w] = torch.as_tensor(mask_hw) + restored = TF.resize(tv_tensors.Mask(canvas), list(orig_rgb.shape[:2])) + return restored.as_subclass(torch.Tensor).numpy() + + def restore_map(self, anomaly_map, original_size): + """Nearest-neighbor display projection; NaN marks unobserved borders. + + This is not an inverse of resizing. Compute metrics in crop space. + Nearest projection avoids blending predictions with unknown borders. + """ + if tuple(anomaly_map.shape) != self.image_size: + raise ValueError("Anomaly map dimensions must match the configured crop.") + canvas = torch.full((1, 1, self.pre_h, self.pre_w), float("nan")) + canvas[..., self.crop_top:self.crop_top + self.h, self.crop_left:self.crop_left + self.w] = anomaly_map.detach().cpu() + restored = torch.nn.functional.interpolate(canvas, size=tuple(original_size), mode="nearest")[0, 0] + return restored, torch.isfinite(restored) + + def geometry(self, original_size): + return {"original_size": list(original_size), "resize_size": [self.pre_h, self.pre_w], + "crop_size": list(self.image_size), "crop_top": self.crop_top, + "crop_left": self.crop_left, "crop_scale": self.crop_scale} diff --git a/docs/detector_choices.md b/docs/detector_choices.md index 1f23717..6d7af44 100644 --- a/docs/detector_choices.md +++ b/docs/detector_choices.md @@ -47,8 +47,10 @@ python -m anomaly_detection.predict --checkpoint path/to/best_model.pth \ --image path/to/image.png --output prediction.pt --device cuda ``` -The output contains the raw anomaly score and map at the configured input size. -It does not apply calibration or restore the source image's original size. +The output contains the raw anomaly score, crop-space map and preprocessing +geometry. Add `--restore-original` for a source-size display map and valid-region +mask; cropped-away borders are marked NaN. It does not apply calibration. +See the [inference guide](inference.md) for preprocessing parity and mask alignment. ## Implementation scope and memory diff --git a/docs/inference.md b/docs/inference.md new file mode 100644 index 0000000..a4d67ab --- /dev/null +++ b/docs/inference.md @@ -0,0 +1,93 @@ +# Inference and preprocessing parity + +Use the shared command for **FastFlow, SSN, PaDiM, PatchCore and the Dinomaly-style +variant**, with either supported DINOv2 backbone or a compatible ResNet: + +```bash +python -m anomaly_detection.predict --checkpoint path/to/best_model.pth \ + --image path/to/image.png --output prediction.pt --device cuda --restore-original +``` + +The checkpoint must be a full YAML-training checkpoint, not a bare state dict. +The detector, backbone, selected layers, input dimensions and `crop_scale` come +from its saved configuration. Backbone weights load from the checkpoint without +another pretrained download. An unavailable requested CUDA device raises an +error instead of silently switching to CPU. The output file is never overwritten. + +For repeated images, load the model once: + +```python +from anomaly_detection.predict import AnomalyInferenceEngine + +engine = AnomalyInferenceEngine("path/to/best_model.pth", device="cuda") +prediction = engine.predict("path/to/image.png", restore_original=True) +``` + +## Exact preprocessing sequence + +Training's deterministic validation/test transform and every inference entry +point share `anomaly_detection/preprocessing.py`: + +1. Convert the source image to RGB. +2. Resize to `(ceil(height / crop_scale), ceil(width / crop_scale))` using + torchvision's antialiased bilinear tensor resize. This is a fixed rectangular + resize, not letterboxing or aspect-ratio-preserving resizing. +3. Center crop to the checkpoint's `(height, width)`. Offsets use torchvision's + `round((resize_dimension - crop_dimension) / 2)`, including round-to-even ties. +4. Convert uint8 values to FP32 `[0, 1]` and normalize with ImageNet mean + `[0.485, 0.456, 0.406]` and standard deviation `[0.229, 0.224, 0.225]`. +5. The detector handles DINO patch padding internally and crops its output back + to the configured input dimensions. Do not pad or crop a second time outside + the model. ResNet models do not receive this DINO padding. + +Training alone additionally applies its existing random horizontal/vertical +flips. These are intentionally absent during evaluation/inference. + +`crop_scale: 1.0` preserves the entire resized field of view. Smaller values +discard borders. Do not change cropping only at inference: retrain/refit and +recalibrate if you change the preprocessing used in an experiment. + +## Outputs and coordinates + +| Output key | Meaning | +| --- | --- | +| `anomaly_map` | Raw `[1, 1, height, width]` anomaly map in crop coordinates | +| `score` | Raw image score; higher means more anomalous | +| `geometry` | Source dimensions, resize dimensions, crop dimensions, offsets and scale | +| `original_anomaly_map` | Optional source-size display map; NaN outside inspected crop | +| `valid_region` | Optional source-size boolean mask marking inspected pixels | + +Source-size restoration inserts the crop into its resized canvas and uses +nearest-neighbor projection back to the source size. It is a display mapping, +not an exact inverse of resizing, and cannot recover discarded borders. Use the +valid mask when visualizing or thresholding. Do not interpret excluded regions +as normal or compute pixel metrics over those regions. + +FastFlow image scores use the same top-1%-pixel mean as the training evaluator. +Other detectors use their model-provided score. Maps are not arbitrarily clamped +or min-max normalized: PaDiM/PatchCore distances are not probabilities, and +SSN's image score is not replaced by a map maximum. Apply the matching run's +`calibration.json` thresholds to raw scores/maps when classification is needed; +the shared command itself does not make binary decisions. + +## Ground-truth masks and legacy scripts + +`engine.gt_mask_to_crop(mask, original_rgb)` uses the same torchvision Mask +resize and center-crop operations as dataset evaluation. Input masks must match +the source image dimensions; mismatches fail explicitly. Masks use nearest +interpolation, not bilinear smoothing. + +The existing `inference.py` and `ssn_inference.py` remain FastFlow- and SSN-specific. +They now share the same preprocessing and corrected crop offsets, including +ground-truth alignment and contour restoration. For legacy checkpoints without +saved preprocessing, supply the original training size and crop scale explicitly: +use `--image_size HEIGHT WIDTH --crop_scale SCALE` (the legacy scale fallback +is 0.875, while saved metadata always takes precedence). +Missing metadata cannot be inferred safely. Use the shared command above for the +three new detector types. + +Tests compare preprocessing pixels and masks against the dataset transform, +exercise odd crop margins, and verify checkpoint-based predictions for all five +DINO-backed detectors with and without center cropping. Additional geometry +checks cover 416, 512, 704 and rectangular sizes. These are CPU checks, not GPU +performance or anomaly-accuracy benchmarks. diff --git a/inference.py b/inference.py index c86e6a2..30307d6 100644 --- a/inference.py +++ b/inference.py @@ -7,7 +7,6 @@ import argparse import json -import math from dataclasses import dataclass from pathlib import Path from typing import List, Optional, Tuple @@ -15,7 +14,7 @@ import cv2 import numpy as np import torch -from PIL import Image +from anomaly_detection.preprocessing import InferencePreprocessing from anomaly_detection.modeling import FastFlowModel @@ -361,7 +360,7 @@ class Sample: gt_mask_orig: Optional[np.ndarray] -class FastFlowInferenceEngine: +class FastFlowInferenceEngine(InferencePreprocessing): def __init__( self, checkpoint_path: str, @@ -379,8 +378,10 @@ def __init__( feature_channels: Optional[int] = None, backbone_precision: Optional[str] = None, ): - self.device = torch.device(device if (device == "cuda" and torch.cuda.is_available()) else "cpu") - ckpt = torch.load(checkpoint_path, map_location="cpu") + if device == "cuda" and not torch.cuda.is_available(): + raise RuntimeError("CUDA was requested, but is unavailable.") + self.device = torch.device(device) + ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=True) model_cfg = ckpt.get("model_cfg", {}) if isinstance(ckpt, dict) else {} backbone = model_cfg.get("backbone_name", backbone) flow_steps = int(model_cfg.get("flow_steps", flow_steps)) @@ -418,30 +419,7 @@ def __init__( self.model.to(self.device) self.model.eval() - from torchvision.transforms import v2 as T - - h, w = self.image_size - pre_h = int(math.ceil(h / crop_scale)) - pre_w = int(math.ceil(w / crop_scale)) - - self.h, self.w = h, w - self.pre_h, self.pre_w = pre_h, pre_w - self.crop_top = (pre_h - h) // 2 - self.crop_left = (pre_w - w) // 2 - - self.transform = T.Compose([ - T.ToImage(), - T.Resize((pre_h, pre_w), antialias=True), - T.CenterCrop((h, w)), - T.ToDtype(torch.float32, scale=True), - T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), - ]) - - def preprocess(self, image_path: str) -> Tuple[torch.Tensor, np.ndarray]: - pil = Image.open(image_path).convert("RGB") - orig_rgb = np.array(pil) - x = self.transform(pil).unsqueeze(0) - return x, orig_rgb + self.setup_preprocessing(self.image_size, crop_scale) @torch.inference_mode() def get_anomaly_map(self, x: torch.Tensor) -> torch.Tensor: @@ -465,22 +443,6 @@ def infer_one(self, image_path: str) -> Tuple[float, np.ndarray, np.ndarray]: amap_np = amap[0, 0].detach().cpu().numpy().astype(np.float32) return score_val, amap_np, orig_rgb - def gt_mask_to_crop(self, gt_mask_orig: np.ndarray, orig_rgb: np.ndarray) -> np.ndarray: - H0, W0 = orig_rgb.shape[:2] - m = gt_mask_orig - if m.shape[:2] != (H0, W0): - m = cv2.resize(m, (W0, H0), interpolation=cv2.INTER_NEAREST) - m = cv2.resize(m, (self.pre_w, self.pre_h), interpolation=cv2.INTER_NEAREST) - t, l = self.crop_top, self.crop_left - m = m[t : t + self.h, l : l + self.w] - return ((m > 0).astype(np.uint8) * 255) - - def uncrop_mask_to_original(self, orig_rgb: np.ndarray, mask_hw: np.ndarray) -> np.ndarray: - H0, W0 = orig_rgb.shape[:2] - canvas = np.zeros((self.pre_h, self.pre_w), dtype=np.uint8) - t, l = self.crop_top, self.crop_left - canvas[t : t + self.h, l : l + self.w] = mask_hw - return cv2.resize(canvas, (W0, H0), interpolation=cv2.INTER_NEAREST) def save_contour_overlay( self, @@ -749,6 +711,7 @@ def main(): parser.add_argument("--backbone", type=str, default="resnet18") parser.add_argument("--flow_steps", type=int, default=8) parser.add_argument("--image_size", type=int, nargs=2, default=[416, 416]) # H W + parser.add_argument("--crop_scale", type=float, default=0.875, help="Legacy checkpoint fallback; saved crop_scale takes precedence.") parser.add_argument("--hidden_ratio", type=float, default=1.0) parser.add_argument("--clamp", type=float, default=2.0) parser.add_argument("--conv3x3_only", action="store_true") @@ -783,6 +746,7 @@ def main(): backbone=args.backbone, flow_steps=args.flow_steps, image_size=tuple(args.image_size), + crop_scale=args.crop_scale, hidden_ratio=args.hidden_ratio, clamp=args.clamp, conv3x3_only=args.conv3x3_only, diff --git a/ssn_inference.py b/ssn_inference.py index 616b702..4f4c775 100644 --- a/ssn_inference.py +++ b/ssn_inference.py @@ -7,7 +7,6 @@ import argparse import json -import math from dataclasses import dataclass from pathlib import Path from typing import List, Optional, Tuple @@ -15,7 +14,7 @@ import cv2 import numpy as np import torch -from PIL import Image +from anomaly_detection.preprocessing import InferencePreprocessing from anomaly_detection.modeling import SuperSimpleNetModel from anomaly_detection.config import BACKBONES @@ -332,7 +331,7 @@ class Sample: gt_mask_orig: Optional[np.ndarray] -class SSNInferenceEngine: +class SSNInferenceEngine(InferencePreprocessing): def __init__( self, checkpoint_path: str, @@ -348,8 +347,10 @@ def __init__( feature_channels: Optional[int] = None, backbone_precision: Optional[str] = None, ): - self.device = torch.device(device if (device == "cuda" and torch.cuda.is_available()) else "cpu") - ckpt = torch.load(checkpoint_path, map_location="cpu") + if device == "cuda" and not torch.cuda.is_available(): + raise RuntimeError("CUDA was requested, but is unavailable.") + self.device = torch.device(device) + ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=True) model_cfg = ckpt.get("model_cfg", {}) if isinstance(ckpt, dict) else {} backbone = model_cfg.get("backbone_name", backbone) image_size = tuple(model_cfg.get("input_size", image_size)) @@ -383,31 +384,7 @@ def __init__( self.model.to(self.device) self.model.eval() - # EXACT transform: Resize -> CenterCrop -> Normalize (torchvision v2) - from torchvision.transforms import v2 as T - - h, w = self.image_size - pre_h = int(math.ceil(h / crop_scale)) - pre_w = int(math.ceil(w / crop_scale)) - - self.h, self.w = h, w - self.pre_h, self.pre_w = pre_h, pre_w - self.crop_top = (pre_h - h) // 2 - self.crop_left = (pre_w - w) // 2 - - self.transform = T.Compose([ - T.ToImage(), - T.Resize((pre_h, pre_w), antialias=True), - T.CenterCrop((h, w)), - T.ToDtype(torch.float32, scale=True), - T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), - ]) - - def preprocess(self, image_path: str) -> Tuple[torch.Tensor, np.ndarray]: - pil = Image.open(image_path).convert("RGB") - orig_rgb = np.array(pil) - x = self.transform(pil).unsqueeze(0) # [1,3,h,w] - return x, orig_rgb + self.setup_preprocessing(self.image_size, crop_scale) @torch.inference_mode() def infer_one(self, image_path: str) -> Tuple[float, np.ndarray, np.ndarray]: @@ -423,24 +400,6 @@ def infer_one(self, image_path: str) -> Tuple[float, np.ndarray, np.ndarray]: amap_np = pred_map[0, 0].detach().cpu().numpy().astype(np.float32) # [0,1] return score_val, amap_np, orig_rgb - def gt_mask_to_crop(self, gt_mask_orig: np.ndarray, orig_rgb: np.ndarray) -> np.ndarray: - """Convert original-size GT mask -> crop-space (h,w) mask aligned with anomaly map.""" - H0, W0 = orig_rgb.shape[:2] - m = gt_mask_orig - if m.shape[:2] != (H0, W0): - m = cv2.resize(m, (W0, H0), interpolation=cv2.INTER_NEAREST) - m = cv2.resize(m, (self.pre_w, self.pre_h), interpolation=cv2.INTER_NEAREST) - t, l = self.crop_top, self.crop_left - m = m[t : t + self.h, l : l + self.w] - return ((m > 0).astype(np.uint8) * 255) - - def uncrop_mask_to_original(self, orig_rgb: np.ndarray, mask_hw: np.ndarray) -> np.ndarray: - """Put crop-space mask back into pre-resize canvas, then resize to original image size.""" - H0, W0 = orig_rgb.shape[:2] - canvas = np.zeros((self.pre_h, self.pre_w), dtype=np.uint8) - t, l = self.crop_top, self.crop_left - canvas[t : t + self.h, l : l + self.w] = mask_hw - return cv2.resize(canvas, (W0, H0), interpolation=cv2.INTER_NEAREST) def save_contour_overlay( self, @@ -703,6 +662,7 @@ def main(): parser.add_argument("--pretrained_backbone", action=argparse.BooleanOptionalAction, default=True) parser.add_argument("--image_size", type=int, nargs=2, default=[416, 416]) # H W + parser.add_argument("--crop_scale", type=float, default=0.875, help="Legacy checkpoint fallback; saved crop_scale takes precedence.") parser.add_argument("--save_dir", type=str, default="./ssn_inference_results") parser.add_argument("--min_area", type=int, default=30) @@ -725,6 +685,7 @@ def main(): checkpoint_path=args.checkpoint_path, backbone=args.backbone, image_size=tuple(args.image_size), + crop_scale=args.crop_scale, perlin_threshold=args.perlin_threshold, adapt_cls_features=args.adapt_cls_features, layers=list(args.layers), diff --git a/tests/test_inference_preprocessing.py b/tests/test_inference_preprocessing.py new file mode 100644 index 0000000..982e828 --- /dev/null +++ b/tests/test_inference_preprocessing.py @@ -0,0 +1,133 @@ +"""Training/inference pixel parity, crop anchors and all-detector contracts.""" + +import math + +import numpy as np +from PIL import Image +import pytest +import torch +from torchvision import tv_tensors +from torchvision.transforms import v2 as T + +from anomaly_detection.builder import build_model, model_kwargs +from anomaly_detection.config import resolve_config +from anomaly_detection.pipeline import make_det_tf +from anomaly_detection.predict import AnomalyInferenceEngine, load_model +from anomaly_detection.preprocessing import InferencePreprocessing +from inference import FastFlowInferenceEngine +from ssn_inference import SSNInferenceEngine + + +@pytest.mark.parametrize("engine_class", [InferencePreprocessing, FastFlowInferenceEngine, SSNInferenceEngine]) +@pytest.mark.parametrize("size,scale", [((32, 48), 0.875), ((416, 512), 0.875), ((512, 704), 0.875), + ((416, 416), 1.0), ((512, 512), 1.0)]) +def test_pixel_and_mask_parity_with_dataset_transform(tmp_path, engine_class, size, scale): + engine = object.__new__(engine_class) + engine.setup_preprocessing(size, scale) + rgb = np.random.default_rng(7).integers(0, 256, (83, 117, 3), dtype=np.uint8) + mask = (rgb[..., 0] > 128).astype(np.uint8) + path = tmp_path / "image.png" + Image.fromarray(rgb).save(path) + h, w = size + transform = make_det_tf(math.ceil(h / scale), math.ceil(w / scale), h, w) + expected_image, expected_mask = transform(tv_tensors.Image(Image.fromarray(rgb)), + tv_tensors.Mask(torch.from_numpy(mask))) + actual, original = engine.preprocess(path) + torch.testing.assert_close(actual[0], expected_image, rtol=0, atol=0) + np.testing.assert_array_equal(original, rgb) + np.testing.assert_array_equal(engine.gt_mask_to_crop(mask, rgb), expected_mask.numpy() * 255) + + +def test_odd_crop_offsets_match_torchvision_and_restore_exact_canvas(): + engine = InferencePreprocessing() + engine.setup_preprocessing((32, 48), 0.875) + assert (engine.pre_h, engine.pre_w) == (37, 55) + assert (engine.crop_top, engine.crop_left) == (2, 4) # floor division incorrectly gave left=3 + coordinates = torch.arange(37 * 55).reshape(1, 37, 55) + torch.testing.assert_close(T.CenterCrop((32, 48))(coordinates), coordinates[:, 2:34, 4:52]) + rgb = np.zeros((37, 55, 3), dtype=np.uint8) + mask = np.ones((32, 48), dtype=np.uint8) * 255 + restored_mask = engine.uncrop_mask_to_original(rgb, mask) + expected = np.zeros((37, 55), dtype=np.uint8) + expected[2:34, 4:52] = 255 + np.testing.assert_array_equal(restored_mask, expected) + restored_map, valid = engine.restore_map(torch.ones(32, 48), (37, 55)) + np.testing.assert_array_equal(valid.numpy(), expected > 0) + assert torch.isnan(restored_map[~valid]).all() + assert (restored_map[valid] == 1).all() + + +@pytest.mark.parametrize("name", ["fastflow", "ssn", "padim", "patchcore", "dinomaly"]) +@pytest.mark.parametrize("scale", [0.875, 1.0]) +def test_every_detector_uses_checkpoint_crop_and_matches_direct_prediction(tmp_path, name, scale): + torch.set_num_threads(2) + cfg = resolve_config({"model": name, "backbone": "dinov2_vits14", "pretrained_backbone": False, + "data_path": "unused", "category": "bottle", "image_size": [32, 48], + "crop_scale": scale, "flow_steps": 1, "decoder_depth": 2, + "feature_channels": 16 if name in ("fastflow", "ssn") else None, + "adapt_cls_features": True, "padim_channels": 4, + "max_patches": 16, "memory_bank_size": 4}) + model = build_model(cfg).eval() + if name in ("padim", "patchcore"): + model.fit_features(iter((model.features(torch.randn(2, 3, 32, 48)),))) + path = tmp_path / "model.pth" + torch.save({"model_state_dict": model.state_dict(), "experiment_cfg": cfg, + "model_cfg": {**model_kwargs(cfg), "crop_scale": scale}}, path) + del model + image = np.random.default_rng(9).integers(0, 256, (79, 113, 3), dtype=np.uint8) + image_path = tmp_path / "image.png" + Image.fromarray(image).save(image_path) + engine = AnomalyInferenceEngine(path) + tensor = make_det_tf(math.ceil(32 / scale), math.ceil(48 / scale), 32, 48)(Image.fromarray(image)).unsqueeze(0) + observed = [] + hook = engine.model.register_forward_pre_hook(lambda module, args: observed.append(args[0].clone())) + prediction = engine.predict(image_path, restore_original=True) + hook.remove() + torch.testing.assert_close(observed[0], tensor, rtol=0, atol=0) + with torch.inference_mode(): + output = engine.model(tensor) + if name == "fastflow": + maps = output + flat = maps.flatten(1) + score = flat.topk(max(1, int(0.01 * flat.shape[1])), dim=1).values.mean(1) + else: + maps, score = output + torch.testing.assert_close(prediction["anomaly_map"], maps) + torch.testing.assert_close(prediction["score"], score) + assert prediction["geometry"]["crop_scale"] == scale + assert prediction["original_anomaly_map"].shape == (79, 113) + valid = prediction["valid_region"] + assert torch.isfinite(prediction["original_anomaly_map"][valid]).all() + assert bool(valid.all()) == (scale == 1.0) + assert prediction["anomaly_map"].shape == (1, 1, 32, 48) # DINO padding removed once by model + if name in ("fastflow", "ssn"): + # Deliberately wrong CLI/API fallback geometry must lose to saved metadata. + common = dict(checkpoint_path=str(path), backbone="resnet18", image_size=(64, 64), + crop_scale=0.5, pretrained_backbone=False, device="cpu") + if name == "fastflow": + legacy = FastFlowInferenceEngine(flow_steps=1, hidden_ratio=1, clamp=2, + conv3x3_only=False, topk_ratio=0.01, **common) + else: + legacy = SSNInferenceEngine(perlin_threshold=0.2, adapt_cls_features=False, + layers=["layer2", "layer3"], **common) + torch.testing.assert_close(legacy.preprocess(image_path)[0], tensor, rtol=0, atol=0) + legacy_score, legacy_map, _ = legacy.infer_one(image_path) + assert legacy_score == pytest.approx(score.item(), abs=1e-6) + np.testing.assert_allclose(legacy_map, maps[0, 0].numpy(), rtol=1e-5, atol=1e-6) + + +def test_bad_geometry_and_legacy_metadata_fail_clearly(tmp_path, monkeypatch): + engine = InferencePreprocessing() + for scale in (0, -1, 2, float("nan")): + with pytest.raises(ValueError, match="crop_scale"): + engine.setup_preprocessing((32, 48), scale) + engine.setup_preprocessing((32, 48), 0.875) + with pytest.raises(ValueError, match="Ground-truth"): + engine.gt_mask_to_crop(np.zeros((3, 4)), np.zeros((4, 5, 3))) + path = tmp_path / "legacy.pth" + torch.save({"weight": torch.ones(1)}, path) + with pytest.raises(ValueError, match="full YAML-training checkpoint"): + load_model(path) + monkeypatch.setattr(torch.cuda, "is_available", lambda: False) + with pytest.raises(RuntimeError, match="CUDA was requested"): + load_model(path, "cuda") From 9503b25ada125fdd53f5e9f1768ff4a7b037c7ba Mon Sep 17 00:00:00 2001 From: yxteo2 Date: Mon, 14 Sep 2026 12:27:53 +0800 Subject: [PATCH 2/2] Consolidate inference helpers and organize detector exports and maintenance docs --- README.md | 4 + anomaly_detection/builder.py | 24 +- anomaly_detection/inference_utils.py | 351 +++++++++++++++++++ anomaly_detection/modeling/__init__.py | 5 +- anomaly_detection/training/fastflow.py | 2 +- anomaly_detection/training/supersimplenet.py | 8 +- docs/repository_layout.md | 74 ++++ inference.py | 346 +----------------- ssn_inference.py | 316 +---------------- tests/test_inference_utils.py | 77 ++++ tests/test_yaml_training.py | 20 +- 11 files changed, 555 insertions(+), 672 deletions(-) create mode 100644 anomaly_detection/inference_utils.py create mode 100644 docs/repository_layout.md create mode 100644 tests/test_inference_utils.py diff --git a/README.md b/README.md index 8a38671..76e0bba 100644 --- a/README.md +++ b/README.md @@ -29,12 +29,16 @@ losses, fitting behavior, runnable examples and differences from the papers. | `anomaly_detection/smoke.py` | Synthetic training/reload and CUDA peak-memory checks | | `anomaly_detection/predict.py` | Shared checkpoint reload and single-image prediction | | `anomaly_detection/preprocessing.py` | Shared resize, center crop, normalization and mask geometry | +| `anomaly_detection/inference_utils.py` | Shared inference metrics, calibration and file helpers | | `anomaly_detection/training/accumulation.py` | Sample-weighted gradient accumulation | | `configs/` | Ready-to-edit YAML experiments for all five detectors | | `docs/yaml_training.md` | YAML options, supported combinations and extension guide | | `docs/gpu_memory.md` | DINOv2, larger inputs and GPU memory configuration | | `tests/` | Regression tests for evaluation and model behavior | +See the [repository maintenance guide](docs/repository_layout.md) for file roles, +compatibility entry points and generated-file conventions. + ## Installation Use Python 3.10 or newer. Install a PyTorch build compatible with your CUDA diff --git a/anomaly_detection/builder.py b/anomaly_detection/builder.py index e8ccd70..82f93c0 100644 --- a/anomaly_detection/builder.py +++ b/anomaly_detection/builder.py @@ -3,18 +3,25 @@ Factories are explicit allowlists: YAML never imports or executes arbitrary code. """ -from anomaly_detection.config import resolve_config -from anomaly_detection.modeling import FastFlowModel, SuperSimpleNetModel +from anomaly_detection.config import MODEL_PARAMS, resolve_config +from anomaly_detection.modeling import ( + DinomalyModel, FastFlowModel, PadimModel, PatchcoreModel, SuperSimpleNetModel, +) from anomaly_detection.training import FastFlowTrainer, SuperSimpleNetTrainer -from anomaly_detection.training.losses import FastFlowNLLLoss, SSNBCELoss, SSNLoss, SSNBCEDiceLoss, SSNFocalDiceLoss -from anomaly_detection.modeling.feature_heads import PadimModel, PatchcoreModel, DinomalyModel +from anomaly_detection.training.losses import ( + FastFlowNLLLoss, SSNBCEDiceLoss, SSNBCELoss, SSNFocalDiceLoss, SSNLoss, +) from anomaly_detection.training.feature_heads import FeatureHeadTrainer, ReconstructionLoss -MODEL_BUILDERS = {"fastflow": FastFlowModel, "ssn": SuperSimpleNetModel} -MODEL_BUILDERS.update(padim=PadimModel, patchcore=PatchcoreModel, dinomaly=DinomalyModel) -LOSS_BUILDERS = {"fastflow_nll": FastFlowNLLLoss, "ssn_focal": SSNLoss, "ssn_bce": SSNBCELoss} -LOSS_BUILDERS.update(ssn_bce_dice=SSNBCEDiceLoss, ssn_focal_dice=SSNFocalDiceLoss) +MODEL_BUILDERS = { + "fastflow": FastFlowModel, "ssn": SuperSimpleNetModel, + "padim": PadimModel, "patchcore": PatchcoreModel, "dinomaly": DinomalyModel, +} +LOSS_BUILDERS = { + "fastflow_nll": FastFlowNLLLoss, "ssn_focal": SSNLoss, "ssn_bce": SSNBCELoss, + "ssn_bce_dice": SSNBCEDiceLoss, "ssn_focal_dice": SSNFocalDiceLoss, +} def model_kwargs(cfg): @@ -34,7 +41,6 @@ def model_kwargs(cfg): kwargs.update({key: cfg[key] for key in ("perlin_threshold", "layers", "adapt_cls_features")}) kwargs["stop_grad"] = True else: - from anomaly_detection.config import MODEL_PARAMS kwargs.pop("feature_channels") kwargs.update({key: cfg[key] for key in MODEL_PARAMS[cfg["model"]]}) return kwargs diff --git a/anomaly_detection/inference_utils.py b/anomaly_detection/inference_utils.py new file mode 100644 index 0000000..34a8baf --- /dev/null +++ b/anomaly_detection/inference_utils.py @@ -0,0 +1,351 @@ +"""Shared metrics, calibration and MVTec file helpers for inference.""" + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import List, Optional, Tuple + +import cv2 +import numpy as np +import torch + + +# ============================================================ +# Self-implemented AUPRO (minimal, compute-only, no torchmetrics) +# ============================================================ +class SelfAUPRO: + """ + Minimal AUPRO implementation inspired by anomalib's AUPRO: + - connected components on GT mask + - compute PRO curve (FPR vs averaged per-region overlap) + - integrate area up to fpr_limit and normalize by fpr_limit + + Expected: + preds: (B,H,W) or (B,1,H,W) float in [0,1] (higher => more anomalous) + target: (B,H,W) or (B,1,H,W) binary {0,1} or {0,255} + """ + + def __init__(self, fpr_limit: float = 0.3): + self.fpr_limit = float(fpr_limit) + self._preds: List[torch.Tensor] = [] + self._target: List[torch.Tensor] = [] + + def update(self, preds: torch.Tensor, target: torch.Tensor) -> None: + if preds.dim() == 4 and preds.size(1) == 1: + preds = preds.squeeze(1) + if target.dim() == 4 and target.size(1) == 1: + target = target.squeeze(1) + + # store on CPU to reduce GPU memory + preds = preds.detach().float().cpu() + target = target.detach().float().cpu() + + # normalize target into {0,1} + if target.max() > 1.0: + target = (target > 0).float() + else: + target = (target > 0.5).float() + + # clamp preds + preds = preds.clamp(0.0, 1.0) + + self._preds.append(preds) + self._target.append(target) + + @staticmethod + def _cca_cv2(mask01: np.ndarray) -> np.ndarray: + """Connected components for one image. mask01 is {0,1} uint8.""" + mask01 = (mask01 > 0).astype(np.uint8) + # returns labels in [0..N] + _, labels = cv2.connectedComponents(mask01, connectivity=8) + return labels.astype(np.int32) + + @staticmethod + def _make_global_region_labels(cca_bhw: torch.Tensor) -> torch.Tensor: + """Offset connected component labels across batch to make them unique (except 0 background).""" + cca_off = cca_bhw.clone() + current_offset = 0 + B = int(cca_off.size(0)) + for b in range(B): + img = cca_off[b] + uniq = torch.unique(img) + uniq_fg = uniq[uniq != 0] + num_regions = int(uniq_fg.numel()) + if num_regions == 0: + continue + fg = img > 0 + img[fg] = img[fg] + current_offset + cca_off[b] = img + current_offset += num_regions + return cca_off + + def perform_cca(self) -> torch.Tensor: + """Return (B,H,W) integer labels; 0 is background; >0 are region IDs unique across batch.""" + target = torch.cat(self._target, dim=0) # (B,H,W) + if target.min() < 0 or target.max() > 1: + raise ValueError(f"AUPRO expects target in [0,1], got [{float(target.min())},{float(target.max())}]") + + # CPU CCA via OpenCV per image + target_np = target.numpy() + ccas = [] + for b in range(target_np.shape[0]): + labels = self._cca_cv2(target_np[b]) + ccas.append(labels) + cca = torch.from_numpy(np.stack(ccas, axis=0)) # (B,H,W) int32 + cca = self._make_global_region_labels(cca) + return cca.long() + + @staticmethod + def _auc_trapz(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + """Trapezoidal integration (assumes x sorted ascending).""" + if x.numel() < 2: + return torch.tensor(0.0, device=x.device, dtype=torch.float32) + dx = x[1:] - x[:-1] + avg = 0.5 * (y[1:] + y[:-1]) + return torch.sum(dx * avg) + + def compute_pro(self, cca: torch.Tensor, preds: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Compute PRO curve (FPR vs averaged per-region overlap). + cca: (B,H,W) int labels, 0 background + preds: (B,H,W) float, higher => more anomalous + """ + device = preds.device + + labels = cca.reshape(-1).long() + preds_flat = preds.reshape(-1).float() + + background = labels == 0 + fp_change = background.float() + num_bg = fp_change.sum() + + f_lim = float(self.fpr_limit) + + if num_bg <= 0: + return ( + torch.tensor([0.0, f_lim], device=device), + torch.tensor([0.0, 0.0], device=device), + ) + + max_label = int(labels.max().item()) + if max_label == 0: + return ( + torch.tensor([0.0, f_lim], device=device), + torch.tensor([0.0, 0.0], device=device), + ) + + region_sizes = torch.bincount(labels, minlength=max_label + 1).float() + num_regions = (region_sizes[1:] > 0).sum() + + if num_regions <= 0: + return ( + torch.tensor([0.0, f_lim], device=device), + torch.tensor([0.0, 0.0], device=device), + ) + + fg_mask = labels > 0 + pro_change = torch.zeros_like(preds_flat) + pro_change[fg_mask] = 1.0 / region_sizes[labels[fg_mask]] + + idx = torch.argsort(preds_flat, descending=True) + fp_sorted = fp_change[idx] + pro_sorted = pro_change[idx] + preds_sorted = preds_flat[idx] + + fpr = torch.cumsum(fp_sorted, 0) / num_bg + pro = torch.cumsum(pro_sorted, 0) / num_regions + fpr = torch.clamp(fpr, max=1.0) + pro = torch.clamp(pro, max=1.0) + + # remove duplicate thresholds + keep = torch.ones_like(preds_sorted, dtype=torch.bool) + keep[:-1] = preds_sorted[:-1] != preds_sorted[1:] + fpr = fpr[keep] + pro = pro[keep] + + # prepend zero + fpr = torch.cat([torch.tensor([0.0], device=device), fpr]) + pro = torch.cat([torch.tensor([0.0], device=device), pro]) + + # clip at fpr_limit with linear interpolation + mask = fpr <= f_lim + if mask.any(): + i = int(mask.nonzero(as_tuple=True)[0][-1].item()) + if fpr[i] < f_lim and i + 1 < fpr.numel(): + f1, f2 = fpr[i], fpr[i + 1] + p1, p2 = pro[i], pro[i + 1] + p_lim = p1 + (p2 - p1) * (f_lim - f1) / (f2 - f1 + 1e-12) + fpr = torch.cat([fpr[: i + 1], torch.tensor([f_lim], device=device)]) + pro = torch.cat([pro[: i + 1], torch.tensor([p_lim], device=device)]) + else: + fpr = fpr[: i + 1] + pro = pro[: i + 1] + else: + fpr = torch.tensor([0.0, f_lim], device=device) + pro = torch.tensor([0.0, 0.0], device=device) + + return fpr, pro + + def compute(self) -> torch.Tensor: + if not self._preds: + return torch.tensor(0.0) + + cca = self.perform_cca() # (B,H,W) on CPU + preds = torch.cat(self._preds, dim=0) # (B,H,W) on CPU + + # compute PRO curve on CPU tensors + fpr, pro = self.compute_pro(cca=cca, preds=preds) + + area = self._auc_trapz(fpr, pro) + # normalize by fpr_limit (or by last x) + denom = fpr[-1].clamp_min(1e-12) + return area / denom + + +# ----------------------------- +# Utilities: metrics (no sklearn) +# ----------------------------- +def confusion_counts(y_true: np.ndarray, y_pred: np.ndarray): + y_true = y_true.astype(np.int64) + y_pred = y_pred.astype(np.int64) + tp = int(((y_true == 1) & (y_pred == 1)).sum()) + tn = int(((y_true == 0) & (y_pred == 0)).sum()) + fp = int(((y_true == 0) & (y_pred == 1)).sum()) + fn = int(((y_true == 1) & (y_pred == 0)).sum()) + return tp, tn, fp, fn + + +def precision_from_counts(tp: int, fp: int) -> float: + return float(tp / (tp + fp + 1e-12)) + + +def accuracy_from_counts(tp: int, tn: int, fp: int, fn: int) -> float: + return float((tp + tn) / (tp + tn + fp + fn + 1e-12)) + + +def auroc_from_scores(y_true: np.ndarray, y_score: np.ndarray) -> float: + """AUROC via Mann–Whitney U (rank-based), tie-safe.""" + y_true = y_true.astype(np.int64) + y_score = y_score.astype(np.float64) + + pos = (y_true == 1) + neg = (y_true == 0) + n_pos = int(pos.sum()) + n_neg = int(neg.sum()) + if n_pos == 0 or n_neg == 0: + return float("nan") + + order = np.argsort(y_score, kind="mergesort") + ranks = np.empty_like(order, dtype=np.float64) + ranks[order] = np.arange(1, len(y_score) + 1, dtype=np.float64) + + sorted_scores = y_score[order] + i = 0 + while i < len(sorted_scores): + j = i + while j + 1 < len(sorted_scores) and sorted_scores[j + 1] == sorted_scores[i]: + j += 1 + if j > i: + avg_rank = (i + 1 + j + 1) / 2.0 + ranks[order[i : j + 1]] = avg_rank + i = j + 1 + + sum_ranks_pos = float(ranks[pos].sum()) + u = sum_ranks_pos - n_pos * (n_pos + 1) / 2.0 + auc = u / (n_pos * n_neg) + return float(auc) + + +def load_calibration(checkpoint_path: str, calibration_path: Optional[str]) -> dict: + candidates = [] + if calibration_path: + candidates.append(Path(calibration_path)) + checkpoint = Path(checkpoint_path) + candidates.extend( + [checkpoint.parent / "calibration.json", checkpoint.parent.parent / "calibration.json"] + ) + for candidate in candidates: + if candidate.is_file(): + with candidate.open("r", encoding="utf-8") as f: + calibration = json.load(f) + if "image_threshold" not in calibration or "pixel_threshold" not in calibration: + raise ValueError(f"Invalid calibration file: {candidate}") + print(f"Loaded calibration: {candidate}") + return calibration + raise FileNotFoundError( + "No calibration.json found. Run train.py with the updated pipeline or pass --calibration_path." + ) + + +# ----------------------------- +# Data helpers +# ----------------------------- +def iter_images_recursive(root: Path): + exts = {".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff"} + for p in root.rglob("*"): + if not p.is_file(): + continue + if p.suffix.lower() not in exts: + continue + if "ground_truth" in {x.lower() for x in p.parts}: + continue + yield p + + +def infer_gt_label_from_path(p: Path) -> Optional[int]: + parts = [x.lower() for x in p.parts] + if "test" not in parts: + return None + i = parts.index("test") + if i + 1 >= len(parts): + return None + return 0 if parts[i + 1] == "good" else 1 + + +def defect_name_from_path(p: Path) -> str: + parts = list(p.parts) + lower = [x.lower() for x in parts] + if "test" in lower: + i = lower.index("test") + if i + 1 < len(parts): + return parts[i + 1] + return p.parent.name + + +def load_gt_mask_mvtec(img_path: Path) -> Optional[np.ndarray]: + parts = list(img_path.parts) + lower = [p.lower() for p in parts] + if "test" not in lower: + return None + ti = lower.index("test") + if ti + 1 >= len(parts): + return None + + defect = parts[ti + 1] + if defect.lower() == "good": + return None + + cat_dir = img_path.parents[2] # .../ + gt_path = cat_dir / "ground_truth" / defect / f"{img_path.stem}_mask.png" + if not gt_path.exists(): + gt_path = cat_dir / "ground_truth" / defect / f"{img_path.stem}.png" + if not gt_path.exists(): + return None + + m = cv2.imread(str(gt_path), cv2.IMREAD_GRAYSCALE) + if m is None: + return None + return ((m > 0).astype(np.uint8) * 255) + + +# ----------------------------- +# Collected prediction +# ----------------------------- +@dataclass +class Sample: + path: Path + gt_label: Optional[int] + score_raw: float + amap_hw: np.ndarray + orig_rgb: np.ndarray + gt_mask_orig: Optional[np.ndarray] diff --git a/anomaly_detection/modeling/__init__.py b/anomaly_detection/modeling/__init__.py index d304c38..b7d26f8 100644 --- a/anomaly_detection/modeling/__init__.py +++ b/anomaly_detection/modeling/__init__.py @@ -1,10 +1,13 @@ """Anomaly-detection model implementations.""" from anomaly_detection.modeling.fastflow import FastFlowModel +from anomaly_detection.modeling.feature_heads import DinomalyModel, PadimModel, PatchcoreModel from anomaly_detection.modeling.supersimplenet import SuperSimpleNetModel __all__ = [ "FastFlowModel", "SuperSimpleNetModel", + "DinomalyModel", + "PadimModel", + "PatchcoreModel", ] - diff --git a/anomaly_detection/training/fastflow.py b/anomaly_detection/training/fastflow.py index 415ca59..0347274 100644 --- a/anomaly_detection/training/fastflow.py +++ b/anomaly_detection/training/fastflow.py @@ -1,4 +1,4 @@ -# trainer.py +"""FastFlow training, validation calibration and final evaluation.""" from pathlib import Path from typing import Any, Dict, Optional diff --git a/anomaly_detection/training/supersimplenet.py b/anomaly_detection/training/supersimplenet.py index a57c9e3..58bfbb6 100644 --- a/anomaly_detection/training/supersimplenet.py +++ b/anomaly_detection/training/supersimplenet.py @@ -1,10 +1,4 @@ -# ssntrainer.py -# Updated anomalib-style SSN trainer/evaluator with: -# - Stable truncation loss (applies on sigmoid(map_logits)) -# - Validation-loss checkpoint selection with an untouched test set -# - Fixed anomaly-score direction (higher means more anomalous) -# - Mask alignment safety (resizes masks to pred_map size with NEAREST) -# - Accuracy and precision from validation-calibrated fixed thresholds +"""SuperSimpleNet training, validation calibration and final evaluation.""" from __future__ import annotations diff --git a/docs/repository_layout.md b/docs/repository_layout.md new file mode 100644 index 0000000..9f695b7 --- /dev/null +++ b/docs/repository_layout.md @@ -0,0 +1,74 @@ +# Repository layout and maintenance + +## Commands + +| File | Role | +| --- | --- | +| `train.py` | Stable training command; delegates to the package CLI | +| `anomaly_detection/__main__.py` | Enables the equivalent `python -m anomaly_detection` command | +| `anomaly_detection/cli.py` | YAML and legacy flag parsing, configuration checks, pipeline launch | +| `anomaly_detection/predict.py` | Shared checkpoint-based prediction for all five detectors | +| `inference.py` | FastFlow dataset inference, metrics and overlays | +| `ssn_inference.py` | SSN dataset inference, metrics and overlays | +| `anomaly_detection/smoke.py` | Synthetic fitting/training/reload and CUDA memory checks | + +The two legacy inference scripts have distinct scoring/evaluation behavior and +remain supported. Common metrics, calibration lookup and file helpers live in +`anomaly_detection/inference_utils.py`; image/mask geometry lives in +`anomaly_detection/preprocessing.py`. Existing helper imports from the legacy +scripts continue to work because those scripts import the shared names. + +## Implementation + +| Location | Responsibility | +| --- | --- | +| `anomaly_detection/config.py` | Safe YAML schema, defaults, compatible backbone/head/loss combinations | +| `anomaly_detection/builder.py` | Explicit model/loss/trainer factories | +| `anomaly_detection/pipeline.py` | Training, held-out calibration and final evaluation lifecycle | +| `anomaly_detection/data.py` | MVTec/VisA datasets and deterministic partitioning | +| `anomaly_detection/modeling/` | Five detector classes; frozen DINO features and feature-head implementations | +| `anomaly_detection/training/` | Model-specific trainers, evaluators, losses and gradient accumulation | +| `anomaly_detection/preprocessing.py` | Shared resize, center crop, normalization and coordinate restoration | +| `anomaly_detection/inference_utils.py` | Shared legacy inference metrics, calibration and file lookup | + +All five model classes are exported by `anomaly_detection.modeling`. Package +`__init__.py` files provide package/import boundaries and are intentional. + +## Examples and documentation + +`configs/` contains three ResNet examples (FastFlow, SSN focal, SSN BCE) and +five DINO examples, one for each detector. These are editable starting points, +not duplicate implementation files. Keep a distinct run name for each experiment. + +| Guide | Purpose | +| --- | --- | +| `README.md` | Installation, quick start and command overview | +| `docs/yaml_training.md` | Configuration reference | +| `docs/detector_choices.md` | Detector/loss matrix and experimental algorithm differences | +| `docs/gpu_memory.md` | DINO geometry, CUDA setup and memory measurement | +| `docs/inference.md` | Checkpoint preprocessing, mask alignment and prediction outputs | + +## Tests and repository settings + +`tests/` holds regressions for configuration, YAML training/evaluation, DINO +geometry, feature heads, preprocessing and shared inference helpers. They use +synthetic datasets and randomly initialized backbones; they do not certify +real-world anomaly accuracy or physical GPU memory usage. + +`requirements.txt` declares runtime dependencies; `requirements-dev.txt` adds +test/static-check tools. `pyproject.toml` configures pytest, `.editorconfig` +defines editing conventions, `.gitignore` excludes generated data, and +`.github/workflows/tests.yml` runs CPU CI. All serve distinct purposes. + +Datasets, downloaded weights, checkpoints, prediction files, caches and run +outputs belong outside tracked source. The audit found no tracked copies of +these artifacts to delete. Avoid deleting tests, examples or compatibility +entry points simply because they are not imported during a particular run. + +Before submitting changes, run: + +```bash +python -m compileall -q . +python -m pyflakes . +python -m pytest -q +``` diff --git a/inference.py b/inference.py index 30307d6..bb35eca 100644 --- a/inference.py +++ b/inference.py @@ -6,8 +6,6 @@ # - contour overlay drawn on ORIGINAL image, but thresholding done in crop-space then "uncropped" back import argparse -import json -from dataclasses import dataclass from pathlib import Path from typing import List, Optional, Tuple @@ -19,345 +17,11 @@ from anomaly_detection.modeling import FastFlowModel -# ============================================================ -# Self-implemented AUPRO (minimal, compute-only, no torchmetrics) -# ============================================================ -class SelfAUPRO: - """ - Minimal AUPRO implementation inspired by anomalib's AUPRO: - - connected components on GT mask - - compute PRO curve (FPR vs averaged per-region overlap) - - integrate area up to fpr_limit and normalize by fpr_limit - - Expected: - preds: (B,H,W) or (B,1,H,W) float in [0,1] (higher => more anomalous) - target: (B,H,W) or (B,1,H,W) binary {0,1} or {0,255} - """ - - def __init__(self, fpr_limit: float = 0.3): - self.fpr_limit = float(fpr_limit) - self._preds: List[torch.Tensor] = [] - self._target: List[torch.Tensor] = [] - - def update(self, preds: torch.Tensor, target: torch.Tensor) -> None: - if preds.dim() == 4 and preds.size(1) == 1: - preds = preds.squeeze(1) - if target.dim() == 4 and target.size(1) == 1: - target = target.squeeze(1) - - # store on CPU to reduce GPU memory - preds = preds.detach().float().cpu() - target = target.detach().float().cpu() - - # normalize target into {0,1} - if target.max() > 1.0: - target = (target > 0).float() - else: - target = (target > 0.5).float() - - # clamp preds - preds = preds.clamp(0.0, 1.0) - - self._preds.append(preds) - self._target.append(target) - - @staticmethod - def _cca_cv2(mask01: np.ndarray) -> np.ndarray: - """Connected components for one image. mask01 is {0,1} uint8.""" - mask01 = (mask01 > 0).astype(np.uint8) - # returns labels in [0..N] - _, labels = cv2.connectedComponents(mask01, connectivity=8) - return labels.astype(np.int32) - - @staticmethod - def _make_global_region_labels(cca_bhw: torch.Tensor) -> torch.Tensor: - """Offset connected component labels across batch to make them unique (except 0 background).""" - cca_off = cca_bhw.clone() - current_offset = 0 - B = int(cca_off.size(0)) - for b in range(B): - img = cca_off[b] - uniq = torch.unique(img) - uniq_fg = uniq[uniq != 0] - num_regions = int(uniq_fg.numel()) - if num_regions == 0: - continue - fg = img > 0 - img[fg] = img[fg] + current_offset - cca_off[b] = img - current_offset += num_regions - return cca_off - - def perform_cca(self) -> torch.Tensor: - """Return (B,H,W) integer labels; 0 is background; >0 are region IDs unique across batch.""" - target = torch.cat(self._target, dim=0) # (B,H,W) - if target.min() < 0 or target.max() > 1: - raise ValueError(f"AUPRO expects target in [0,1], got [{float(target.min())},{float(target.max())}]") - - # CPU CCA via OpenCV per image - target_np = target.numpy() - ccas = [] - for b in range(target_np.shape[0]): - labels = self._cca_cv2(target_np[b]) - ccas.append(labels) - cca = torch.from_numpy(np.stack(ccas, axis=0)) # (B,H,W) int32 - cca = self._make_global_region_labels(cca) - return cca.long() - - @staticmethod - def _auc_trapz(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: - """Trapezoidal integration (assumes x sorted ascending).""" - if x.numel() < 2: - return torch.tensor(0.0, device=x.device, dtype=torch.float32) - dx = x[1:] - x[:-1] - avg = 0.5 * (y[1:] + y[:-1]) - return torch.sum(dx * avg) - - def compute_pro(self, cca: torch.Tensor, preds: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Compute PRO curve (FPR vs averaged per-region overlap). - cca: (B,H,W) int labels, 0 background - preds: (B,H,W) float, higher => more anomalous - """ - device = preds.device - - labels = cca.reshape(-1).long() - preds_flat = preds.reshape(-1).float() - - background = labels == 0 - fp_change = background.float() - num_bg = fp_change.sum() - - f_lim = float(self.fpr_limit) - - if num_bg <= 0: - return ( - torch.tensor([0.0, f_lim], device=device), - torch.tensor([0.0, 0.0], device=device), - ) - - max_label = int(labels.max().item()) - if max_label == 0: - return ( - torch.tensor([0.0, f_lim], device=device), - torch.tensor([0.0, 0.0], device=device), - ) - - region_sizes = torch.bincount(labels, minlength=max_label + 1).float() - num_regions = (region_sizes[1:] > 0).sum() - - if num_regions <= 0: - return ( - torch.tensor([0.0, f_lim], device=device), - torch.tensor([0.0, 0.0], device=device), - ) - - fg_mask = labels > 0 - pro_change = torch.zeros_like(preds_flat) - pro_change[fg_mask] = 1.0 / region_sizes[labels[fg_mask]] - - idx = torch.argsort(preds_flat, descending=True) - fp_sorted = fp_change[idx] - pro_sorted = pro_change[idx] - preds_sorted = preds_flat[idx] - - fpr = torch.cumsum(fp_sorted, 0) / num_bg - pro = torch.cumsum(pro_sorted, 0) / num_regions - fpr = torch.clamp(fpr, max=1.0) - pro = torch.clamp(pro, max=1.0) - - # remove duplicate thresholds - keep = torch.ones_like(preds_sorted, dtype=torch.bool) - keep[:-1] = preds_sorted[:-1] != preds_sorted[1:] - fpr = fpr[keep] - pro = pro[keep] - - # prepend zero - fpr = torch.cat([torch.tensor([0.0], device=device), fpr]) - pro = torch.cat([torch.tensor([0.0], device=device), pro]) - - # clip at fpr_limit with linear interpolation - mask = fpr <= f_lim - if mask.any(): - i = int(mask.nonzero(as_tuple=True)[0][-1].item()) - if fpr[i] < f_lim and i + 1 < fpr.numel(): - f1, f2 = fpr[i], fpr[i + 1] - p1, p2 = pro[i], pro[i + 1] - p_lim = p1 + (p2 - p1) * (f_lim - f1) / (f2 - f1 + 1e-12) - fpr = torch.cat([fpr[: i + 1], torch.tensor([f_lim], device=device)]) - pro = torch.cat([pro[: i + 1], torch.tensor([p_lim], device=device)]) - else: - fpr = fpr[: i + 1] - pro = pro[: i + 1] - else: - fpr = torch.tensor([0.0, f_lim], device=device) - pro = torch.tensor([0.0, 0.0], device=device) - - return fpr, pro - - def compute(self) -> torch.Tensor: - if not self._preds: - return torch.tensor(0.0) - - cca = self.perform_cca() # (B,H,W) on CPU - preds = torch.cat(self._preds, dim=0) # (B,H,W) on CPU - - # compute PRO curve on CPU tensors - fpr, pro = self.compute_pro(cca=cca, preds=preds) - - area = self._auc_trapz(fpr, pro) - # normalize by fpr_limit (or by last x) - denom = fpr[-1].clamp_min(1e-12) - return area / denom - - -# ----------------------------- -# Utilities: metrics (no sklearn) -# ----------------------------- -def confusion_counts(y_true: np.ndarray, y_pred: np.ndarray): - y_true = y_true.astype(np.int64) - y_pred = y_pred.astype(np.int64) - tp = int(((y_true == 1) & (y_pred == 1)).sum()) - tn = int(((y_true == 0) & (y_pred == 0)).sum()) - fp = int(((y_true == 0) & (y_pred == 1)).sum()) - fn = int(((y_true == 1) & (y_pred == 0)).sum()) - return tp, tn, fp, fn - - -def precision_from_counts(tp: int, fp: int) -> float: - return float(tp / (tp + fp + 1e-12)) - - -def accuracy_from_counts(tp: int, tn: int, fp: int, fn: int) -> float: - return float((tp + tn) / (tp + tn + fp + fn + 1e-12)) - - -def auroc_from_scores(y_true: np.ndarray, y_score: np.ndarray) -> float: - """AUROC via Mann–Whitney U (rank-based), tie-safe.""" - y_true = y_true.astype(np.int64) - y_score = y_score.astype(np.float64) - - pos = (y_true == 1) - neg = (y_true == 0) - n_pos = int(pos.sum()) - n_neg = int(neg.sum()) - if n_pos == 0 or n_neg == 0: - return float("nan") - - order = np.argsort(y_score, kind="mergesort") - ranks = np.empty_like(order, dtype=np.float64) - ranks[order] = np.arange(1, len(y_score) + 1, dtype=np.float64) - - sorted_scores = y_score[order] - i = 0 - while i < len(sorted_scores): - j = i - while j + 1 < len(sorted_scores) and sorted_scores[j + 1] == sorted_scores[i]: - j += 1 - if j > i: - avg_rank = (i + 1 + j + 1) / 2.0 - ranks[order[i : j + 1]] = avg_rank - i = j + 1 - - sum_ranks_pos = float(ranks[pos].sum()) - u = sum_ranks_pos - n_pos * (n_pos + 1) / 2.0 - auc = u / (n_pos * n_neg) - return float(auc) - - -def load_calibration(checkpoint_path: str, calibration_path: Optional[str]) -> dict: - candidates = [] - if calibration_path: - candidates.append(Path(calibration_path)) - checkpoint = Path(checkpoint_path) - candidates.extend( - [checkpoint.parent / "calibration.json", checkpoint.parent.parent / "calibration.json"] - ) - for candidate in candidates: - if candidate.is_file(): - with candidate.open("r", encoding="utf-8") as f: - calibration = json.load(f) - if "image_threshold" not in calibration or "pixel_threshold" not in calibration: - raise ValueError(f"Invalid calibration file: {candidate}") - print(f"Loaded calibration: {candidate}") - return calibration - raise FileNotFoundError( - "No calibration.json found. Run train.py with the updated pipeline or pass --calibration_path." - ) - - -# ----------------------------- -# Data helpers -# ----------------------------- -def iter_images_recursive(root: Path): - exts = {".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff"} - for p in root.rglob("*"): - if not p.is_file(): - continue - if p.suffix.lower() not in exts: - continue - if "ground_truth" in {x.lower() for x in p.parts}: - continue - yield p - - -def infer_gt_label_from_path(p: Path) -> Optional[int]: - parts = [x.lower() for x in p.parts] - if "test" not in parts: - return None - i = parts.index("test") - if i + 1 >= len(parts): - return None - return 0 if parts[i + 1] == "good" else 1 - - -def defect_name_from_path(p: Path) -> str: - parts = list(p.parts) - lower = [x.lower() for x in parts] - if "test" in lower: - i = lower.index("test") - if i + 1 < len(parts): - return parts[i + 1] - return p.parent.name - - -def load_gt_mask_mvtec(img_path: Path) -> Optional[np.ndarray]: - parts = list(img_path.parts) - lower = [p.lower() for p in parts] - if "test" not in lower: - return None - ti = lower.index("test") - if ti + 1 >= len(parts): - return None - - defect = parts[ti + 1] - if defect.lower() == "good": - return None - - cat_dir = img_path.parents[2] # .../ - gt_path = cat_dir / "ground_truth" / defect / f"{img_path.stem}_mask.png" - if not gt_path.exists(): - gt_path = cat_dir / "ground_truth" / defect / f"{img_path.stem}.png" - if not gt_path.exists(): - return None - - m = cv2.imread(str(gt_path), cv2.IMREAD_GRAYSCALE) - if m is None: - return None - return ((m > 0).astype(np.uint8) * 255) - - -# ----------------------------- -# Core OOP runner -# ----------------------------- -@dataclass -class Sample: - path: Path - gt_label: Optional[int] - score_raw: float - amap_hw: np.ndarray - orig_rgb: np.ndarray - gt_mask_orig: Optional[np.ndarray] +from anomaly_detection.inference_utils import ( + Sample, SelfAUPRO, accuracy_from_counts, auroc_from_scores, confusion_counts, + defect_name_from_path, infer_gt_label_from_path, iter_images_recursive, + load_calibration, load_gt_mask_mvtec, precision_from_counts, +) class FastFlowInferenceEngine(InferencePreprocessing): diff --git a/ssn_inference.py b/ssn_inference.py index 4f4c775..7c9b0ec 100644 --- a/ssn_inference.py +++ b/ssn_inference.py @@ -6,8 +6,6 @@ # - contour overlay drawn on ORIGINAL image, but thresholding done in crop-space then "uncropped" back import argparse -import json -from dataclasses import dataclass from pathlib import Path from typing import List, Optional, Tuple @@ -20,315 +18,11 @@ from anomaly_detection.config import BACKBONES -# ============================================================ -# Self-implemented AUPRO (minimal, compute-only, no torchmetrics) -# ============================================================ -class SelfAUPRO: - """ - Minimal AUPRO implementation inspired by anomalib's AUPRO: - - connected components on GT mask - - compute PRO curve (FPR vs averaged per-region overlap) - - integrate area up to fpr_limit and normalize by fpr_limit - - Expected: - preds: (B,H,W) or (B,1,H,W) float in [0,1] (higher => more anomalous) - target: (B,H,W) or (B,1,H,W) binary {0,1} or {0,255} - """ - - def __init__(self, fpr_limit: float = 0.3): - self.fpr_limit = float(fpr_limit) - self._preds: List[torch.Tensor] = [] - self._target: List[torch.Tensor] = [] - - def update(self, preds: torch.Tensor, target: torch.Tensor) -> None: - if preds.dim() == 4 and preds.size(1) == 1: - preds = preds.squeeze(1) - if target.dim() == 4 and target.size(1) == 1: - target = target.squeeze(1) - - preds = preds.detach().float().cpu() - target = target.detach().float().cpu() - - # normalize target into {0,1} - if target.max() > 1.0: - target = (target > 0).float() - else: - target = (target > 0.5).float() - - preds = preds.clamp(0.0, 1.0) - - self._preds.append(preds) - self._target.append(target) - - @staticmethod - def _cca_cv2(mask01: np.ndarray) -> np.ndarray: - mask01 = (mask01 > 0).astype(np.uint8) - _, labels = cv2.connectedComponents(mask01, connectivity=8) - return labels.astype(np.int32) - - @staticmethod - def _make_global_region_labels(cca_bhw: torch.Tensor) -> torch.Tensor: - cca_off = cca_bhw.clone() - current_offset = 0 - B = int(cca_off.size(0)) - for b in range(B): - img = cca_off[b] - uniq = torch.unique(img) - uniq_fg = uniq[uniq != 0] - num_regions = int(uniq_fg.numel()) - if num_regions == 0: - continue - fg = img > 0 - img[fg] = img[fg] + current_offset - cca_off[b] = img - current_offset += num_regions - return cca_off - - def perform_cca(self) -> torch.Tensor: - target = torch.cat(self._target, dim=0) # (B,H,W) - if target.min() < 0 or target.max() > 1: - raise ValueError(f"AUPRO expects target in [0,1], got [{float(target.min())},{float(target.max())}]") - - target_np = target.numpy() - ccas = [] - for b in range(target_np.shape[0]): - labels = self._cca_cv2(target_np[b]) - ccas.append(labels) - cca = torch.from_numpy(np.stack(ccas, axis=0)) - cca = self._make_global_region_labels(cca) - return cca.long() - - @staticmethod - def _auc_trapz(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: - if x.numel() < 2: - return torch.tensor(0.0, device=x.device, dtype=torch.float32) - dx = x[1:] - x[:-1] - avg = 0.5 * (y[1:] + y[:-1]) - return torch.sum(dx * avg) - - def compute_pro(self, cca: torch.Tensor, preds: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: - device = preds.device - labels = cca.reshape(-1).long() - preds_flat = preds.reshape(-1).float() - - background = labels == 0 - fp_change = background.float() - num_bg = fp_change.sum() - - f_lim = float(self.fpr_limit) - if num_bg <= 0: - return (torch.tensor([0.0, f_lim], device=device), torch.tensor([0.0, 0.0], device=device)) - - max_label = int(labels.max().item()) - if max_label == 0: - return (torch.tensor([0.0, f_lim], device=device), torch.tensor([0.0, 0.0], device=device)) - - region_sizes = torch.bincount(labels, minlength=max_label + 1).float() - num_regions = (region_sizes[1:] > 0).sum() - if num_regions <= 0: - return (torch.tensor([0.0, f_lim], device=device), torch.tensor([0.0, 0.0], device=device)) - - fg_mask = labels > 0 - pro_change = torch.zeros_like(preds_flat) - pro_change[fg_mask] = 1.0 / region_sizes[labels[fg_mask]] - - idx = torch.argsort(preds_flat, descending=True) - fp_sorted = fp_change[idx] - pro_sorted = pro_change[idx] - preds_sorted = preds_flat[idx] - - fpr = torch.cumsum(fp_sorted, 0) / num_bg - pro = torch.cumsum(pro_sorted, 0) / num_regions - fpr = torch.clamp(fpr, max=1.0) - pro = torch.clamp(pro, max=1.0) - - keep = torch.ones_like(preds_sorted, dtype=torch.bool) - keep[:-1] = preds_sorted[:-1] != preds_sorted[1:] - fpr = fpr[keep] - pro = pro[keep] - - fpr = torch.cat([torch.tensor([0.0], device=device), fpr]) - pro = torch.cat([torch.tensor([0.0], device=device), pro]) - - mask = fpr <= f_lim - if mask.any(): - i = int(mask.nonzero(as_tuple=True)[0][-1].item()) - if fpr[i] < f_lim and i + 1 < fpr.numel(): - f1, f2 = fpr[i], fpr[i + 1] - p1, p2 = pro[i], pro[i + 1] - p_lim = p1 + (p2 - p1) * (f_lim - f1) / (f2 - f1 + 1e-12) - fpr = torch.cat([fpr[: i + 1], torch.tensor([f_lim], device=device)]) - pro = torch.cat([pro[: i + 1], torch.tensor([p_lim], device=device)]) - else: - fpr = fpr[: i + 1] - pro = pro[: i + 1] - else: - fpr = torch.tensor([0.0, f_lim], device=device) - pro = torch.tensor([0.0, 0.0], device=device) - - return fpr, pro - - def compute(self) -> torch.Tensor: - if not self._preds: - return torch.tensor(0.0) - - cca = self.perform_cca() - preds = torch.cat(self._preds, dim=0) - - fpr, pro = self.compute_pro(cca=cca, preds=preds) - area = self._auc_trapz(fpr, pro) - - denom = fpr[-1].clamp_min(1e-12) # usually == fpr_limit - return area / denom - - -# ----------------------------- -# Utilities: metrics (no sklearn) -# ----------------------------- -def confusion_counts(y_true: np.ndarray, y_pred: np.ndarray): - y_true = y_true.astype(np.int64) - y_pred = y_pred.astype(np.int64) - tp = int(((y_true == 1) & (y_pred == 1)).sum()) - tn = int(((y_true == 0) & (y_pred == 0)).sum()) - fp = int(((y_true == 0) & (y_pred == 1)).sum()) - fn = int(((y_true == 1) & (y_pred == 0)).sum()) - return tp, tn, fp, fn - - -def precision_from_counts(tp: int, fp: int) -> float: - return float(tp / (tp + fp + 1e-12)) - - -def accuracy_from_counts(tp: int, tn: int, fp: int, fn: int) -> float: - return float((tp + tn) / (tp + tn + fp + fn + 1e-12)) - - -def auroc_from_scores(y_true: np.ndarray, y_score: np.ndarray) -> float: - """AUROC via Mann–Whitney U (rank-based), tie-safe.""" - y_true = y_true.astype(np.int64) - y_score = y_score.astype(np.float64) - - pos = (y_true == 1) - neg = (y_true == 0) - n_pos = int(pos.sum()) - n_neg = int(neg.sum()) - if n_pos == 0 or n_neg == 0: - return float("nan") - - order = np.argsort(y_score, kind="mergesort") - ranks = np.empty_like(order, dtype=np.float64) - ranks[order] = np.arange(1, len(y_score) + 1, dtype=np.float64) - - sorted_scores = y_score[order] - i = 0 - while i < len(sorted_scores): - j = i - while j + 1 < len(sorted_scores) and sorted_scores[j + 1] == sorted_scores[i]: - j += 1 - if j > i: - avg_rank = (i + 1 + j + 1) / 2.0 - ranks[order[i : j + 1]] = avg_rank - i = j + 1 - - sum_ranks_pos = float(ranks[pos].sum()) - u = sum_ranks_pos - n_pos * (n_pos + 1) / 2.0 - auc = u / (n_pos * n_neg) - return float(auc) - - -def load_calibration(checkpoint_path: str, calibration_path: Optional[str]) -> dict: - candidates = [] - if calibration_path: - candidates.append(Path(calibration_path)) - checkpoint = Path(checkpoint_path) - candidates.extend( - [checkpoint.parent / "calibration.json", checkpoint.parent.parent / "calibration.json"] - ) - for candidate in candidates: - if candidate.is_file(): - with candidate.open("r", encoding="utf-8") as f: - calibration = json.load(f) - if "image_threshold" not in calibration or "pixel_threshold" not in calibration: - raise ValueError(f"Invalid calibration file: {candidate}") - print(f"Loaded calibration: {candidate}") - return calibration - raise FileNotFoundError( - "No calibration.json found. Run train.py with the updated pipeline or pass --calibration_path." - ) - - -# ----------------------------- -# Data helpers -# ----------------------------- -def iter_images_recursive(root: Path): - exts = {".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff"} - for p in root.rglob("*"): - if not p.is_file(): - continue - if p.suffix.lower() not in exts: - continue - if "ground_truth" in {x.lower() for x in p.parts}: - continue - yield p - - -def infer_gt_label_from_path(p: Path) -> Optional[int]: - parts = [x.lower() for x in p.parts] - if "test" not in parts: - return None - i = parts.index("test") - if i + 1 >= len(parts): - return None - return 0 if parts[i + 1] == "good" else 1 - - -def defect_name_from_path(p: Path) -> str: - parts = list(p.parts) - lower = [x.lower() for x in parts] - if "test" in lower: - i = lower.index("test") - if i + 1 < len(parts): - return parts[i + 1] - return p.parent.name - - -def load_gt_mask_mvtec(img_path: Path) -> Optional[np.ndarray]: - parts = list(img_path.parts) - lower = [p.lower() for p in parts] - if "test" not in lower: - return None - ti = lower.index("test") - if ti + 1 >= len(parts): - return None - - defect = parts[ti + 1] - if defect.lower() == "good": - return None - - cat_dir = img_path.parents[2] # .../ - gt_path = cat_dir / "ground_truth" / defect / f"{img_path.stem}_mask.png" - if not gt_path.exists(): - gt_path = cat_dir / "ground_truth" / defect / f"{img_path.stem}.png" - if not gt_path.exists(): - return None - - m = cv2.imread(str(gt_path), cv2.IMREAD_GRAYSCALE) - if m is None: - return None - return ((m > 0).astype(np.uint8) * 255) - - -# ----------------------------- -# Core OOP runner (SSN) -# ----------------------------- -@dataclass -class Sample: - path: Path - gt_label: Optional[int] - score_raw: float # SSN pred_score (sigmoid) by default - amap_hw: np.ndarray # SSN pred_map in crop-space (h,w), float32 [0,1] - orig_rgb: np.ndarray - gt_mask_orig: Optional[np.ndarray] +from anomaly_detection.inference_utils import ( + Sample, SelfAUPRO, accuracy_from_counts, auroc_from_scores, confusion_counts, + defect_name_from_path, infer_gt_label_from_path, iter_images_recursive, + load_calibration, load_gt_mask_mvtec, precision_from_counts, +) class SSNInferenceEngine(InferencePreprocessing): diff --git a/tests/test_inference_utils.py b/tests/test_inference_utils.py new file mode 100644 index 0000000..7e71b05 --- /dev/null +++ b/tests/test_inference_utils.py @@ -0,0 +1,77 @@ +"""Regression coverage for shared inference metrics and file helpers.""" + +import json + +import numpy as np +from PIL import Image +import pytest +import torch + +from anomaly_detection.inference_utils import ( + SelfAUPRO, defect_name_from_path, infer_gt_label_from_path, iter_images_recursive, + load_calibration, load_gt_mask_mvtec, +) + + + +@pytest.mark.parametrize("prediction,expected", [ + ("perfect", 1.0), ("reversed", 0.0), ("tied", 0.15), ("one_region", 0.575), +]) +def test_aupro_ranking_ties_and_equal_region_weighting(prediction, expected): + masks = torch.zeros(2, 1, 3, 3) + masks[0, 0, 0, 0] = 1 + masks[1, 0, :2, :2] = 1 # A larger region in a separate image. + if prediction == "perfect": + scores = masks.clone() + elif prediction == "reversed": + scores = 1 - masks + elif prediction == "tied": + scores = torch.full_like(masks, 0.5) + else: + scores = torch.zeros_like(masks) + scores[0] = masks[0] + metric = SelfAUPRO(fpr_limit=0.3) + # Separate updates and both supported binary-mask encodings. + metric.update(scores[:1], masks[:1]) + metric.update(scores[1:], masks[1:] * 255) + # With one region detected, PRO runs from 0.5 to 0.65 over FPR [0, 0.3]. + assert metric.compute().item() == pytest.approx(expected) + + +def test_calibration_lookup_priority_and_missing_or_invalid_files(tmp_path): + checkpoint = tmp_path / "run/checkpoints/best_model.pth" + checkpoint.parent.mkdir(parents=True) + candidates = [ + tmp_path / "explicit.json", + checkpoint.parent / "calibration.json", + checkpoint.parent.parent / "calibration.json", + ] + for index, path in enumerate(candidates): + path.write_text(json.dumps({"image_threshold": index, "pixel_threshold": index + 0.5})) + assert load_calibration(str(checkpoint), str(candidates[0]))["image_threshold"] == 0 + assert load_calibration(str(checkpoint), None)["image_threshold"] == 1 + candidates[1].unlink() + assert load_calibration(str(checkpoint), None)["image_threshold"] == 2 + candidates[2].unlink() + with pytest.raises(FileNotFoundError, match="No calibration.json"): + load_calibration(str(checkpoint), None) + candidates[0].write_text('{"image_threshold": 0.5}') + with pytest.raises(ValueError, match="Invalid calibration file"): + load_calibration(str(checkpoint), str(candidates[0])) + + +@pytest.mark.parametrize("mask_name", ["001_mask.png", "001.png"]) +def test_mvtec_file_helpers_skip_masks_and_find_both_mask_names(tmp_path, mask_name): + good = tmp_path / "bottle/test/good/001.PNG" + defect = tmp_path / "bottle/test/crack/001.png" + mask = tmp_path / "bottle/ground_truth/crack" / mask_name + for path in (good, defect, mask): + path.parent.mkdir(parents=True, exist_ok=True) + Image.fromarray(np.array([[0, 1], [255, 0]], dtype=np.uint8)).save(path) + (tmp_path / "notes.txt").write_text("not an image") + assert set(iter_images_recursive(tmp_path)) == {good, defect} + assert infer_gt_label_from_path(good) == 0 + assert infer_gt_label_from_path(defect) == 1 + assert defect_name_from_path(defect) == "crack" + assert load_gt_mask_mvtec(good) is None + np.testing.assert_array_equal(load_gt_mask_mvtec(defect), [[0, 255], [255, 0]]) diff --git a/tests/test_yaml_training.py b/tests/test_yaml_training.py index b9b41d2..ee9e063 100644 --- a/tests/test_yaml_training.py +++ b/tests/test_yaml_training.py @@ -14,8 +14,8 @@ from anomaly_detection.config import load_config, resolve_config from anomaly_detection.pipeline import AnomalyPipeline from anomaly_detection.training.losses import FastFlowNLLLoss, SSNBCELoss, SSNLoss -from inference import FastFlowInferenceEngine -from ssn_inference import SSNInferenceEngine +from inference import FastFlowInferenceEngine, MVTecFastFlowEvaluator, iter_images_recursive, load_calibration +from ssn_inference import SSNInferenceEngine, MVTecSSNEvaluator @pytest.fixture(autouse=True) @@ -178,6 +178,22 @@ def capture_loss(cfg): assert np.isfinite(score) and np.isfinite(anomaly_map).all() assert anomaly_map.shape == (32, 32) + # Exercise shared file/calibration/metric helpers with real checkpoint outputs. + evaluator_cls = MVTecFastFlowEvaluator if model_name == "fastflow" else MVTecSSNEvaluator + evaluator = evaluator_cls( + engine=engine, out_dir=tmp_path / "inference", category="bottle", backbone=backbone, + min_area=0, thickness=1, fpr_limit=0.3, aupro_downsample=1, save_mode="pred", + calibration=load_calibration(str(checkpoint_path), None), + ) + evaluator.collect(list(iter_images_recursive(tmp_path / "data/bottle/test"))) + labels, _, _, _ = evaluator.compute_image_metrics() + assert sorted(labels.tolist()) == [0, 1] + evaluator.compute_pixel_metrics() + assert np.isfinite(evaluator.image_metrics["auroc"]) + assert np.isfinite(evaluator.pixel_metrics["pixel_auroc_sampled"]) + assert 0 <= evaluator.pixel_metrics["pixel_aupro"] <= 1 + assert evaluator.image_metrics["threshold"] == calibration["image_threshold"] + # A second invocation must not overwrite a completed experiment implicitly. with pytest.raises(FileExistsError, match="Output directory is not empty"): main(["--config", str(path)])