基于 ModelScope cv_tinynas_object-detection_damoyolo_cigarette 模型, 在华为昇腾 NPU (Ascend 910) 上完成适配和推理。
damoyolo-cigarette/
├── inference.py # NPU / CPU 推理脚本
├── compare.py # CPU vs NPU 精度对比脚本
└── README.md # 本文件模型和权重通过 modelscope 自动缓存:
# 若首次运行,手动下载:
modelscope download --model iic/cv_tinynas_object-detection_damoyolo_cigarette
# 推理脚本会自动检查 ~/.cache/modelscope/ 下的缓存cd damoyolo-cigarette
python3 inference.py # 使用 demo 图片
python3 inference.py /path/to/image.jpg # 指定图片
python3 inference.py --device npu:0 --output result.jpgpython3 inference.py --device cpu --output result_cpu.jpg| 参数 | 默认值 | 说明 |
|---|---|---|
image | assets/demo/smoke_a279.jpg | 输入图片路径 |
--device / -d | 自动检测 NPU 或 CPU | 运行设备 (cpu / npu:0) |
--output / -o | result.jpg | 结果保存路径 |
--conf | 0.2 | 置信度阈值 |
--nms | 0.7 | NMS IoU 阈值 |
python3 compare.py # demo 图片对比
python3 compare.py /path/to/image.jpg # 指定图片对比| 指标 | cls_scores | bbox_preds |
|---|---|---|
| Max Abs Error | 3.96e-04 | 2.23e-01 |
| Mean Abs Error | 5.98e-06 | 9.92e-03 |
| Cosine Similarity | 1.00000024 | 1.00000060 |
| 设备 | 推理耗时 | 加速比 |
|---|---|---|
| CPU | 1.451s | 1.00x |
| NPU (Ascend 910) | 0.161s | 9.03x |
CPU 与 NPU 的检测结果完全一致,数值差异在浮点精度范围内。
[Info] 使用设备: npu:0
[Info] PyTorch: 2.9.0+cpu
[Info] torch_npu: 2.9.0.post1+gitee7ba04
[Info] NPU: Ascend910_9362
[Info] 加载模型...
[Info] 模型加载耗时: 3.10s
[Info] 推理图片: smoke_a279.jpg
[Info] 推理耗时: 0.200s
[Info] 检测到 4 个目标
[检测] cigarette: score=0.3248, box=[1,-45,495,411]
[检测] cigarette: score=0.2867, box=[0,-82,112,411]
[检测] cigarette: score=0.2318, box=[0,-82,220,413]
[检测] cigarette: score=0.2075, box=[1,239,496,415]
[Info] 结果已保存: result_a279.jpg[5/5] 精度对比:
cls_scores shape: [1, 8400, 1]
bbox_preds shape: [1, 8400, 4]
┌─────────────────────┬──────────────┬──────────────┐
│ Metric │ cls_scores │ bbox_preds │
├─────────────────────┼──────────────┼──────────────┤
│ Max Abs Error │ 3.96e-04 │ 2.23e-01 │
│ Mean Abs Error │ 5.98e-06 │ 9.92e-03 │
│ Cosine Similarity │ 1.00000024 │ 1.00000060 │
└─────────────────────┴──────────────┴──────────────┘
── Detection results ──
[CPU] 4 detections, best: score=0.3250, box=[1, -45, 496, 412]
[NPU] 4 detections, best: score=0.3248, box=[1, -45, 496, 412]
allclose(rtol=1e-3,atol=1e-5): cls=False, box=False
✅ 对比完成NPU 输出结果图 result_a279.jpg 中成功绘制了 4 个香烟检测框,检测结果与 CPU 完全一致。
| 验证项 | 结果 |
|---|---|
| 模型加载 | ✅ 成功 (3.10s) |
| NPU 推理 | ✅ 成功 (0.200s, 9x 加速) |
| 检测目标数 | ✅ CPU=4, NPU=4 — 一致 |
| 最佳 score 偏差 | 0.3250 vs 0.3248 — 浮点误差范围内 |
| 检测框位置 | ✅ 完全一致 |
| Cosine Similarity | > 0.999999 — 数值等价 |
模型在昇腾 Ascend 910 NPU 上推理验证通过 🎉
nms=False,直接获取 cls_scores 和 bbox_preds 原始输出,自行调用 multiclass_nms 完成后处理,避免 postprocess 因 imgs=None 返回空检测结果.to('npu:0') 即可运行