可用于在华为 Ascend NPU 上实现工业异常检测,通过自动选择 NPU/CUDA/CPU 设备,支持端到端训练与推理,相比 CPU 推理速度提升约 6.6 倍且保持精度一致,适配 torch_npu 并提供部署指南。【此简介由AI生成】
| Files | Last commit | Last update |
|---|---|---|
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago | ||
| 5 months ago |
PatchCore for Ascend NPU
This repository contains the Ascend NPU-adapted implementation of PatchCore (Roth et al., 2021) for industrial anomaly detection. The original code was hard-coded for CUDA GPUs; we have refactored the device abstraction layer so that PatchCore now automatically selects NPU > CUDA > CPU, enabling out-of-the-box execution on Huawei Ascend NPUs (e.g., Atlas 800 A2/A3) via torch_npu.
1. What's New (Ascend Adaptation)
| Capability | Before (Original) | After (This Fork) |
|---|---|---|
| Device Support | CUDA only (torch.cuda.*) |
Auto-detects NPU / CUDA / CPU |
| FAISS Backend | Requires faiss-gpu (CUDA) |
Forces faiss-cpu with safe fallback |
| Running on Ascend | Crashes with AttributeError on torch.cuda |
Full train + infer pipeline works |
| Backbone Loading | pretrained=True deprecation warnings |
Compatible with weights API |
Modified Files
src/patchcore/utils.py— genericempty_cache(),get_device_context(), NPU-aware seedingsrc/patchcore/common.py— FAISS GPU APIs removed, forced CPU fallback for Ascendsrc/patchcore/backbones.py— modernweightsAPI compatibilitybin/run_patchcore.py— replaced alltorch.cuda.*calls with generic wrappersbin/load_and_evaluate_patchcore.py— same as above
New Files
inference.py— standalone inference script with auto device selectionevaluation/evaluate_ascend.py— accuracy & latency benchmark scriptrun_patchcore_ascend.sh— one-click train / eval scriptASCEND_DEPLOY.md— detailed deployment guide in Chinese
2. Performance: Before vs After
2.1 Functional Comparison
| Metric | Original Code on Ascend | Adapted Code on Ascend NPU |
|---|---|---|
| Can run training? | No (crashes on torch.cuda.empty_cache) |
Yes |
| Can run inference? | No (crashes on torch.cuda.device) |
Yes |
| Can load saved model? | No (FAISS GPU API missing) | Yes (CPU FAISS fallback) |
| Device used | — | npu:0 |
2.2 Accuracy & Speed Comparison (CPU vs Ascend NPU)
Benchmarked on Atlas 800 A2 (CANN 8.5.1, torch_npu 2.9.0) with MVTec bottle test set (10 images).
| Device | Instance AUROC | Full Pixel AUROC | Anomaly Pixel AUROC | Inference Time | Throughput |
|---|---|---|---|---|---|
| CPU | 1.0000 | 0.9957 | 0.9927 | 5.739 s | 1.74 img/s |
| Ascend NPU | 1.0000 | 0.9957 | 0.9927 | 0.874 s | 11.44 img/s |
- Accuracy is identical between CPU and NPU (no precision loss).
- NPU is ~6.6x faster than CPU for inference throughput.
Raw benchmark JSON:
evaluation/eval_results.json
3. Environment
| Component | Version |
|---|---|
| Python | 3.11+ |
| PyTorch | 2.9.0+cpu |
| torch_npu | 2.9.0.post1+ |
| CANN | 8.5.1 |
| faiss | faiss-cpu (GPU not available on Ascend) |
4. Installation
# 1. Clone this repo (or download zip)
git clone https://gitcode.com/gcw_i0yFZkCV/My_PatchCore.git
cd My_PatchCore
# 2. Install dependencies
pip install click scipy scikit-image scikit-learn tqdm faiss-cpu pretrainedmodels timm matplotlib
# 3. Verify NPU is visible
python -c "import torch, torch_npu; print(torch.npu.is_available())"
# Expected: True
5. Quick Start
5.1 Train + Evaluate (end-to-end)
export PYTHONPATH=src
python bin/run_patchcore.py \
--gpu 0 --seed 0 \
--save_patchcore_model \
results \
patch_core \
-b wideresnet50 \
-le layer2 -le layer3 \
--pretrain_embed_dimension 1024 \
--target_embed_dimension 1024 \
--anomaly_scorer_num_nn 1 \
--patchsize 3 \
sampler \
-p 0.1 approx_greedy_coreset \
dataset \
--resize 256 --imagesize 224 \
-d bottle mvtec /path/to/mvtec
--gpu 0is automatically mapped tonpu:0on Ascend. No extra flags needed.
5.2 Load Pretrained Model & Infer
python bin/load_and_evaluate_patchcore.py \
--gpu 0 --seed 0 \
evaluated_results \
patch_core_loader \
-p /path/to/saved_model/mvtec_bottle \
dataset \
--resize 256 --imagesize 224 \
-d bottle mvtec /path/to/mvtec
5.3 Standalone Inference Script
python inference.py \
--model_path /path/to/saved_model/mvtec_bottle \
--data_path /path/to/mvtec \
--category bottle \
--output_path ./inference_results \
--device auto \
--save_images
5.4 Benchmark (CPU vs NPU)
python evaluation/evaluate_ascend.py \
--data_path /path/to/mvtec \
--category bottle \
--model_path /path/to/saved_model/mvtec_bottle \
--output evaluation/eval_results.json
5.5 One-Click Script
bash run_patchcore_ascend.sh train /path/to/mvtec
bash run_patchcore_ascend.sh eval /path/to/mvtec /path/to/saved_model
6. Dataset Setup (MVTec AD)
Download MVTec AD from mvtec.com and arrange as:
mvtec/
|-- bottle/
| |-- ground_truth/
| |-- test/
| | |-- good/
| | |-- broken_large/
| |-- train/
| | |-- good/
|-- cable/
|-- ...
7. Known Issues & Notes
-
Git LFS pointers: The pretrained models shipped in the original
models/folder are Git LFS pointers, not real binaries. If you see_pickle.UnpicklingError: invalid load key, 'v', either:- Run
git lfs pullto fetch real weights, or - Re-train on your NPU with
--save_patchcore_model.
- Run
-
FAISS on GPU: Ascend NPU does not support
faiss-gpu. The code automatically falls back tofaiss-cpuand prints a warning if--faiss_on_gpuis passed. -
Torchvision deprecation: We have patched
backbones.pyto use the modernweightsAPI, eliminatingpretrained is deprecatedwarnings.
8. Citation
Original Paper:
@misc{roth2021total,
title={Towards Total Recall in Industrial Anomaly Detection},
author={Karsten Roth and Latha Pemula and Joaquin Zepeda and Bernhard Schölkopf and Thomas Brox and Peter Gehler},
year={2021},
eprint={2106.08265},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
9. License
Apache-2.0 (same as the original repository).
10. Tags
#NPU #Ascend #PatchCore #AnomalyDetection #torch_npu