MobileCLIP是苹果公司专为移动设备和边缘计算场景设计的轻量级多模态模型系列,其核心目标是在保持高性能的同时实现低延迟、小体积的部署效果。该模型通过多模态强化训练和轻量级架构设计 (如混合卷积-Transformer架构和结构重参数化技术),在参数规模(50M-150M)和推理延迟(3-15毫秒)间取得了优异平衡。其核心能力包括零样本图像分类、图文检索和图文一致性判断,无需针对特定任务微调即可快速适应新场景。
MobileCLIP适用于对延迟和隐私要求较高的场景,例如:
硬件型号:Atlas 800 3000 (300I Duo卡)
软件版本:
推理镜像下载:https://www.hiascend.com/developer/ascendhub/detail/af85b724a7e5469ebd7ea13c3439d48f

选择硬件对应的推理镜像

Docker启动命令:
docker run -it -d --net=host --shm-size=1g \
--privileged \
--name <container-name> \
-v /usr/local/Ascend/driver:/usr/local/Ascend/driver:ro \
-v /usr/local/sbin:/usr/local/sbin:ro \
-v /path-to-weights:/path-to-weights:ro \
mindie:1.0.0-800I-A2-py311-openeuler24.03-lts bash拉取MobileClip的Huggingace和Github官方仓库:
拉取仓库到本地
git clone https://github.com/apple/ml-mobileclip.git
git clone https://huggingface.co/apple/MobileCLIP-B-LT根据MobileClip官方仓库指导,创建conda环境:
conda create -n clipenv python=3.10
conda activate clipenv
pip install -e .torch.onnx.export()用于将PyTorch框架中训练好的模型转换为onnx格式
onnx-simplifier简化后,可以使ONNX模型结构更清晰,减少了ATC转换过程中因复杂结构或冗余节点导致的转换错误,简化后的模型可能触发ATC更高效的算子调度和内存优化策略,从而提升推理性能
安装onnx-simplifier:
pip install onnx-simplifier>=0.3.10 onnx>=1.14.0 onnxruntime>=1.14.1 numpy>=1.21.0修改textMobileCLIP_to_onnx_.py文件,将create_model_and_transforms()方法中路径修改为实际权重文件所在路径
# 加载模型
model, _, preprocess = mobileclip.create_model_and_transforms(
'mobileclip_blt',
pretrained='C:/xxxxx/ml-mobileclip/checkpoints/mobileclip_blt.pt' # 修改为mobileclip_blt.pt文件所在路径
)
model.eval().cpu()执行textMobileCLIP_to_onnx_.py,导出onnx模型,并完成简化,生成mobileclip_text_encoder_sim.onnx模型文件
python textMobileCLIP_to_onnx_.py昇腾张量编译器(Ascend Tensor Compiler,简称ATC)是异构计算架构CANN体系下的模型转换工具
可以将开源框架的网络模型以及Ascend IR定义的单算子描述文件(JSON格式)转换为昇腾AI处理器支持的.om格式离线模型
模型转换过程中,ATC会进行算子调度优化、权重数据重排、内存使用优化等具体操作,对原始的深度学习模型进行进一步的调优
ATC转换命令:
atc --model=mobileclip_text_encoder_sim.onnx \
--framework=5 \
--input_shape="text_input:1,77" \
--soc_version=Ascend310P3 \
--output=mobileclip_text_encoder参数说明:
修改onnx_infer_test.py中模型为导出的onnx模型路径:
import onnx
import onnxruntime as ort
import numpy as np
model = onnx.load("mobileclip_text_encoder_sim.onnx") # 修改为导出的onnx模型路径
onnx.checker.check_model(model) # 无报错说明结构完整
# 加载模型(只需一次)
ort_session = ort.InferenceSession("mobileclip_text_encoder_sim.onnx")
# 测试不同批量大小(batch_size)
for batch in [1, 4, 8]:
# 生成int64类型输入数据
dummy_input = np.random.randint(0, 1000, (batch, 77)).astype(np.int64)
outputs = ort_session.run(None, {"text_input": dummy_input})
print(f"Batch {batch} → 输出形状: {outputs[0].shape}")
执行onnx_infer_test.py文件
python onnx_infer_test.py