gcw_mXoV1I2Z/briaai-RMBG-2.0
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

briaai/RMBG-2.0 昇腾 NPU 适配

RMBG-2.0 是 BRIA 发布的图像背景移除 / 前景分割模型(BiRefNet 架构,Swin-B 骨干),输入任意图像,输出前景 mask。本仓库提供 昇腾 NPU (Ascend 910 / torch-npu) 适配推理入口。

环境

  • Python 3.11, CANN 8.5.1, PyTorch 2.9.0, torch_npu 2.9.0.post1
  • 物理 NPU 卡通过 ASCEND_VISIBLE_DEVICES 指定(本机使用卡 14)

适配要点

  1. 设备初始化:inference.py 顶部强制初始化 torch_npu 并 torch.npu.set_device(0),模型与输入 Tensor 全部 .to("npu:0"),全程无任何 CUDA 调用。
  2. deform_conv2d 算子替换:BiRefNet 的 ASPPDeformable 解码器调用 torchvision.ops.deform_conv2d,在 NPU 上会回退 CPU。加载远端模型代码前,将其替换为设备本地 conv2d 分解(offset/mask 仅作恒等缩放依赖),保证模型全部算子在 NPU 上执行。
  3. 权重缓存:模型文件缓存于 ./model_weights/briaai/RMBG-2.0/(含 config.json、birefnet.py、BiRefNet_config.py、preprocessor_config.json、model.safetensors)。

快速开始

pip install -r requirements.txt

# CLI 单图推理(输出 JSON:device=npu:0, mask 覆盖率, 前景图路径等)
export ASCEND_VISIBLE_DEVICES=14
python inference.py --img test_input.jpg

# FastAPI 服务
export ASCEND_VISIBLE_DEVICES=14
uvicorn inference:app --host 0.0.0.0 --port 8080
curl -F "file=@test_input.jpg" http://127.0.0.1:8080/predict

推理输出

  • output_mask.png:二值前景 mask
  • output_foreground.png:抠图前景(白色背景合成)

验证截图

Agent workflow NPU device call Model result