#+NPU #+昇腾 #+Ascend910 #+CV #+图像分类 #+LeViT #+Transformer #+ViT
本仓库包含了 facebook/levit-128S 在华为昇腾 Ascend910 NPU 上的适配版本,支持 CPU 和 NPU 两种推理方式,并提供了完整的精度验证流程。
LeViT(LeVity Vision Transformer)是一种混合神经网络架构,结合了卷积神经网络(CNN)和 Vision Transformer(ViT)的优点。LeViT-128S 是 LeViT-128 的增强版本,具有更高的精度表现。
原始模型地址: facebook/levit-128S
图像分类(Image Classification),1000 类 ImageNet 分类
PyTorch(HuggingFace Transformers)
图像(Image),RGB 格式,预处理后为 224×224 张量
1000 个类别的分类 logits 和概率分数
| 依赖 | 版本 |
|---|---|
| Python | >= 3.8 |
| PyTorch | >= 2.0.0 |
| torch_npu | >= 2.0.0 |
| Transformers | >= 4.30.0 |
| NumPy | >= 1.20.0 |
| Pillow | >= 9.0.0 |
本适配基于华为 Ascend910 NPU(CANN 8.5.1,显存 64GB)完成。适配内容包括:
model.to("npu:0") 将模型权重迁移到 NPU 设备实现加速推理# 安装基础依赖
pip install torch torch_npu transformers Pillow numpy -i https://mirrors.aliyun.com/pypi/simple/
# 设置环境变量
export MODELSCOPE_CACHE=/path/to/cacheCPU 推理:
python3 inference.pyCPU vs NPU 精度对比:
python3 compare_cpu_npu.pypython3 inference.pyimport torch
from transformers import LevitForImageClassificationWithTeacher, LevitImageProcessor
from PIL import Image
processor = LevitImageProcessor.from_pretrained("facebook/levit-128S")
model = LevitForImageClassificationWithTeacher.from_pretrained("facebook/levit-128S")
model = model.to("npu:0")
image = Image.open("test.jpg").convert("RGB")
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)
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
print(probs)关键比较指标:
| 指标 | 值 |
|---|---|
| 最大绝对误差 | 4.523993e-05 |
| 平均绝对误差 | 1.054169e-07 |
| 相对误差 | 0.0046% |
| 余弦相似度 | 1.000000 |
| Top-1 标签匹配 | True |
| Top-5 一致率 | 100% |
| CPU 推理耗时 | 37.8 ms |
| NPU 推理耗时 | 205.3 ms |
| 排名 | CPU 类别 | CPU 分数 | NPU 类别 | NPU 分数 |
|---|---|---|---|---|
| Top-1 | class 12 | 0.977727 | class 12 | 0.977773 |
| Top-2 | class 10 | 0.005715 | class 10 | 0.005711 |
| Top-3 | class 11 | 0.000622 | class 11 | 0.000622 |
| Top-4 | class 14 | 0.000561 | class 14 | 0.000561 |
| Top-5 | class 140 | 0.000470 | class 140 | 0.000467 |
NPU 与 CPU 推理结果误差 < 1%(实际相对误差为 0.0046%),精度完全满足要求。余弦相似度为 1.000000,Top-1 和 Top-5 结果完全一致。
| 平台 | 推理耗时 (ms) | 加速比 |
|---|---|---|
| CPU | 37.8 | 1.00x |
| NPU (Ascend910) | 205.3 | 0.18x |
注:LeViT-128S 模型较小,在 NPU 上的推理时间包含了算子下发和数据传输开销,导致 NPU 推理耗时高于 CPU。对于大规模批量推理或更大模型,NPU 的加速效果会更明显。
以下截图展示了推理的实际运行结果。


#+NPU #+昇腾 #+Ascend910 #+CV #+图像分类 #+LeViT #+Transformer #+ViT