本项目在 昇腾 NPU(Ascend)上适配了 test_nfnet.r160_in1k 图像分类模型。NFNet(Normalizer-Free ResNet)是一种无归一化层的残差网络架构,在保持训练稳定性的同时去除了 Batch Normalization,从而减少计算开销。该模型为 NFNet 的轻量测试版本,参数量 0.4M,输入尺寸 160x160,基于 ImageNet-1k 预训练。
原始模型地址:timm/test_nfnet.r160_in1k
| 组件 | 版本 |
|---|---|
| Python | 3.11.14 |
| PyTorch | 2.9.0 |
| torch_npu | 2.9.0.post1 |
| timm | 1.0.27 |
| torchvision | 0.24.0 |
| Ascend CANN | 8.5.1 |
| 操作系统 | Linux aarch64 |
该模型基于 timm 框架,使用纯 PyTorch 算子,无需修改模型源代码即可在昇腾 NPU 上运行。适配过程仅需:
timm.create_model() 加载预训练权重model.to("npu") 将模型迁移至 NPU 设备# 安装依赖
pip install torch torchvision timm Pillow numpy requests
# 验证 NPU 可用性
python3 -c "import torch; print('NPU available:', torch.npu.is_available())"# CPU 推理
python3 inference.py --device cpu
# NPU 推理
python3 inference.py --device npu
# 使用指定图片推理
python3 inference.py --device npu --image /path/to/image.jpg| Rank | Class ID | Probability(%) |
|---|---|---|
| 1 | 393 | 0.1036 |
| 2 | 706 | 0.1031 |
| 3 | 695 | 0.1030 |
| 4 | 563 | 0.1030 |
| 5 | 574 | 0.1029 |
| Rank | Class ID | Probability(%) |
|---|---|---|
| 1 | 393 | 0.1036 |
| 2 | 706 | 0.1031 |
| 3 | 695 | 0.1030 |
| 4 | 563 | 0.1030 |
| 5 | 574 | 0.1029 |

import torch
import timm
from PIL import Image
from timm.data import resolve_model_data_config, create_transform
# 加载模型(NPU)
model = timm.create_model("test_nfnet.r160_in1k", pretrained=True).eval().to("npu")
# 准备输入
img = Image.open("example.jpg").convert("RGB")
data_config = resolve_model_data_config(model)
transform = create_transform(**data_config, is_training=False)
input_tensor = transform(img).unsqueeze(0).to("npu")
# 推理
with torch.no_grad():
output = model(input_tensor)
probs = torch.nn.functional.softmax(output, dim=1)
top5 = torch.topk(probs, k=5, dim=1)
print(top5)# 执行完整 CPU / NPU 精度对比
python3 compare_cpu_npu.pytorch.manual_seed(42))| 指标 | 值 |
|---|---|
| MAE (Mean Absolute Error) | 0.00001548 |
| MSE | 0.00000000 |
| RMSE | 0.00001928 |
| Max Absolute Error | 0.00006037 |
| Cosine Similarity | 0.99999877 |
| Relative Error | 0.5571% |
| Prob MAE | 0.00000002 |
| Prob Max Abs Error | 0.00000006 |
| Top-1 Match | True (均为 Class 393) |
| Top-5 Overlap | 5/5 (完全一致) |
| Rank | CPU Class ID | CPU Prob(%) | NPU Class ID | NPU Prob(%) |
|---|---|---|---|---|
| 1 | 393 | 0.1036 | 393 | 0.1036 |
| 2 | 706 | 0.1031 | 706 | 0.1031 |
| 3 | 695 | 0.1030 | 695 | 0.1030 |
| 4 | 563 | 0.1030 | 563 | 0.1030 |
| 5 | 574 | 0.1029 | 574 | 0.1029 |

NPU 与 CPU 推理结果相对误差 < 1%(0.5571%),精度测试通过。
| 设备 | 推理耗时 (s) |
|---|---|
| CPU | 0.0265 |
| NPU (Ascend) | 0.1581 |
说明:该模型参数量仅 0.4M,属于超轻量模型,CPU 可直接快速完成推理。NPU 推理包含设备数据传输开销,对大 batch 和大模型场景优势更明显。
import gc
gc.collect()
torch.npu.empty_cache()Apache-2.0