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

mobilevit-x-small on Ascend NPU

1. 简介

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

MobileViT 是 Apple 提出的移动端视觉 Transformer,将 CNN 的局部特征提取能力与 ViT 的全局自注意力机制融合。x-small 是第二小变体(2.3M 参数),在 ImageNet-1k 上训练,支持 1000 类分类。相比 xx-small(1.3M),精度提升约 1-2 个百分点。

相关获取地址:

  • 权重下载地址(HuggingFace):https://huggingface.co/apple/mobilevit-x-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-x-small python=3.11 -y
conda activate mobilevit-x-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-x-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 吞吐量6.9 img/s
NPU 吞吐量96.3 img/s
CPU/NPU 加速比13.9 ×

6. 精度评测

6.1 评测方法

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

6.2 评测结果

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

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

7. 迁移适配说明

7.1 模型结构

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

7.2 适配要点

  1. AutoModelForImageClassification.from_pretrained() 加载
  2. model.to("npu:0") 迁移
  3. CNN 卷积和 Transformer 注意力在 NPU 上原生加速

7.3 关键代码

from transformers import AutoImageProcessor, AutoModelForImageClassification
model = AutoModelForImageClassification.from_pretrained("mobilevit-x-small").to("npu:0")
processor = AutoImageProcessor.from_pretrained("mobilevit-x-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) → x-small (2.3M) → small (5.6M),速度和精度逐级提升
  2. CNN+ViT 混合架构:相比纯 ViT,MobileViT 对分辨率变化更鲁棒
  3. 首次 NPU 推理:轻量模型编译器编译约 2-3 秒
  4. 适合边缘设备:2.3M 参数,ONNX 导出后可部署到手机/嵌入式设备
下载使用量0