LeViT(LeViT: a Vision Transformer in ConvNet's Clothing for Faster Inference)是 Facebook Research 提出的一种轻量级视觉 Transformer 模型。LeViT-128S 是 LeViT-128 的精简版本,具有更浅的网络深度([2, 3, 4] 对比 [4, 4, 4]),在 ImageNet-1K 数据集上预训练。
LeViT 混合了卷积神经网络(CNN)和 Transformer 的优势,LeViT-128S 在保持良好精度的同时进一步减少了计算量。
图像分类(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 进行适配。LeViT-128S 具有 30MB 的模型大小,是 LeViT 系列中最轻量的模型之一。
.float() 确保 FP32 精度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: 27.94%
2. class 701: 14.33%
3. class 128: 4.68%
4. class 405: 2.68%
5. class 146: 2.46%Top-5 predictions:
1. class 21: 28.00%
2. class 701: 14.32%
3. class 128: 4.70%
4. class 405: 2.68%
5. class 146: 2.46%inference.py 进行推理使用相同输入分别在 CPU 和 NPU 上推理,对比 logits、概率分布、Top-1/Top-5 预测一致性。
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 概率 | 27.94% | 28.00% | 0.06% |
| Logits MAE | - | - | 0.00112328 |
| Logits MaxAE | - | - | 0.00683403 |
| Logits RMSE | - | - | 0.00144269 |
| 概率 MaxAE | - | - | 0.053775% |
| 余弦相似度 | - | - | 0.99999948 |
NPU 与 CPU 推理误差 < 1%。概率最大绝对误差仅 0.053775%,余弦相似度达到 0.99999948。Top-1 和 Top-5 预测完全一致。
| 设备 | 平均推理耗时 | 加速比 |
|---|---|---|
| CPU | 31.17 ms | 1.0× |
| NPU (Ascend 910) | 7.30 ms | 4.3× |
NPU 推理速度约为 CPU 的 4.3 倍。
