ZhengPeng7/BiRefNethttps://huggingface.co/ZhengPeng7/BiRefNete2bf8e4460fc8fa32bba5ea4d94b3233d367b0e4 (main)model.safetensors, dtype float32image-segmentation via AutoModelForImageSegmentation with trust_remote_code=Truefrom 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.
np.random.seed(42) torch.manual_seed(42) 固定, dtype float32, eval mode, 同一合成输入张量 CPU 生成后搬运至 NPU 以保证一致性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默认即完成真实 NPU 推理 (自动检测 npu:0):
python inference.py
# 可选: 验证模式 (CPU-NPU 对比 + 性能) 与基准模式
python inference.py --mode validate
python inference.py --mode benchmark
python inference.py --device cpu # CPU 对照/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() 计时mask.png (1024x1024 灰度)torchvision::deform_conv2d 在 NPU 上不支持, 会回退至 CPU (日志可见 npu_cpu_fallback), 其余算子在 NPU 执行seed=42 1024x1024
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(1,1,1024,1024) min -86.5184 max 27.2941 mean -8.5227(1,1,1024,1024) min 0.0000 max 1.0000 mean 0.1199mask.png 1024x1024PASS 退出码 0, 完整日志见 assets/model_result.png(1,1,1024,1024) min -86.5180 max 27.2812 mean -8.5224(1,1,1024,1024) min 0.0000 max 1.0000 mean 0.1199数值为本次真实 NPU 推理直接输出, 非估算, 日志已通过 xterm.js 渲染存证.
cpu_logits.npy/cpu_prob.npy 与 npu_logits.npy/npu_prob.npy 后比较compare_outputs.py --atol 1e-4 --rtol 1e-3)torch.npu.synchronize(), dtype float32, batch 1, 1024x1024torchvision::deform_conv2d CPU fallback 的调度开销)assets/agent_workflow.png : 工作流完整日志 (下载、侦察、加载、NPU推理、验证、性能) 渲染assets/npu_device_call.png : npu-smi info + torch.npu.is_available() + 设备名 + 首参 deviceassets/model_result.png : python inference.py 默认 NPU 推理输出 (含任务结果与 PASS)torchvision::deform_conv2d 不支持 NPU, 自动回退 CPU, 导致性能未达最优且延迟较高 (~11s/张). 若未来 CANN 支持该算子, 可进一步提速.trust_remote_code=True (已审查 birefnet.py 无网络/子进程写入风险).Generated for ZhengPeng7/BiRefNet NPU adaptation, 2026-08-21, Ascend910_9362.