BiRefNet(Bilateral Reference Network,双向参考网络)在华为 Ascend 910 NPU 上的端到端推理适配。
本项目使用与 GPU 完全一致的 PyTorch 模型与权重,仅通过 torch_npu 完成设备迁移,
不修改模型结构、不改写权重,输入 1024x1024 图像输出单通道二分分割 mask。
ZhengPeng7/BiRefNet(BiRefNet-L,Swin-Large 22k 背骨 + 双向参考 Transformer 解码器)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,仅影响该子模块性能,不影响精度)。| 组件 | 版本 |
|---|---|
| 硬件 | Ascend 910(2 卡,本实验用 npu:0) |
| OS / CPU | aarch64 Linux |
| Python | 3.11.14 |
| CANN | 8.5.1 |
| torch | 2.9.0+cpu |
| torch_npu | 2.9.0.post1 |
| transformers | 4.57.6 |
pip install -r requirements.txt权重(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/# NPU 推理(Ascend 910)
python3 inference.py --device npu
# CPU 推理(同输入同 seed 的对照)
python3 inference.py --device cpu
# 精度与性能对比(6 项指标,结果写入 assets/compare_result.txt)
python3 compare.pyNPU 推理输出(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| 指标 | 定义 | 实测值 | 验收线 | 结果 |
|---|---|---|---|---|
| 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.5 | mask 二值一致率(阈值 0.5) | 0.999999 | > 99% | ✅ PASS |
| iou@0.5 | 二值 mask IoU(阈值 0.5) | 0.999998 | > 0.90 | ✅ PASS |
| time_ratio | CPU 耗时 / NPU 耗时 | 4.992751 | > 1.0 | ✅ PASS |
torch.npu.max_memory_allocated)torch.cuda 调用;设备通过 torch_npu.npu.set_device(0) 指定torchvision::deform_conv2d 无 NPU 算子,torch_npu 自动 CPU fallback(不影响精度)