g
gcw_C8PI9e90/levit-384-npu
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

LeViT-384 昇腾 NPU 适配说明

模型介绍

LeViT(LeViT: a Vision Transformer in ConvNet's Clothing for Faster Inference)是 Facebook Research 提出的一种轻量级视觉 Transformer 模型。LeViT-384 是 LeViT 系列中最大的模型,具有 384/512/768 的隐藏维度,在 ImageNet-1K 数据集上预训练。

LeViT-384 在 LeViT 系列中拥有最强的表达能力,同时保持了高效推理的特性。

  • 论文: LeViT: a Vision Transformer in ConvNet's Clothing for Faster Inference
  • 原始模型: facebook/levit-384

任务类型

图像分类(Image Classification)

模型框架

  • PyTorch + Transformers

输入格式

  • RGB 图像,分辨率 224×224 像素
  • 预处理:使用 LevitImageProcessor 进行标准化处理

输出格式

  • 1000 个 ImageNet 类别的 logits 向量
  • 经过 Softmax 后的概率分布

依赖环境

依赖版本
Python3.11.14
PyTorch2.9.0
torch_npu2.9.0.post1
Transformers4.57.6
Pillow12.2.0
NumPy1.x

NPU 适配说明

该模型基于华为昇腾 Ascend 910 NPU 进行适配。LeViT-384 是 LeViT 系列中最大的模型,约 150MB,NPU 加速效果最为显著。

适配要点

  • 模型加载后使用 .float() 确保 FP32 精度
  • CPU 和 NPU 使用完全相同的输入图像和预处理流程
  • 推理过程使用 10 次平均以获取稳定耗时数据

环境准备

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple torch torchvision transformers Pillow numpy

推理命令

CPU 推理

python3 inference.py --device cpu --image test.jpg

NPU 推理

python3 inference.py --device npu --image test.jpg

推理结果

使用合成测试图像(224×224 RGB)进行推理测试:

CPU 推理结果

Top-5 predictions:
  1. class 21: 36.24%
  2. class 701: 9.08%
  3. class 549: 7.85%
  4. class 128: 5.87%
  5. class 405: 1.94%

NPU 推理结果

Top-5 predictions:
  1. class 21: 36.35%
  2. class 701: 9.08%
  3. class 549: 7.81%
  4. class 128: 5.90%
  5. class 405: 1.95%

部署和推理方法

  1. 通过 ModelScope 下载模型或使用本地权重
  2. 运行 inference.py 进行推理
  3. 支持 CPU 和 NPU 两种模式

CPU/NPU 精度测试方法

使用相同输入分别在 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 精度测试结果

指标CPUNPU误差
Top-1 类别class 21class 21一致
Top-1 概率36.24%36.35%0.11%
Logits MAE--0.00163950
Logits MaxAE--0.00856113
Logits RMSE--0.00205914
概率 MaxAE--0.108862%
余弦相似度--0.99999929

结论

NPU 与 CPU 推理误差 < 1%。概率最大绝对误差仅 0.108862%,余弦相似度达到 0.99999929。Top-1 和 Top-5 预测完全一致。

性能测试结果

设备平均推理耗时加速比
CPU124.94 ms1.0×
NPU (Ascend 910)9.42 ms13.3×

NPU 推理速度约为 CPU 的 13.3 倍。LeViT-384 在 NPU 上的加速效果最为显著,因为大模型能更充分地利用 NPU 的计算能力。

模拟终端输出截图

终端输出

模型标签

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