Interlinked7/levit-128-npu
模型介绍文件和版本Pull Requests讨论分析
下载使用量0

levit-128-NPU

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

模型介绍

本仓库包含了 facebook/levit-128 在华为昇腾 Ascend910 NPU 上的适配版本,支持 CPU 和 NPU 两种推理方式,并提供了完整的精度验证流程。

LeViT(LeVity Vision Transformer)是一种混合神经网络架构,结合了卷积神经网络(CNN)和 Vision Transformer(ViT)的优点。LeViT-128 是 LeViT 系列的小型模型,具有 128 维隐藏层,在保持较高分类精度的同时具有极快的推理速度。

原始模型地址: facebook/levit-128

任务类型

图像分类(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

NPU 适配说明

本适配基于华为 Ascend910 NPU(CANN 8.5.1,显存 64GB)完成。适配内容包括:

  1. 使用 HuggingFace Transformers 加载 LeViT-128 预训练模型
  2. 通过 model.to("npu:0") 将模型权重迁移到 NPU 设备实现加速推理
  3. 对输入张量进行设备迁移以确保在 NPU 上正确运行
  4. 实现了 CPU 与 NPU 推理结果的精度对比验证

环境准备

# 安装基础依赖
pip install torch torch_npu transformers Pillow numpy -i https://mirrors.aliyun.com/pypi/simple/

# 设置环境变量
export MODELSCOPE_CACHE=/path/to/cache

推理命令

CPU 推理:

python3 inference.py

CPU vs NPU 精度对比:

python3 compare_cpu_npu.py

部署和推理方法

方式一:直接运行推理脚本

python3 inference.py

方式二:自定义 NPU 推理

import torch
from transformers import LevitForImageClassificationWithTeacher, LevitImageProcessor
from PIL import Image

# 加载模型和处理器
processor = LevitImageProcessor.from_pretrained("facebook/levit-128")
model = LevitForImageClassificationWithTeacher.from_pretrained("facebook/levit-128")

# NPU 推理
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)

CPU/NPU 精度测试方法

  1. 使用 HuggingFace Transformers 加载 LeViT-128 预训练模型
  2. 在 CPU 上执行推理,记录输出分数和标签
  3. 将模型迁移到 NPU 设备,在 NPU 上执行相同推理
  4. 对比 CPU 与 NPU 输出的差异

关键比较指标:

  • 最大绝对误差(Max Absolute Difference):逐元素比较输出分数的最大差异
  • 平均绝对误差(Mean Absolute Difference):逐元素比较输出分数的平均差异
  • 相对误差(Relative Error):最大绝对误差 / 最大分数值
  • 余弦相似度(Cosine Similarity):衡量输出向量的方向一致性
  • Top-1 匹配率:最高概率标签是否一致
  • Top-5 一致率:前5个预测标签的重叠比例

CPU/NPU 精度测试结果

指标值
最大绝对误差1.019239e-05
平均绝对误差3.569107e-08
相对误差0.0010%
余弦相似度1.000000
Top-1 标签匹配True
Top-5 一致率100%
CPU 推理耗时48.0 ms
NPU 推理耗时195.7 ms

Top-5 分类结果对比

排名CPU 类别CPU 分数NPU 类别NPU 分数
Top-1class 120.986135class 120.986125
Top-2class 100.001502class 100.001501
Top-3class 130.001080class 130.001081
Top-4class 140.000801class 140.000804
Top-5class 110.000790class 110.000789

精度结论

NPU 与 CPU 推理结果误差 < 1%(实际相对误差为 0.0010%),精度完全满足要求。余弦相似度为 1.000000,Top-1 和 Top-5 结果完全一致。

性能测试结果

平台推理耗时 (ms)加速比
CPU48.01.00x
NPU (Ascend910)195.70.25x

注:LeViT-128 模型较小(参数量少),在 NPU 上的推理时间包含了算子下发和数据传输开销,导致 NPU 推理耗时高于 CPU。对于大规模批量推理或更大模型,NPU 的加速效果会更明显。

运行截图

以下截图展示了推理的实际运行结果。

推理截图

推理

精度对比截图

精度对比

模型标签

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