A from-scratch, minimal reimplementation of PatchCore (Towards Total
Recall in Industrial Anomaly Detection, Roth et al., CVPR 2022) written so
every distance-based step runs as pure matrix multiplication on Ascend NPUs
via torch_npu — no Faiss, no CUDA.
The four pipeline steps are kept as independent, importable modules so each one can be studied against the original paper and optimized separately.
| Step | What it does | Where |
|---|---|---|
| 1 | Feature extraction with a frozen pretrained WideResNet-50 (layer2+layer3) | feature_extractor.py |
| 2 | 3×3 average pooling — local neighbourhood aggregation | inside FeatureExtractor.forward |
| 3 | Coreset subsampling (Random / Greedy / Approximate Greedy) | sampler.py |
| 4 | k-NN anomaly scoring + heat-map resolution | nn_search.py + anomaly_score.py |
PatchCore never learns "what a defect looks like". It memorizes what "perfectly normal" looks like, and at inference time anything whose features don't match the memory bank is anomalous:
anomaly_score(patch) = min over memory bank of ||patch_feature - bank_feature||The k-NN distance is computed with the identity
||q - x||² = ||q||² + ||x||² - 2 · q·xᵀi.e. one matmul (torch.mm), which is exactly what the Ascend NPU
executes efficiently. This is the same decomposition that the BaihuNN
module in quzhi_1981/ascend-patchcore uses.
# 1. Synthetic demo — no data, no network, verifies the plumbing end to end:
python main.py --demo
# 2. On real images (needs a directory of "normal" training images):
python main.py --train-dir /path/to/normal/ --test-image /path/to/test.png
# 3. Force Ascend NPU:
python main.py --demo --npuAs a library:
import torch
from patchcore_npu import (
FeatureExtractor, ApproximateGreedyCoresetSampler, BaihuNN,
NearestNeighbourScorer,
)
device = torch.device("npu:0") # or "cpu"
extractor = FeatureExtractor(device=device)
sampler = ApproximateGreedyCoresetSampler(percentage=0.1, device=device)
nn = BaihuNN(on_npu=device.type == "npu")
scorer = NearestNeighbourScorer(n_nearest_neighbours=1, nn_method=nn)
train_feats = [extractor(img.to(device)) for img in train_images]
coreset = sampler.run(torch.cat(train_feats))
scorer.fit(coreset)
scores, _, _ = scorer.predict(extractor(test_img.to(device)))The sampler.py and nn_search.py modules deliberately mirror the upstream
amazon-science/patchcore-inspection interfaces:
BaihuNN ↔ FaissNN — same fit() / run(k, query, index=None) contract,
returning (distances, indices). You can drop it in wherever a FaissNN
was used.GreedyCoresetSampler / ApproximateGreedyCoresetSampler / RandomSampler
↔ the same-named classes upstream.For a MVTec-AD run that matches the paper, use wideresnet50_2 (torchvision)
and a coreset percentage of 0.1 (10%), which is what the reference
configuration uses.
本项目的诞生与演进,离不开开源社区的智慧结晶与昇腾生态开发者的无私分享。我们在此向以下项目与作者致以最诚挚的感谢:
原始论文与官方实现: 感谢 Karsten Roth 等人提出的 PatchCore 算法 (CVPR 2022) 及 Amazon Science 提供的官方开源实现 (amazon-science/patchcore-inspection),为本项目奠定了坚实的理论与代码基础。
昇腾 NPU 算子重构启发:
感谢 quzhi_1981/ascend-patchcore 项目。其首创的 BaihuNN 模块,通过数学公式将 KNN 搜索转化为纯 NPU 矩阵乘法 (torch.mm),彻底消灭了 PCIe 数据搬运瓶颈。这一"算子重构"思想为本项目实现全链路 NPU 闭环提供了核心灵感。
端到端 (E2E) 极限工程优化启发:
感谢 gcw_C8PI9e90/Patchcore 项目。该项目在"无 Warmup 冷启动"和"端到端耗时压榨"上做到了极致。其关于特征显存常驻缓存、以及深度利用 CANN 8.5+ 环境变量(如 ACL_OP_COMPILER_CACHE_MODE)进行算子融合的工程实践,为本项目的性能调优提供了标准范式。
严谨的精度对齐基线启发:
感谢 weixin_62994174/PatchCore 项目。其提供的详尽的 MVTec-AD 15 类精度对比表与双后端(NPU/CPU)验证方法,为本项目确立"精度误差 < 1%"的验收基线提供了重要的参考标尺。
同时,感谢昇腾 AI 开发者社区及 ModelAgent 团队在环境配置与工具链上提供的支持。