Inception v4 是基于 CNN 的图像分类模型,在 ImageNet-1k 数据集上训练。该模型在华为昇腾 NPU 上完成推理适配。
| 属性 | 值 |
|---|---|
| 输入尺寸 | 299 × 299 |
| 类别数 | 1000 |
| 预处理均值 | [0.485, 0.456, 0.406] |
| 预处理标准差 | [0.229, 0.224, 0.225] |
此模型基于 torch_npu 在华为昇腾 NPU 上完成推理适配。模型权重通过 ModelScope 下载,加载到 timm 定义的模型结构中。CPU 和 NPU 推理结果对比验证精度满足要求。
pip install -r requirements.txtpython3 inference.py --device cpupython3 inference.py --device npu=== Running inference on CPU ===
Average inference time: 593.28 ms (10 runs)
Top-5 predictions:
Class 21: 0.107987
Class 701: 0.052939
Class 405: 0.029546
Class 557: 0.026602
Class 892: 0.026484=== Running inference on NPU ===
Average inference time: 16.05 ms (10 runs)
Top-5 predictions:
Class 21: 0.108195
Class 701: 0.052953
Class 405: 0.029556
Class 557: 0.026634
Class 892: 0.026473| 设备 | 平均推理耗时 (ms) | 加速比 |
|---|---|---|
| CPU | 593.28 | 1.0× |
| NPU (Ascend910) | 16.05 | 37.0× |
NPU 推理相比 CPU 加速约 37.0 倍。
使用相同输入(固定随机种子)分别在 CPU 和 NPU 上运行推理,对比输出 logits 和概率分布。
运行精度测试脚本:
python3 compare_cpu_npu.py| 指标 | 值 |
|---|---|
| Logits 最大绝对误差 | 0.00418520 |
| Logits 余弦相似度 | 0.99999989 |
| Probabilities 最大绝对误差 | 0.00012060 |
| Top-1 类别一致率 | 100.00% |
| Top-5 类别一致率 | 100.00% |
| Rank | CPU Class | CPU Prob | NPU Class | NPU Prob | Prob Diff |
|---|---|---|---|---|---|
| 1 | 21 | 0.107987 | 21 | 0.108195 | 0.00020800 |
| 2 | 701 | 0.052939 | 701 | 0.052953 | 0.00001400 |
| 3 | 405 | 0.029546 | 405 | 0.029556 | 0.00001000 |
| 4 | 557 | 0.026602 | 557 | 0.026634 | 0.00003200 |
| 5 | 892 | 0.026484 | 892 | 0.026473 | 0.00001100 |
NPU 与 CPU 推理误差为 0.01%(概率最大绝对误差),符合精度误差小于 1% 的要求。
Top-1 和 Top-5 类别完全一致,余弦相似度为 0.99999989,表明 NPU 推理结果与 CPU 高度一致。
import timm, torch
from timm.data import resolve_data_config, create_transform
from safetensors.torch import load_file
from PIL import Image
import numpy as np
model_name = 'inception_v4.tf_in1k'
model = timm.create_model(model_name, pretrained=False)
# 从 safetensors 加载权重
state_dict = load_file('/path/to/model.safetensors')
model.load_state_dict(state_dict, strict=True)
model = model.to('npu')
model.eval()
# 数据预处理
config = resolve_data_config({}, model=model)
transform = create_transform(**config)
# 推理
img = Image.open('image.jpg').convert('RGB')
input_tensor = transform(img).unsqueeze(0).to('npu')
with torch.no_grad():
output = model(input_tensor)
probs = torch.nn.functional.softmax(output, dim=1)
top_probs, top_indices = torch.topk(probs, 5, dim=1)
以下日志展示了 NPU 推理成功的关键信息:
=== Running inference on CPU ===
Average inference time: 593.28 ms (10 runs)
Top-5 predictions:
Inference completed on cpu
Average inference time: 593.28 ms本仓库为 inception_v4.tf_in1k 模型在华为昇腾 NPU 上的适配仓库,包含完整的推理脚本、精度测试脚本和部署说明。