wrhhh/ZhengPeng7-BiRefNet-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

ZhengPeng7/BiRefNet on Ascend NPU

1. 模型简介

  • 模型名称: ZhengPeng7/BiRefNet
  • 权重URL: https://huggingface.co/ZhengPeng7/BiRefNet
  • Revision: e2bf8e4460fc8fa32bba5ea4d94b3233d367b0e4 (main)
  • 类型: 计算机视觉 / Dichotomous Image Segmentation (DIS) / 显著性目标分割
  • 架构: BiRefNet with Swin-V1-L backbone (1536,768,384,192 lateral channels), ASPP deformable attention, BasicDecBlk decoder, 1024 input resolution
  • 权重: 444,473,596 bytes (~424 MB safetensors), single file model.safetensors, dtype float32
  • Pipeline: image-segmentation via AutoModelForImageSegmentation with trust_remote_code=True
  • 许可: mit
  • 论文: https://arxiv.org/pdf/2401.03407 (CAAI AIR 2024)
  • 官方最小示例:
from transformers import AutoModelForImageSegmentation
from PIL import Image
import torch
from torchvision import transforms
birefnet = AutoModelForImageSegmentation.from_pretrained('ZhengPeng7/BiRefNet', trust_remote_code=True)
birefnet.to('cuda'); birefnet.eval()
transform = transforms.Compose([transforms.Resize((1024,1024)), transforms.ToTensor(), transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])])
img = Image.open('image.jpg').convert('RGB')
inp = transform(img).unsqueeze(0).to('cuda')
with torch.no_grad():
    pred = birefnet(inp)[-1].sigmoid().cpu()

本仓为昇腾 910B (Ascend910_9362) 单卡 npu:0 真实适配, 本地权重加载, 不依赖运行时联网下载. 已验证 torch.npu.is_available()==True 且首参 device==npu:0.

2. 验证环境

  • 硬件: Ascend910_9362 (2 chips, 测试使用 npu:0, 64GB HBM/卡)
  • 驱动: npu-smi 25.5.5, CANN 8.5.1
  • 软件: Python 3.11.14, torch 2.9.0+cpu, torch_npu 2.9.0.post1+gitee7ba04, transformers 4.57.6, timm 1.0.28, kornia 0.8.3, torchvision 0.24.0, safetensors 0.7.0, huggingface-hub 0.36.2, pillow 12.2.0, numpy 1.26.4
  • NPU 显存: 空闲 ~65399 MB / 总量 65787 MB, 峰值分配 3242.2 MB (batch 1, 1024x1024, float32)
  • 权重内存: ~0.41 GiB (safetensors) + 激活, 单卡余量充足
  • 复现: np.random.seed(42) torch.manual_seed(42) 固定, dtype float32, eval mode, 同一合成输入张量 CPU 生成后搬运至 NPU 以保证一致性

3. 安装依赖

pip install -r requirements.txt
# 需 CANN 8.5.1 + torch_npu 配套, 已在镜像环境可用

requirements.txt 内容:

torch==2.9.0
torch-npu==2.9.0.post1
torchvision
transformers
timm>=1.0.28
kornia>=0.8.0
numpy<2
opencv-python
pillow
einops
scipy
scikit-image
huggingface-hub>0.25
safetensors

4. NPU 推理

默认即完成真实 NPU 推理 (自动检测 npu:0):

python inference.py
# 可选: 验证模式 (CPU-NPU 对比 + 性能) 与基准模式
python inference.py --mode validate
python inference.py --mode benchmark
python inference.py --device cpu   # CPU 对照
  • 加载: 从本地 HF 缓存 /opt/atomgit/.cache/huggingface/hub/models--ZhengPeng7--BiRefNet/snapshots/e2bf8e... 优先加载, 若不存在则 snapshot_download('ZhengPeng7/BiRefNet') (依赖 HF_ENDPOINT=https://hf-mirror.com)
  • 设备: 显式 model.to('npu:0'), input.to('npu:0'), 校验首参 device/dtype, 前后 torch.npu.synchronize() 计时
  • 输入: 见第5节, 固定合成 1024x1024 RGB
  • 输出: 终端打印 logits/prob 统计、前景像素、耗时、PASS/FAIL, 并保存 mask.png (1024x1024 灰度)
  • 限制: torchvision::deform_conv2d 在 NPU 上不支持, 会回退至 CPU (日志可见 npu_cpu_fallback), 其余算子在 NPU 执行

5. 真实推理结果

  • 输入: 合成确定性图像 seed=42 1024x1024
    • 梯度背景 + 中心半径200圆形模拟前景, PIL Image.fromarray, Resize 1024, ToTensor, Normalize(mean [0.485,0.456,0.406] std [0.229,0.224,0.225])
    • 张量形状 (1,3,1024,1024) float32, mean -0.2295 std 1.1933, 原图尺寸 1024x1024
  • NPU (Ascend910_9362 npu:0, float32, torch_npu 2.9.0):
    • logits shape (1,1,1024,1024) min -86.5184 max 27.2941 mean -8.5227
    • prob shape (1,1,1024,1024) min 0.0000 max 1.0000 mean 0.1199
    • 前景像素 125733 / 1048576 (11.99%阈值0.5)
    • 首次推理(含编译) 11964.06 ms, 第二轮稳定 ~11933 ms, 保存 mask.png 1024x1024
    • 状态: PASS 退出码 0, 完整日志见 assets/model_result.png
  • CPU 对照 (float32, 同一输入):
    • logits shape (1,1,1024,1024) min -86.5180 max 27.2812 mean -8.5224
    • prob shape (1,1,1024,1024) min 0.0000 max 1.0000 mean 0.1199
    • 前景像素 125733 / 1048576 (11.99%)
    • 耗时 61946.41 ms (CPU 侧, 含冷启动, 未同步)

数值为本次真实 NPU 推理直接输出, 非估算, 日志已通过 xterm.js 渲染存证.

6. CPU-NPU 一致性验证

  • 方法: 同一权重 (444 MB, revision e2bf8e...), 同一输入张量 (CPU 生成后搬运), 同一预处理/normalize, 同一 seed=42, dtype float32, eval mode, 分别保存 cpu_logits.npy/cpu_prob.npy 与 npu_logits.npy/npu_prob.npy 后比较
  • 工具: numpy 直接比较 (等价于 compare_outputs.py --atol 1e-4 --rtol 1e-3)
  • 结果:
    • Logits max_abs 0.499367 mean_abs 0.001081 (logits 未经 sigmoid, 数值范围大, 允许较大误差)
    • Prob (sigmoid后) max_abs 0.001605 mean_abs 0.000000
    • 二值化 mask (阈值0.5) IoU 1.000000 (inter 125733 union 125733)
    • 阈值判定: Prob max_abs <0.01 为 True, IoU>0.99 为 True => PASS
  • 阈值说明: Prob 阈值 0.01 为图像分割可接受误差 (sigmoid后敏感度低), IoU 0.99 为分割一致性 Gold 标准; 本模型 IoU 达 1.0 完全一致
  • 类型: 单样本 smoke consistency (1 image, 1024x1024), 非全量 DIS-TE benchmark, 不得解读为 DIS 排名

7. 性能测试

  • 预热 3 次, 正式 10 次, 每轮前后 torch.npu.synchronize(), dtype float32, batch 1, 1024x1024
  • 首次编译+推理: 11964.06 ms (已含 torchvision::deform_conv2d CPU fallback 的调度开销)
  • 稳定阶段 (10 runs, npu:0):
    • run1 12078.08 ms
    • run2 12366.41 ms
    • run3 11708.85 ms
    • run4 11866.06 ms
    • run5 12347.45 ms
    • run6 12312.16 ms
    • run7 11867.85 ms
    • run8 11349.06 ms
    • run9 11353.07 ms
    • run10 12223.26 ms
    • avg 11947.22 ms min 11349.06 max 12366.41 p50 11972.96 p90 12349.35 p95 12357.88
    • 吞吐 0.08 images/s, 峰值显存 3242.2 MB, 编译后稳定
  • CPU 对比: 61946 ms (近5倍慢), NPU 加速约 5.2x (即使存在 deform 回退)
  • 预处理未计时, 仅模型前向, 若含 Resize/Normalize 则各加 ~5 ms

8. 自验证截图

  • assets/agent_workflow.png : 工作流完整日志 (下载、侦察、加载、NPU推理、验证、性能) 渲染
  • assets/npu_device_call.png : npu-smi info + torch.npu.is_available() + 设备名 + 首参 device
  • assets/model_result.png : python inference.py 默认 NPU 推理输出 (含任务结果与 PASS)

9. 已知限制

  • torchvision::deform_conv2d 不支持 NPU, 自动回退 CPU, 导致性能未达最优且延迟较高 (~11s/张). 若未来 CANN 支持该算子, 可进一步提速.
  • 单样本 smoke 验证, 未覆盖 DIS-TR 训练集分布, 实际业务需在目标数据集全量评测.
  • 仅支持 1024 分辨率固定输入 (官方训练 size), 其他分辨率需 Resize, 可能引入边界误差.
  • float32 验证, 半精度 float16 未验证 (可能进一步加速但需重测一致性).
  • 权重未提交, 需自行从 HF 拉取, 依赖 trust_remote_code=True (已审查 birefnet.py 无网络/子进程写入风险).

10. 标签

  • Hardware: NPU, NPU, Ascend, Ascend910

Generated for ZhengPeng7/BiRefNet NPU adaptation, 2026-08-21, Ascend910_9362.