本文档记录 google/vit-base-patch16-224-in21k 在华为昇腾 NPU(Ascend910B4)上的推理适配与验证结果。
vit-base-patch16-224-in21k 是 Google 提出的 Vision Transformer 基线模型,基于 ImageNet-21k 预训练。本验证的核心目标是确认该模型在昇腾 NPU 上可完成标准 PyTorch 推理,且精度与 CPU 基线的误差控制在 1% 以内。
相关获取地址:
参考文档:
| 组件 | 版本 |
|---|---|
CANN | 8.5.1 |
torch | 2.9.0 |
torch-npu | 2.9.0.post1+gitee7ba04 |
transformers | 4.57.6 |
modelscope | 1.35.3 |
Pillow | 10.4.0 |
numpy | 1.26.4 |
1 逻辑卡(Ascend910B4)/opt/atomgit/vit-base-patch16-224-npu/model_weights/google/vit-base-patch16-224-in21ksource /usr/local/Ascend/ascend-toolkit/set_env.sh
export ASCEND_RT_VISIBLE_DEVICES=0import torch_npu
from torch_npu.contrib import transfer_to_npu # 自动替换 cuda→npu
import torch
import numpy as np
from PIL import Image
from transformers import ViTForImageClassification, ViTImageProcessor
model_path = 'google/vit-base-patch16-224-in21k'
processor = ViTImageProcessor.from_pretrained(model_path)
model = ViTForImageClassification.from_pretrained(model_path)
model.eval()
model = model.to('npu:0')
image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8))
inputs = processor(images=image, return_tensors="pt")
inputs = {k: v.to('npu:0') for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
print(logits)cd /opt/atomgit/vit-base-patch16-224-npu/scripts
# CPU baseline
python3 infer_cpu.py
# NPU inference
python3 infer_npu.py
# 精度对比
python3 compare_accuracy.py
# 综合性能测评
python3 benchmark.py基础检查:
cd /opt/atomgit/vit-base-patch16-224-npu/scripts
python3 infer_npu.py验证结果:
0logits shape 为 [1, 2](因预训练权重不含分类头,维度由模型默认配置决定)~12 ms测试条件:连续推理,预热后取多次测量的统计值。
| 指标 | CPU | NPU (batch=1) | NPU (batch=4) | NPU (batch=8) |
|---|---|---|---|---|
mean_latency_ms | 1761.40 | 12.42 | 12.03 | 11.91 |
median_latency_ms | 1760.89 | 12.21 | 11.72 | 11.81 |
min_latency_ms | 1751.59 | 11.83 | 11.53 | 11.66 |
max_latency_ms | 1775.22 | 15.38 | 16.81 | 12.62 |
p99_latency_ms | 1774.63 | 14.92 | — | — |
std_ms | — | 0.60 | 1.11 | 0.27 |
加速比(相对 CPU):
~142x~568x(单样本等效)说明:batch 增大时,NPU 单 batch 延迟基本保持不变,说明 AICore 利用率仍有冗余,吞吐随 batch 线性提升。
使用相同随机种子构造输入,分别运行 CPU 和 NPU 推理,对比 logits。
| 指标 | 数值 |
|---|---|
max_abs_diff | 7.54e-04 |
mean_abs_diff | 4.52e-04 |
max_rel_diff | 1.26% |
mean_rel_diff | 0.76% |
top1_match_rate | 100% |
结论:Mean Relative Diff < 1%,Top-1 匹配率 100%,精度验证通过。
transfer_to_npu 注入顺序
必须在所有其他 import 之前注入:
import torch_npu
from torch_npu.contrib import transfer_to_npu否则 .cuda() 等 API 不会被自动替换为 .npu()。
预训练权重不含分类头
vit-base-patch16-224-in21k 为 ImageNet-21k 预训练权重,不含下游任务的 classifier.weight/bias。直接推理时分类头是随机初始化的,输出的类别概率无实际语义。如需实际图像分类,请使用下游微调后的 checkpoint(例如 google/vit-base-patch16-224)。
算子编译缓存
NPU 首次运行时会触发算子编译(AICore kernel compile),首次延迟可能略高(约 15 ms)。编译缓存会自动落盘,二次运行延迟稳定在 ~12 ms。
内存占用
batch=1 时 NPU HBM 占用约 ~400 MB,远低于 Ascend910B4 的 32 GB 显存,单卡可同时部署多个实例。