z
zkx_/mobilevit-small-ascend
模型介绍文件和版本Pull Requests讨论分析

mobilevit-small on Ascend NPU

1. 简介

本文档记录 apple/mobilevit-small MobileViT 图像分类模型在昇腾 NPU(Ascend 910B3)上的迁移适配、精度评测与性能验证结果。

MobileViT-small 是 MobileViT 系列中最大的标准变体(5.6M 参数),在 ImageNet-1k 上训练,支持 1000 类分类。相比 xx-small(1.3M)和 x-small(2.3M),small 版本精度最高,适合对分类质量要求较高但仍需移动端部署的场景。

相关获取地址:

  • 权重下载地址(HuggingFace):https://huggingface.co/apple/mobilevit-small

2. 验证环境

组件版本
torch2.8.0
torch_npu2.8.0.post4
transformers5.8.1
CANN8.5.1
  • NPU:8 × Ascend 910B3
  • 精度对比基准:CPU(x86, PyTorch 2.8.0)

3. 部署使用流程

3.1 环境准备

conda create -n mobilevit-small python=3.11 -y
conda activate mobilevit-small

pip install torch==2.8.0 torch_npu==2.8.0.post4 \
    -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install transformers torchvision pillow numpy \
    -i https://pypi.tuna.tsinghua.edu.cn/simple

3.2 推理脚本使用

python inference.py --image photo.jpg --device npu
from inference import AgeClassifier
clf = AgeClassifier(model_path="./mobilevit-small", device="npu")
results = clf.predict(["photo.jpg"])

4. Smoke 验证

python inference.py --image photo.jpg --device npu

预期输出:Top-5 分类标签及置信度,无运行时错误。

5. 性能参考

测试条件:10 张合成 224×224 图像(固定种子),batch_size=8,NPU 预热 1 轮。

指标数值
CPU 吞吐量5.6 img/s
NPU 吞吐量161.1 img/s
CPU/NPU 加速比28.9 ×

MobileViT-small 5.6M 参数在 NPU 上获得 28.9× 加速,兼顾精度与效率。

6. 精度评测

6.1 评测方法

分别在 CPU 和 NPU 上推理 10 张合成图像,比较 1000 维 softmax 余弦相似度和 Top-1 一致性。

6.2 评测结果

指标数值
精度误差率0.0004%
Top-1 准确率100.0%

结论:精度误差率 0.0004%,远低于 1% 要求,评测通过。

7. 迁移适配说明

7.1 模型结构

  • Backbone:MobileViT(CNN + Transformer 混合,small 约 5.6M 参数)
  • Head:线性层 → 1000 类 ImageNet
  • 输入:224×224 RGB

7.2 适配要点

  1. AutoModelForImageClassification.from_pretrained() 加载
  2. model.to("npu:0") 迁移
  3. 与 xx-small/x-small 系列共享完全相同适配代码

7.3 关键代码

from transformers import AutoImageProcessor, AutoModelForImageClassification
model = AutoModelForImageClassification.from_pretrained("mobilevit-small").to("npu:0")
processor = AutoImageProcessor.from_pretrained("mobilevit-small")
inputs = processor(images=image, return_tensors="pt")
inputs = {k: v.to("npu:0") for k, v in inputs.items()}
with torch.no_grad():
    probs = torch.softmax(model(**inputs).logits, dim=-1)

8. 注意事项

  1. MobileViT 系列对比:xx-small (1.3M/69% top-1) → x-small (2.3M/74%) → small (5.6M/78%),参数量越大精度越高
  2. CNN+Transformer 融合:在移动端图像分类任务上优于同参数量纯 CNN(MobileNetV3)和纯 ViT
  3. 首次 NPU 推理:small 版本 5.6M 参数,算子编译约 3-4 秒
  4. 实时推理:NPU 161 img/s 可满足实时视频流(30fps × 5 路)的分类需求
下载使用量0