本文档记录 nateraw/resnet18-random-classifier 在昇腾 NPU(Ascend910)环境的快速部署与验证结果。
ResNet-18 图像分类模型,基于 timm 框架,支持一键加载推理。
相关获取地址:
| 组件 | 版本 |
|---|---|
torch | 2.5.1 |
torch_npu | 2.5.1 |
timm | >=1.0.0 |
CANN | 8.5.RC1 |
pip install timm torch torchvision pillowimport torch, timm
from PIL import Image
from torchvision import transforms
device = torch.device("npu:0" if torch.npu.is_available() else "cpu")
model = timm.create_model("resnet18", pretrained=False, num_classes=4)
state_dict = torch.load("pytorch_model.bin", map_location="cpu")
model.load_state_dict(state_dict)
model = model.to(device).eval()
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
img = Image.new("RGB", (224, 224), (128, 128, 128))
input_tensor = transform(img).unsqueeze(0).to(device)
with torch.no_grad():
output = model(input_tensor)
pred = output.argmax(-1).item()
print(f"Predicted class: {pred}")python3 inference.py验证结果:
npu:0测试条件:FP32 / batch=1 / warmup=5 / timed=50 runs,Ascend910 单卡。
| 指标 | 数值 |
|---|---|
| 平均推理时间 | 1.99 ms |
| 测试次数 | 50 |
NPU 与 CPU 输出对比,使用 4 张纯色测试图(RGB 255/0、0/255/0、0/0/255、128/128/128),比较 logits 一致性。
| 指标 | 数值 |
|---|---|
| Top-1 一致性 | 4/4 |
| Top-5 一致性 | 4/4 |
| 最大 logits 相对误差 | 0.392 % |
| 平均 KL 散度 | 0.0 |
| 结论 | PASS |