LeViT(LeViT: a Vision Transformer in ConvNet's Clothing for Faster Inference)是 Facebook Research 提出的一种轻量级视觉 Transformer 模型。LeViT-128 是该系列中的一个小型模型,在 ImageNet-1K 数据集上预训练,适用于图像分类任务。
LeViT 混合了卷积神经网络(CNN)和 Transformer 的优势,通过使用注意力机制和卷积操作的结合,在保持高精度的同时实现了快速的推理速度。
图像分类(Image Classification)
| 依赖 | 版本 |
|---|---|
| Python | 3.11.14 |
| PyTorch | 2.9.0 |
| torch_npu | 2.9.0.post1 |
| Transformers | 4.57.6 |
| Pillow | 12.2.0 |
| NumPy | 1.x |
该模型基于华为昇腾 Ascend 910 NPU 进行适配,主要工作包括:
.float() 确保 FP32 精度# 安装依赖
pip install torch torchvision transformers Pillow numpy
# 或使用清华镜像
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple torch torchvision transformers Pillow numpypython3 inference.py --device cpu --image test.jpgpython3 inference.py --device npu --image test.jpg使用合成测试图像(224×224 RGB)进行推理测试:
Top-5 predictions:
1. class 21: 33.67%
2. class 701: 13.35%
3. class 22: 4.16%
4. class 128: 3.54%
5. class 977: 2.38%Top-5 predictions:
1. class 21: 33.91%
2. class 701: 13.27%
3. class 22: 4.20%
4. class 128: 3.57%
5. class 557: 2.34%inference.py 脚本进行推理python3 inference.py --device cpu --image test.jpg
python3 inference.py --device npu --image test.jpg
python3 compare_cpu_npu.py| 指标 | CPU | NPU | 误差 |
|---|---|---|---|
| Top-1 类别 | class 21 | class 21 | 一致 |
| Top-1 概率 | 33.67% | 33.91% | 0.24% |
| Logits MAE | - | - | 0.00356148 |
| Logits MaxAE | - | - | 0.01721168 |
| Logits RMSE | - | - | 0.00462557 |
| 概率 MaxAE | - | - | 0.246301% |
| 余弦相似度 | - | - | 0.99999537 |
NPU 与 CPU 推理误差 < 1%。所有精度指标均显示 NPU 推理结果与 CPU 推理结果高度一致,概率最大绝对误差仅 0.246301%,余弦相似度达到 0.99999537。Top-1 预测完全一致。
| 设备 | 平均推理耗时 | 加速比 |
|---|---|---|
| CPU | 40.17 ms | 1.0× |
| NPU (Ascend 910) | 9.24 ms | 4.3× |
NPU 推理速度约为 CPU 的 4.3 倍。
