File size: 8,566 Bytes
142281f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | """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)
@torch.inference_mode()
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
@torch.inference_mode()
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
@torch.inference_mode()
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)
@torch.inference_mode()
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))
@classmethod
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
|