My_PatchCore:基于 Ascend NPU 的工业异常检测项目

可用于在华为 Ascend NPU 上实现工业异常检测,通过自动选择 NPU/CUDA/CPU 设备,支持端到端训练与推理,相比 CPU 推理速度提升约 6.6 倍且保持精度一致,适配 torch_npu 并提供部署指南。【此简介由AI生成】

Branch1Tags0
FilesLast commitLast 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

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 — generic empty_cache(), get_device_context(), NPU-aware seeding
  • src/patchcore/common.py — FAISS GPU APIs removed, forced CPU fallback for Ascend
  • src/patchcore/backbones.py — modern weights API compatibility
  • bin/run_patchcore.py — replaced all torch.cuda.* calls with generic wrappers
  • bin/load_and_evaluate_patchcore.py — same as above

New Files

  • inference.py — standalone inference script with auto device selection
  • evaluation/evaluate_ascend.py — accuracy & latency benchmark script
  • run_patchcore_ascend.sh — one-click train / eval script
  • ASCEND_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 0 is automatically mapped to npu:0 on 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

  1. 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 pull to fetch real weights, or
    • Re-train on your NPU with --save_patchcore_model.
  2. FAISS on GPU: Ascend NPU does not support faiss-gpu. The code automatically falls back to faiss-cpu and prints a warning if --faiss_on_gpu is passed.

  3. Torchvision deprecation: We have patched backbones.py to use the modern weights API, eliminating pretrained is deprecated warnings.


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

Introduction

可用于在华为 Ascend NPU 上实现工业异常检测,通过自动选择 NPU/CUDA/CPU 设备,支持端到端训练与推理,相比 CPU 推理速度提升约 6.6 倍且保持精度一致,适配 torch_npu 并提供部署指南。【此简介由AI生成】

Customize your domain