v
v_50/winclip-opt
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

WinCLIP

Unofficial Implementation of CVPR'23 paper "WinCLIP: Zero-/few-shot anomaly classification and segmentation".

🎯 昇腾 NPU 适配版 — 在 Ascend 910B4 上运行,含 2.67x 性能优化。

Setup

依赖安装

pip install -r requirements.txt

NPU 用户: 额外安装 torch_npu(参考 昇腾官方文档)

CUDA 用户: 确保 torch 版本与 CUDA 版本匹配

依赖版本:

包最低版本已验证版本
python>= 3.10.113.10.11
torch>= 2.1.02.10.0
torchvision>= 0.14.00.25.0
torch_npu—2.10.0 (Ascend)
open-clip-torch>= 3.3.03.3.0
scipy>= 1.10.11.17.1
scikit-image>= 0.21.00.25.2
scikit-learn>= 1.3.01.8.0
numpy>= 1.24.32.4.6
tqdm>= 4.64.04.67.3

Device

  • ✅ NVIDIA GeForce RTX 3090 (原始)
  • ✅ Ascend 910B4 (已适配,已验证)

Quick Start (一键复现)

chmod +x run.sh && ./run.sh

脚本会自动:

  1. 安装依赖
  2. 下载预训练权重 (vit_b_16_plus_240-laion400m_e31-8fb26589.pt)
  3. 提示下载 VisA 数据集
  4. 运行 benchmark

Run

命令行方式 (推荐)

# 基准测试 + 精度验证
python tools/benchmark.py --device npu --obj_type candle --shot 2 --mode benchmark

# 仅精度验证
python tools/benchmark.py --device npu --obj_type candle --shot 2 --mode precision

参数说明:

  • --device: 运行设备 (npu 或 cuda)
  • --obj_type: 类别名称 (如 candle, capsules, pcb1 等)
  • --shot: few-shot 样本数 (0 或 2)
  • --mode: 运行模式
    • benchmark: 性能基准测试 + 精度评估
    • precision: 仅精度验证 (run-to-run)
  • --data_dir: 数据集根目录 (默认: ./mvtec_datasets/visa)

原始方式

修改 main.py 中的配置:

dataset_root_dir = "/visa_anomaly_detection"
datasetname = "visa"
shot = 0
OBJECT_TYPE = ["candle"]

然后运行:

python main.py

Dataset

VisA 数据集

  1. 从 Amazon-Science/spot-diff 下载 VisA 数据集
  2. 解压到任意目录(记为 $VISA_ROOT)
  3. 转换为 MVTec AD 格式:
python prepare_visa_data.py --visa_root $VISA_ROOT --output_root ./mvtec_datasets/visa

转换后的目录结构:

mvtec_datasets/visa/
    candle/
        train/good/
        test/good/
        test/anomaly/
        ground_truth/anomaly/
    capsules/
    ...

Performance (Ascend 910B4)

指标优化前优化后提升
平均耗时414.95 ms155.20 ms2.67x 加速
FPS2.41 it/s6.44 it/s+167%
AUROC0.94950.9495✅ 精度不变
AUPR0.95400.9540✅ 精度不变
Max F10.87100.8710✅ 精度不变

优化项

  1. 批量 Gallery 编码: 将 5 次独立前向 (4 gallery + 1 test) 合并为 2 次 (1 batch + 1 test),单次编码 4 张图片
  2. 移除冗余 .double(): NPU 不支持 fp64,消除无用的 fp32→fp64→fp32 转换链
  3. 预转置 window masks: 将 window_mask.T 缓存为预转置 buffer

Citation

This implementation is used to produce the WinCLIP results in our CVPR'24 InCTRL paper. If you find the implementation useful, we would appreciate your acknowledgement via citing the InCTRL paper:

@inproceedings{zhu2024toward,
  title={Toward generalist anomaly detection via in-context residual learning with few-shot sample prompts},
  author={Zhu, Jiawen and Pang, Guansong},
  booktitle={Proceedings of the IEEE/CVF conference on computer vision and pattern recognition},
  pages={17826--17836},
  year={2024}
}