swinv2_cr_small_224.sw_in1k 是 Swin Transformer V2 系列中的 CR-Small 版本,基于 ImageNet-1K 数据集训练,支持 224x224 分辨率图像分类。
| 组件 | 规格 |
|---|---|
| NPU | Ascend 910 (32GB HBM) |
| CPU | ARM 64核 |
| 内存 | 256GB |
| 组件 | 版本 |
|---|---|
| 操作系统 | Ubuntu 22.04 (aarch64) |
| Python | 3.11.14 |
| PyTorch | 2.9.0 |
| torch_npu | 2.9.0.post1 |
| timm | 1.0.27 |
| CANN | 8.5.1 |
pip install torch torchvision timm Pillow modelscope safetensors使用 ModelScope 下载模型权重:
from modelscope import snapshot_download
model_path = snapshot_download('timm/swinv2_cr_small_224.sw_in1k')
print(f'模型下载路径: {model_path}')import torch
import timm
from PIL import Image
from safetensors.torch import load_file
MODEL_NAME = 'swinv2_cr_small_224.sw_in1k'
DEVICE = 'npu:0' # 或 'cpu'
# 加载模型
model = timm.create_model(MODEL_NAME, pretrained=False)
state_dict = load_file('model.safetensors')
# 移除 attn_mask 缓冲区
for k in list(state_dict.keys()):
if 'attn_mask' in k:
del state_dict[k]
model.load_state_dict(state_dict, strict=False)
model = model.to(DEVICE)
model.eval()
# 预处理
data_cfg = timm.data.resolve_model_data_config(model)
transform = timm.data.create_transform(**data_cfg, is_training=False)
# 加载图像
img = Image.open('test_image.jpg').convert('RGB')
input_tensor = transform(img).unsqueeze(0).to(DEVICE)
# 推理
with torch.no_grad():
output = model(input_tensor)
probs = torch.nn.functional.softmax(output[0], dim=0)
top5 = torch.topk(probs, 5)
for i in range(5):
print(f'{i+1}: class {top5.indices[i].item()} = {top5.values[i].item():.6f}')| 设备 | 平均耗时 (ms/张) | 加速比 |
|---|---|---|
| CPU | 423.93 | 1.0x |
| NPU (Ascend 910) | 23.29 | 18.2x |
NPU 推理速度相比 CPU 提升约 18 倍。
| 指标 | 数值 |
|---|---|
| 最大 Logits 绝对误差 | < 0.03 |
| 平均 Logits 绝对误差 | < 0.003 |
| 最大概率误差 | 0.000043 |
| 余弦相似度 | > 0.99997 |
使用合成测试图像(灰色纯色图)进行推理,CPU 与 NPU 的 Top-5 预测结果高度一致, 所有 Top-5 类别完全相同,概率误差极小。
NPU 与 CPU 推理结果误差 < 1%,精度通过。
最大概率误差仅为 0.000043(0.0043%),远低于 1% 的阈值。

python3 inference.py swinv2_cr_small_224.sw_in1k npupython3 inference.py swinv2_cr_small_224.sw_in1k cpupython3 compare_cpu_npu.py swinv2_cr_small_224.sw_in1k