Download patchcore/model.py from salimamri9/patchcore-mvtec-cpu: direct link, hf CLI and curl.
- Browser
- Download file 8.57 kB
-
https://huggingface.co/salimamri9/patchcore-mvtec-cpu/resolve/main/patchcore/model.py
- Command line
-
hf download hf://salimamri9/patchcore-mvtec-cpu/patchcore/model.py
-
curl -L -o model.py https://huggingface.co/salimamri9/patchcore-mvtec-cpu/resolve/main/patchcore/model.py
8.57 kB
| """PatchCore (Roth et al., CVPR 2022) re-implemented from scratch for CPU. | |
| Pipeline | |
| -------- | |
| image (3x224x224) | |
| -> frozen ImageNet backbone, mid-level features layer2 (C2 x 28 x 28) + layer3 (C3 x 14 x 14) | |
| -> 3x3 local neighbourhood average pooling (locally aware patch features) | |
| -> layer3 upsampled to 28x28, concatenated with layer2 -> (C2+C3) x 28 x 28 | |
| -> channel reduction by adaptive average pooling -> D x 28 x 28 (D=1024 for WRN50) | |
| -> 784 patch vectors per image | |
| Training ("fit") = no gradient descent: patch vectors of all *normal* training | |
| images are stored, then sub-sampled with a greedy k-center coreset. | |
| Inference: every test patch is scored by its distance to the nearest neighbour | |
| in the memory bank. Image score = max patch score; the 28x28 score grid is | |
| upsampled to 224x224 and smoothed with a Gaussian (sigma=4) -> anomaly map. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import math | |
| import time | |
| from pathlib import Path | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from torchvision.models import ( | |
| ResNet18_Weights, | |
| Wide_ResNet50_2_Weights, | |
| resnet18, | |
| wide_resnet50_2, | |
| ) | |
| BACKBONES = { | |
| "wide_resnet50_2": (wide_resnet50_2, Wide_ResNet50_2_Weights.IMAGENET1K_V1), | |
| "resnet18": (resnet18, ResNet18_Weights.IMAGENET1K_V1), | |
| } | |
| class FeatureExtractor(nn.Module): | |
| """Returns layer2 and layer3 feature maps of a frozen torchvision ResNet.""" | |
| def __init__(self, name: str = "wide_resnet50_2"): | |
| super().__init__() | |
| fn, weights = BACKBONES[name] | |
| m = fn(weights=weights) | |
| self.stem = nn.Sequential(m.conv1, m.bn1, m.relu, m.maxpool) | |
| self.layer1, self.layer2, self.layer3 = m.layer1, m.layer2, m.layer3 | |
| # layer4 / fc are dropped: too ImageNet-specific and not needed | |
| self.eval().requires_grad_(False) | |
| def forward(self, x): | |
| x = self.layer1(self.stem(x)) | |
| f2 = self.layer2(x) | |
| f3 = self.layer3(f2) | |
| return f2, f3 | |
| def gaussian_blur(x: torch.Tensor, sigma: float = 4.0) -> torch.Tensor: | |
| """Separable Gaussian blur on a (B,1,H,W) tensor (same as scipy truncate=4).""" | |
| radius = int(4 * sigma + 0.5) | |
| k = torch.arange(-radius, radius + 1, dtype=x.dtype) | |
| k = torch.exp(-(k**2) / (2 * sigma**2)) | |
| k = (k / k.sum()).to(x.device) | |
| x = F.pad(x, (radius, radius, 0, 0), mode="reflect") | |
| x = F.conv2d(x, k.view(1, 1, 1, -1)) | |
| x = F.pad(x, (0, 0, radius, radius), mode="reflect") | |
| return F.conv2d(x, k.view(1, 1, -1, 1)) | |
| def greedy_coreset(feats: torch.Tensor, n: int, proj_dim: int = 128, seed: int = 0) -> torch.Tensor: | |
| """Greedy k-center selection (minimax facility location). | |
| Distances are computed in a random-projection space (Johnson-Lindenstrauss) | |
| of `proj_dim` dimensions, which keeps the O(N * n) loop affordable on CPU. | |
| """ | |
| g = torch.Generator().manual_seed(seed) | |
| N, D = feats.shape | |
| if n >= N: | |
| return torch.arange(N) | |
| P = torch.randn(D, proj_dim, generator=g) / math.sqrt(proj_dim) | |
| z = feats.float() @ P | |
| sq = (z * z).sum(1) | |
| sel = torch.empty(n, dtype=torch.long) | |
| i = int(torch.randint(N, (1,), generator=g)) | |
| min_d = torch.full((N,), float("inf")) | |
| for t in range(n): | |
| sel[t] = i | |
| # ||z - z_i||^2 = |z|^2 + |z_i|^2 - 2 z.z_i (one GEMV instead of a full norm) | |
| d = sq + sq[i] - 2.0 * (z @ z[i]) | |
| torch.minimum(min_d, d, out=min_d) | |
| i = int(torch.argmax(min_d)) | |
| return sel | |
| class PatchCore: | |
| def __init__( | |
| self, | |
| backbone: str = "wide_resnet50_2", | |
| target_dim: int = 1024, | |
| coreset_ratio: float = 0.01, | |
| proj_dim: int = 128, | |
| image_size: int = 224, | |
| blur_sigma: float = 4.0, | |
| extractor: FeatureExtractor | None = None, | |
| ): | |
| self.backbone_name = backbone | |
| self.extractor = extractor if extractor is not None else FeatureExtractor(backbone) | |
| self.target_dim = target_dim | |
| self.coreset_ratio = coreset_ratio | |
| self.proj_dim = proj_dim | |
| self.image_size = image_size | |
| self.blur_sigma = blur_sigma | |
| self.bank: torch.Tensor | None = None | |
| self.bank_sq: torch.Tensor | None = None | |
| self.image_threshold: float | None = None | |
| self.pixel_threshold: float | None = None | |
| self.fmap_hw: tuple[int, int] | None = None | |
| # ------------------------------------------------------------------ features | |
| def embed(self, x: torch.Tensor) -> torch.Tensor: | |
| """(B,3,H,W) -> (B, h*w, D) locally-aware patch features.""" | |
| f2, f3 = self.extractor(x) | |
| f2 = F.avg_pool2d(f2, 3, 1, 1) | |
| f3 = F.avg_pool2d(f3, 3, 1, 1) | |
| f3 = F.interpolate(f3, size=f2.shape[-2:], mode="bilinear", align_corners=False) | |
| f = torch.cat([f2, f3], 1) | |
| B, C, H, W = f.shape | |
| self.fmap_hw = (H, W) | |
| f = f.permute(0, 2, 3, 1).reshape(B * H * W, C) | |
| D = min(self.target_dim, C) | |
| if D != C: | |
| f = F.adaptive_avg_pool1d(f.unsqueeze(1), D).squeeze(1) | |
| return f.reshape(B, H * W, D) | |
| # ------------------------------------------------------------------ fit | |
| def fit(self, loader, log=print) -> dict: | |
| t0 = time.time() | |
| feats = [] | |
| for batch in loader: | |
| f = self.embed(batch["image"]) | |
| feats.append(f.reshape(-1, f.shape[-1])) | |
| feats = torch.cat(feats) | |
| t_feat = time.time() - t0 | |
| n = max(1, int(len(feats) * self.coreset_ratio)) | |
| t1 = time.time() | |
| idx = greedy_coreset(feats, n, self.proj_dim) | |
| t_core = time.time() - t1 | |
| self._set_bank(feats[idx].contiguous()) | |
| log(f" memory bank: {len(feats):,} patches -> coreset {n:,} " | |
| f"(feat {t_feat:.1f}s, coreset {t_core:.1f}s)") | |
| return {"n_patches": len(feats), "bank_size": n, "t_features": t_feat, "t_coreset": t_core} | |
| def _set_bank(self, bank): | |
| self.bank = bank.float() | |
| self.bank_sq = (self.bank * self.bank).sum(1) | |
| # ------------------------------------------------------------------ predict | |
| def nn_distance(self, f: torch.Tensor, chunk: int = 8192) -> torch.Tensor: | |
| """Euclidean distance of each row of f (M,D) to its nearest bank vector.""" | |
| out = [] | |
| for c in f.split(chunk): | |
| d2 = (c * c).sum(1, keepdim=True) + self.bank_sq[None] - 2.0 * (c @ self.bank.T) | |
| out.append(d2.min(1).values.clamp_min(0).sqrt()) | |
| return torch.cat(out) | |
| def predict(self, x: torch.Tensor): | |
| """Returns (image_scores (B,), anomaly_maps (B,H,W)).""" | |
| f = self.embed(x) | |
| B, P, D = f.shape | |
| s = self.nn_distance(f.reshape(-1, D)).reshape(B, 1, *self.fmap_hw) | |
| image_scores = s.flatten(1).max(1).values | |
| maps = F.interpolate(s, size=x.shape[-2:], mode="bilinear", align_corners=False) | |
| maps = gaussian_blur(maps, self.blur_sigma)[:, 0] | |
| return image_scores, maps | |
| # ------------------------------------------------------------------ io | |
| def save(self, path: str | Path, extra: dict | None = None): | |
| from safetensors.torch import save_file | |
| path = Path(path) | |
| path.mkdir(parents=True, exist_ok=True) | |
| save_file({"memory_bank": self.bank.half().contiguous()}, str(path / "memory_bank.safetensors")) | |
| cfg = { | |
| "backbone": self.backbone_name, | |
| "target_dim": self.target_dim, | |
| "coreset_ratio": self.coreset_ratio, | |
| "proj_dim": self.proj_dim, | |
| "image_size": self.image_size, | |
| "blur_sigma": self.blur_sigma, | |
| "image_threshold": self.image_threshold, | |
| "pixel_threshold": self.pixel_threshold, | |
| **(extra or {}), | |
| } | |
| (path / "config.json").write_text(json.dumps(cfg, indent=2)) | |
| def load(cls, path: str | Path, extractor: FeatureExtractor | None = None) -> "PatchCore": | |
| from safetensors.torch import load_file | |
| path = Path(path) | |
| cfg = json.loads((path / "config.json").read_text()) | |
| m = cls(cfg["backbone"], cfg["target_dim"], cfg["coreset_ratio"], cfg["proj_dim"], | |
| cfg["image_size"], cfg["blur_sigma"], extractor) | |
| m._set_bank(load_file(str(path / "memory_bank.safetensors"))["memory_bank"].float()) | |
| m.image_threshold = cfg["image_threshold"] | |
| m.pixel_threshold = cfg["pixel_threshold"] | |
| m.config = cfg | |
| return m | |