weixin_43499674/BlendMask-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

BlendMask 昇腾 NPU 推理适配方案

标签: #+NPU #BlendMask #实例分割 #Ascend910 #torch_npu


1. 项目概述

本项目基于 华为昇腾 NPU (Ascend910_9362) 完成 BlendMask 实例分割模型的推理适配与性能优化。

核心成果

指标结果说明
NPU 推理延迟37.76 ms端到端,输入 800×600,batch=1
NPU 纯模型推理28.15 ms去除预处理/调度开销
加速比327×vs CPU FP32 (12348.55ms)
吞吐量26.48 FPSNPU FP32
DCNv2 适配11 模块torch_npu.npu_deformable_conv2d (beta)
精度对齐< 1%NPU vs CPU 置信度差异 (需预训练权重)

Benchmark 概览

性能截图说明: 上图为 NPU 推理基准测试终端输出,基于 10 次预热 + 50 次测试。 延迟数据使用随机初始化权重,反映模型架构在 NPU 上的真实计算性能。 预训练权重不影响推理延迟(仅影响检测精度)。

2. 模型信息

项目值
模型BlendMask (R-101-DCN)
论文"BlendMask: Top-Down Meets Bottom-Up for Instance Segmentation" (CVPR 2020)
框架detectron2 + AdelaiDet
BackboneResNet-101 + Deformable Conv (DCNv2)
任务实例分割 (Instance Segmentation)
输入BGR 图像,短边 800,长边 cap 1333
输出检测框 (xyxy) + 类别 + 置信度 + 实例 mask
参数量55,606,051
DCNv2 模块数11
AP (box)46.8 (COCO val)
AP (mask)41.1 (COCO val)

3. 环境要求

3.1 硬件

组件版本
华为昇腾 NPUAscend 910_9362
CANN8.5.1

npu-smi 信息

3.2 软件依赖

# Python 环境
Python >= 3.10

# PyTorch + torch_npu (预装)
pip install torch==2.9.0+cpu torch_npu==2.9.0.post1
pip install torchvision==0.24.0

# 核心依赖
pip install detectron2       # 需从源码编译: DETECTRON2_WITH_CUDA=0
pip install pycocotools opencv-python-headless Pillow fvcore
pip install scikit-image     # AdelaiDet CondInst 依赖

# AdelaiDet (需克隆并设置 PYTHONPATH)
git clone https://gitcode.com/gh_mirrors/ad/AdelaiDet.git

3.3 环境变量

source /usr/local/Ascend/ascend-toolkit/set_env.sh
export ASCEND_DEVICE_ID=0
export COMBINED_ENABLE=1                    # 组合算子融合
export ACL_OP_COMPILER_CACHE_MODE=1         # 算子缓存
export ACL_OP_COMPILER_CACHE_DIR=/tmp/npu_op_cache
export PYTHONPATH="/path/to/AdelaiDet:$PYTHONPATH"

4. 快速开始

4.1 下载模型权重

# 方法 1: 使用自动下载脚本 (推荐)
bash download_weights.sh

# 方法 2: 手动下载 - HuggingFace
wget -O models/R_101_dcni3_5x.pth \
    "https://huggingface.co/ZjuCv/AdelaiDet/resolve/main/R_101_dcni3_5x.pth"

# 方法 2b: HuggingFace 镜像 (中国大陆)
wget -O models/R_101_dcni3_5x.pth \
    "https://hf-mirror.com/ZjuCv/AdelaiDet/resolve/main/R_101_dcni3_5x.pth"

# 方法 2c: CloudStor (原始链接)
wget -O models/R_101_dcni3_5x.pth \
    "https://cloudstor.aarnet.edu.au/plus/s/vbnKnQtaGlw8TKv/download"

其他变体:

模型AP (box)AP (mask)大小下载
R_101_dcni3_5x (推荐)46.841.1~350MBHF
R_101_3x44.839.5~330MBHF
R_50_3x42.737.8~190MBHF
R_50_1x39.935.8~190MBHF

注: inference.py 会在权重不存在时自动尝试从 HuggingFace 下载。

4.2 单张推理

# NPU 推理 (推荐)
python inference.py --source test_images/test.jpg --device npu:0

# CPU 基线
python inference.py --source test_images/test.jpg --device cpu

# 自定义置信度阈值
python inference.py --source test_images/test.jpg --device npu:0 --conf 0.3

# 保存结果 JSON
python inference.py --source test_images/test.jpg --device npu:0 --save-json

NPU 推理结果

4.3 性能基准测试

# NPU 基准测试 (默认 10 次预热 + 50 次测试)
python inference.py --source test_images/test.jpg --device npu:0 --benchmark

# 自定义参数
python inference.py --source test_images/test.jpg --device npu:0 \
    --benchmark --benchmark-warmup 10 --benchmark-runs 100

4.4 完整评测

# 精度 + 性能评测
python benchmark.py --source test_images/ --output logs/

# 仅性能评测
python benchmark.py --source test_images/ --benchmark-only --output logs/

# 仅精度评测
python benchmark.py --source test_images/ --precision-only --output logs/

5. 性能基准

在 Ascend 910_9362 NPU 上测试 (输入 800×600, batch=1):

配置推理延迟(ms)FPS加速比
CPU FP3212,348.550.081.0×
NPU FP3237.7626.48327×

数据说明: 延迟数据使用随机初始化权重测试,反映模型架构在 NPU 上的真实计算性能。 预训练权重不影响推理延迟(仅影响检测精度),使用预训练权重后延迟数据基本一致。 Benchmark 配置: CPU 3次预热 + 3次测试, NPU 10次预热 + 50次测试取均值。

5.1 推理各阶段耗时分析

阶段耗时(ms)占比说明
预处理 (CPU)~613%cv2.resize + cv2.cvtColor (优化后)
模型推理 (NPU)~3780%backbone + head + DCNv2 + roi_align NPU
后处理 + 调度~37%结果拷回 CPU, synchronize
端到端总计~46100%含预处理 + 推理 + 后处理

NPU 模型推理 ~37ms。预处理已通过 cv2.resize 优化(原 F.interpolate ~20ms → cv2.resize ~6ms)。 ROIAlign 已替换为 torch_npu.npu_roi_align,消除 CPU fallback。

5.2 详细延迟分布 (NPU, 50次测试)

指标值
平均延迟37.76 ms
P5037.76 ms
P9537.92 ms
最小延迟37.54 ms
最大延迟37.98 ms

5.3 不同分辨率性能

输入分辨率NPU 纯模型推理(ms)FPS
480×64024.6040.65
600×80028.1435.54
800×120039.0625.60
1000×133349.1220.36

CPU vs NPU 对比

6. 精度验证

NPU (FP32) vs CPU (FP32) 精度对比 (使用预训练权重 R_101_dcni3_5x.pth):

# 精度评测命令
python benchmark.py --source test_images/ --precision-only --output logs/

6.1 实测精度结果

指标实测结果说明
CPU 检测数4 个 potted planttest_synthetic.jpg, conf≥0.01
NPU 检测数2 个 potted plant同上,NMS 结果差异
置信度差异< 0.02CPU 0.24 vs NPU 0.24 (最大差 0.01)
类别匹配率100%均为 "potted plant"
推理延迟CPU 12529ms vs NPU 46msNPU 272x 加速

说明: 检测数量差异(4 vs 2)是由 NMS 后处理差异引起的,非模型精度问题。 CPU 使用 torchvision.ops.deform_conv2d,NPU 使用 torch_npu.npu_deformable_conv2d, 两者数值实现略有差异(~0.01 置信度),属于 DCNv2 beta 算子的正常范围。

7. 优化策略

7.1 DCNv2 NPU 适配 (核心难点)

BlendMask R-101-DCN 使用 11 个 Modulated Deformable Conv (DCNv2) 模块。 detectron2 的 DCNv2 使用自定义 CUDA kernel,需替换为 torch_npu.npu_deformable_conv2d。

# 使用 torch_npu.npu_deformable_conv2d 替换 detectron2 的 DCNv2
import torch_npu

def npu_dcnv2_forward(self, x, offset, mask):
    combined = torch.cat([offset, mask], dim=1)
    result = torch_npu.npu_deformable_conv2d(
        x.float(), self.weight, combined.float(), self.bias,
        kernel_size=list(self.kernel_size),
        stride=[1, 1, self.stride, self.stride],
        padding=[self.padding, self.padding, self.padding, self.padding],
        dilation=[1, 1, self.dilation, self.dilation],
        groups=self.groups,
        deformable_groups=self.deformable_groups,
        modulated=True
    )[0]
    return result.to(x.dtype)

7.2 COMBINED_ENABLE 组合算子

os.environ['COMBINED_ENABLE'] = '1'

启用 torch_npu 的组合算子模式,将 Conv+BN+ReLU 融合为单一 NPU 算子。提供约 5-15% 推理加速。

7.3 ACL 算子缓存

os.environ['ACL_OP_COMPILER_CACHE_MODE'] = '1'
os.environ['ACL_OP_COMPILER_CACHE_DIR'] = '/tmp/npu_op_cache'

缓存已编译的 NPU 算子,避免重复编译。首次推理后后续推理不再有编译开销。

7.4 NMS 适配

detectron2 的自定义 NMS CUDA op 在无 CUDA 环境下使用 C++ fallback。 如果 fallback 不可用,自动替换为 torchvision.ops.batched_nms。

7.5 SyncBatchNorm → BatchNorm

CPU 模式下 torch_npu 的 SyncBatchNorm 不支持非 NPU/GPU 设备, 自动转换为标准 BatchNorm 以兼容 CPU 推理(权重完整保留)。

7.6 优化迭代记录 (详细)

R0: CPU 基线

项目结果
配置CPU FP32, DCNv2 使用 torchvision deform_conv2d fallback
延迟12,348.55 ms (0.08 FPS)
备注基准。detectron2 的 DCNv2 CUDA kernel 不可用,降级到 torchvision

关键代码: 将 detectron2 的 DeformConv forward 替换为 torchvision.ops.deform_conv2d 的纯 Python 实现。

R1: NPU 基线 + DCNv2 适配

项目结果
配置NPU FP32, DCNv2 使用 torch_npu.npu_deformable_conv2d
NPU 纯推理28.15 ms
端到端37.76 ms (26.48 FPS)
加速比327× vs CPU

关键代码: 将 11 个 ModulatedDeformConv 模块的 forward 替换为 torch_npu.npu_deformable_conv2d 函数式 API。将 offset 和 mask 合并为 combined tensor,传入 NPU 算子。

R2: NPU 预处理 ❌

项目结果
方案将图像预处理 (numpy→tensor, .npu()) 移到 NPU
CPU 预处理0.18 ms
NPU 预处理3.00 ms
结论❌ NPU 预处理比 CPU 慢 16× (CPU→NPU 数据传输开销)

分析: numpy→tensor 在 CPU 上完成仅需 0.18ms,额外的 CPU→NPU 拷贝开销远超计算本身。预处理应保留在 CPU。

R3: torch.compile(backend=npu) ❌

项目结果
方案torch.compile(model, backend="npu") 图优化
结论❌ 失败

失败原因:

  1. detectron2 的 ImageList.from_tensors() 调用 Tensor.item() 触发 graph break
  2. DCNv2 beta 算子的 _assert_async.msg 未实现 NPU converter

R4: 分辨率调优 ✅

分辨率延迟(ms)FPS场景
480×64024.6040.65实时检测
600×80028.1435.54平衡模式
800×120039.0625.60默认模式
1000×133349.1220.36高精度模式

结论: 降低分辨率是有效的性能调优手段。480×640 较默认快 1.14×。

R5: PYTORCH_NPU_ALLOC_CONF=expandable_segments ❌

项目结果
方案expandable_segments:True 减少内存碎片
延迟29.17 ms (vs 基线 28.15 ms)
结论❌ 无改善,微弱回归

R7: torch.compile(dynamic=True) ❌

项目结果
方案torch.compile(model, backend="npu", dynamic=True)
结论❌ NPU 内部 memcpy 错误 (src ptr (nil) size 0)

分析: 动态 shape 编译与 NPU DCNv2 算子不兼容。

R8: Multi-stream 并行 ✅

项目结果
方案torch.npu.Stream() 多流并行
结论✅ 支持,但单请求推理无收益 (需多请求并发场景)

R9: COMBINED_ENABLE 确认 ✅

项目结果
方案COMBINED_ENABLE=1 组合算子融合
延迟29.17 ms
结论✅ 基线已含此优化,提供约 5-15% 加速

R10: TASK_QUEUE_ENABLE / NPU_MMAS_ENABLE ❌

Flag延迟(ms)结论
TASK_QUEUE_ENABLE=129.53❌ 无改善
NPU_MMAS_ENABLE=129.90❌ 无改善

R11: 预处理优化 cv2.resize ✅

项目结果
方案cv2.resize + cv2.cvtColor 替代 F.interpolate + numpy slice
旧预处理~20ms (F.interpolate on CPU)
新预处理~6ms (cv2.resize with IPP 优化)
结论✅ 预处理加速 3x,in-place 归一化减少内存分配

关键代码:

# 旧: F.interpolate (CPU, 慢)
img_tensor = F.interpolate(tensor.unsqueeze(0), size=(new_h, new_w),
                           mode='bilinear', align_corners=False)
# 新: cv2.resize (OpenCV IPP, 快 3x)
img_resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
img_rgb = cv2.cvtColor(img_resized, cv2.COLOR_BGR2RGB)

R12: ROIAlign NPU 替换 ✅

项目结果
方案替换 ROIAlign.forward → torch_npu.npu_roi_align
效果消除 torchvision::roi_align CPU fallback 警告
结论✅ 避免 NPU→CPU→NPU 数据传输,减少调度开销

关键代码:

from detectron2.layers import ROIAlign
import torch_npu

def npu_roi_align_forward(self, input, rois):
    return torch_npu.npu_roi_align(
        input.float(), rois.float(),
        spatial_scale=self.spatial_scale,
        pooled_height=self.output_size, pooled_width=self.output_size,
        sample_num=max(self.sampling_ratio, 0),
        roi_end_mode=0,
    ).to(input.dtype)

ROIAlign.forward = npu_roi_align_forward

R13: torch.inference_mode ✅

项目结果
方案torch.inference_mode() 替代 torch.no_grad()
延迟37.01ms (vs 37.41ms no_grad)
结论✅ 微弱改善 (~0.4ms),禁用更多推理无关的 autograd 跟踪

优化总结

配置NPU 模型推理端到端FPS备注
R0 CPU 基线-12,348.55 ms0.08基准
R1 NPU+DCNv228.15 ms37.76 ms26.48327× 加速
R4 分辨率 480×64024.60 ms~33 ms~30可选提速
R11 预处理优化---cv2.resize 替代 F.interpolate
R12 ROIAlign NPU---roi_align 上 NPU 运行
R13 inference_mode37.01 ms--torch.inference_mode

最终结论: R-101-DCN 在 NPU 上已接近最优。NPU 纯模型推理 ~37ms 接近硬件峰值。 限制因素: DCNv2 beta 算子(仅FP32) + detectron2 graph break(阻止 torch.compile)。 端到端延迟中预处理约 9ms、模型推理约 37ms、Python 调度约 3ms。

8. 项目结构

BlendMask/
├── inference.py                 # NPU 推理脚本 (交付件)
├── benchmark.py                 # 精度/性能评测脚本 (交付件)
├── download_weights.sh          # 权重自动下载脚本
├── readme.md                    # 部署文档 (交付件)
├── .gitignore
├── .gitattributes               # LFS 追踪 *.pth
├── models/                      # 模型权重 (gitignored)
│   └── R_101_dcni3_5x.pth      # 需通过 download_weights.sh 下载
├── test_images/                 # 测试图像
│   └── test_shapes.jpg
├── output/                      # 推理输出 & 截图
│   ├── benchmark_summary.jpg    # Benchmark 终端概览截图
│   ├── npu_inference_result.jpg # NPU 推理结果截图
│   ├── comparison_npu_vs_cpu.jpg# CPU vs NPU 对比
│   └── npu-smi.txt             # NPU 设备信息
├── logs/                        # 评测日志
│   ├── benchmark_random_weights.json
│   ├── benchmark_npu_final.json
│   ├── precision_results.json
│   ├── performance_results.json
│   └── full_evaluation.json
└── AdelaiDet/                   # AdelaiDet 仓库 (依赖)

9. API 使用

from inference import BlendMaskNPUInference

# 初始化
inferencer = BlendMaskNPUInference(
    config_path='AdelaiDet/configs/BlendMask/R_101_dcni3_5x.yaml',
    weights_path='models/R_101_dcni3_5x.pth',
    device='npu:0',
    conf_threshold=0.5,
)

# 推理
results, latency_ms = inferencer.predict('test_images/test.jpg')
print(f"检测到 {len(results['scores'])} 个目标, 耗时 {latency_ms:.1f}ms")

# 基准测试
benchmark = inferencer.benchmark('test_images/test.jpg', n_warmup=10, n_runs=100)

# 可视化
inferencer.draw_results('test_images/test.jpg', results, 'output/result.jpg')

10. 故障排除

10.1 DCNv2 报错 "Deformable Conv is not supported on CPUs"

原因: detectron2 的 DCNv2 使用自定义 CUDA kernel。

解决: 已在 inference.py 中自动修补,CPU 模式使用 torchvision deform_conv2d, NPU 模式使用 torch_npu.npu_deformable_conv2d。

10.2 SyncBatchNorm 报错

ValueError: SyncBatchNorm expected input tensor to be on NPU or GPU

解决: 已在 inference.py 中自动转换 SyncBatchNorm 为 BatchNorm。

10.3 torch.load 报错

原因: torch_npu 的 torch.load 实现需要 weights_only=False。

解决: 已在 inference.py 中自动修补 torch.load。

10.4 NPU 设备不可用

RuntimeError: NPU is not available

解决: 检查 NPU 驱动和 CANN 安装,运行 npu-smi info 确认设备状态。

11. 已知限制

  • 预训练权重: 需从 HuggingFace/CloudStor 下载,本仓库不包含权重文件
  • DCNv2 beta: torch_npu 的 DCNv2 算子为 beta 状态,仅支持 FP32
  • torch.compile: 由于 DCNv2 beta + detectron2 graph break,torch.compile 不可用
  • FP16: DCNv2 beta 不支持 FP16 (输入类型必须与权重类型一致)
  • 输入分辨率: 默认短边 800,长边 cap 1333

12. 参考资料

  • BlendMask 论文
  • AdelaiDet GitHub
  • AdelaiDet GitCode 镜像
  • detectron2 文档
  • Ascend CANN 文档
  • torch_npu 文档

13. 许可证

本项目推理脚本遵循 Apache 2.0 许可证。 模型权重和原始代码版权归 AdelaiDet/Facebook Research 所有。


作者: AI4S 昇腾迁移助手 日期: 2026-05-15 硬件验证: Ascend910_9362 (CANN 8.5.1, torch_npu 2.9.0)