KevinLi11/BiRefNet
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

BiRefNet 昇腾 NPU 适配(高分辨率二分图像分割)

BiRefNet(Bilateral Reference Network,双向参考网络)在华为 Ascend 910 NPU 上的端到端推理适配。 本项目使用与 GPU 完全一致的 PyTorch 模型与权重,仅通过 torch_npu 完成设备迁移, 不修改模型结构、不改写权重,输入 1024x1024 图像输出单通道二分分割 mask。

1. 模型简介

  • 模型:ZhengPeng7/BiRefNet(BiRefNet-L,Swin-Large 22k 背骨 + 双向参考 Transformer 解码器)
  • 参数量:约 220.2M(fp32 权重约 444 MB,safetensors)
  • 任务:高分辨率二分图像分割(Dichotomous Image Segmentation)
  • 输入:RGB 图像,推理分辨率 1024x1024(ImageNet 归一化)
  • 输出:单通道分割 mask(sigmoid 后取值 [0,1],阈值 0.5 二值化)
  • 加载方式:transformers.AutoModelForImageSegmentation + trust_remote_code=True (transformers 4.57.6 未内置 birefnet 模块,需使用模型仓库随附的自定义代码 birefnet.py)
  • 解码器注意:ASPPDeformable 中的 torchvision.ops.deform_conv2d 在 NPU 后端无算子, torch_npu 自动回退 CPU 执行(npu_cpu_fallback,仅影响该子模块性能,不影响精度)。

2. 部署步骤

2.1 环境要求(本仓库实测)

组件版本
硬件Ascend 910(2 卡,本实验用 npu:0)
OS / CPUaarch64 Linux
Python3.11.14
CANN8.5.1
torch2.9.0+cpu
torch_npu2.9.0.post1
transformers4.57.6

2.2 安装依赖

pip install -r requirements.txt

2.3 准备权重

权重(model.safetensors + config.json + 自定义代码 birefnet.py / BiRefNet_config.py) 放置在 models/BiRefNet/ 目录(该目录已被 .gitignore 排除,权重不入库):

mkdir -p models/BiRefNet
# 将权重目录中的 model.safetensors、config.json、birefnet.py、BiRefNet_config.py 放入 models/BiRefNet/

3. 推理示例

# NPU 推理(Ascend 910)
python3 inference.py --device npu

# CPU 推理(同输入同 seed 的对照)
python3 inference.py --device cpu

# 精度与性能对比(6 项指标,结果写入 assets/compare_result.txt)
python3 compare.py

NPU 推理输出(npu_output.txt)示例:

BiRefNet inference report (device=npu)
model_path: /data/birefnet/models/BiRefNet
input: synthetic RGB 1024x1024 (seed=42)
dtype: torch.float32
mask_shape: (1024, 1024)
inference_time_s: 11.2011
peak_memory_allocated_bytes: 3381371392
peak_rss_kb: 4006172
mask_min: 0.000000
mask_max: 1.000000
mask_mean: 0.403730
mask_constant: False

4. 实测 6 指标对比表(NPU vs CPU,同一 1024x1024 合成输入,seed=42,fp32)

指标定义实测值验收线结果
cos_sim扁平化 mask 余弦相似度1.000000> 0.95✅ PASS
max_abs逐像素最大绝对差0.001115< 0.05✅ PASS
mean_abs逐像素平均绝对差0.000001< 0.01✅ PASS
bin_acc@0.5mask 二值一致率(阈值 0.5)0.999999> 99%✅ PASS
iou@0.5二值 mask IoU(阈值 0.5)0.999998> 0.90✅ PASS
time_ratioCPU 耗时 / NPU 耗时4.992751> 1.0✅ PASS
  • NPU 单次前向:11.20 s(含首次算子编译);CPU 单次前向:55.92 s
  • NPU 显存峰值:3.38 GB(torch.npu.max_memory_allocated)
  • 总判定:PASS(cos_sim > 0.95 且二值一致率 > 99%)

NPU 适配要点

  • 全程无 torch.cuda 调用;设备通过 torch_npu.npu.set_device(0) 指定
  • 使用 fp32 精度(Ascend 910 自动将 fp64 降级为 fp32),与 CPU 结果逐像素对齐
  • torchvision::deform_conv2d 无 NPU 算子,torch_npu 自动 CPU fallback(不影响精度)
  • 1024x1024 全分辨率推理峰值显存约 3.4 GB,单卡 910 轻松承载