将 unitreerobotics/UnifoLM-VLM-Base(Qwen2.5-VL 架构多模态大模型,transformers + PyTorch 框架)迁移到本地昇腾 Ascend910 NPU,并提供 HTTP 服务化多模态推理(图片 + 文本 → 回答)。
| 项目 | 说明 |
|---|---|
| 模型 | unitreerobotics/UnifoLM-VLM-Base (Qwen2_5_VLForConditionalGeneration) |
| 参数 | 语言侧 28 层 / hidden 3584 / GQA 4 KV-heads;视觉 ViT 32 层 / hidden 1280 |
| 精度 | bfloat16,权重约 16 GB(4 个 safetensors 分片) |
| 能力 | 视觉问答 / 多模态对话(支持图像与文本输入) |
| 迁移框架 | PyTorch 2.9.0 + torch_npu 2.9.0.post1 + transformers 4.57.6 |
| 推理硬件 | 昇腾 Ascend910 (Ascend910_9382) × 8 卡 |
| 服务框架 | FastAPI + Uvicorn |
| 本机实测 | 模型加载 ~4.5 s;视觉问答 109 tokens 输出正常,文本问答正确 |
UnifoLM-VLM-Base-npu/
├── README.md # 本指南
├── requirements.txt # 运行环境依赖
├── inference.py # NPU 多模态服务化推理脚本 (FastAPI)
├── test_inference.py # 自动化测试用例
├── make_screenshots.py # 截图渲染工具(终端风格)
├── assets/ # 截图
│ ├── npu_device_call.png # NPU 设备调用截图
│ ├── model_result.png # 测试结果截图
│ └── agent_workflow.png # 适配过程截图
└── results/
├── test_results.json # 测试结果 (JSON)
├── test_results.txt # 测试结果 (文本)
└── server.log # 服务运行日志flash_attn(本适配使用 transformers eager 注意力,避免 CUDA 编译依赖)# 1. 加载 CANN 环境
source /usr/local/Ascend/ascend-toolkit/set_env.sh
# 2. 安装依赖(华为镜像源)
export PIP_INDEX_URL=https://repo.huaweicloud.com/repository/pypi/simple/
pip install -r requirements.txt
# 3. 校验 NPU 可用
npu-smi info
python -c "import torch, torch_npu; print(torch.randn(3, 4).npu() + torch.randn(3, 4).npu())"export ASCEND_RT_VISIBLE_DEVICES=0 # 指定使用第 0 卡
python inference.py --host 0.0.0.0 --port 8000首次启动需加载 16GB 权重(约 5 秒)+ 首次推理算子编译(数分钟,之后走缓存)。启动后打印模型/设备信息(对照 assets/npu_device_call.png)。
# 自动启动服务 → 测试 5 个接口 → 结果写入 results/
python test_inference.py --port 8000预期输出(对照 assets/model_result.png):
[PASS] /health 设备=npu:0 NPU可用=True
[PASS] /model_info 架构=Qwen2_5_VLForConditionalGeneration 28层 设备=npu:0
[PASS] /test_image 测试图片生成 OK (336x336)
[PASS] /generate 回答: The image features a striking contrast between two colors...
[PASS] /generate 输出 109 tokens 设备=npu:0
[PASS] /generate(文本) 回答: 5
[PASS] 全部测试用例通过 ✅python inference.py --self-test| 方法 | 路径 | 说明 |
|---|---|---|
| GET | /health | 健康检查,返回服务与 NPU 设备状态 |
| GET | /model_info | 模型结构、视觉/语言配置、推理设备 |
| GET | /test_image | 返回内置测试图片(base64),供测试调试 |
| POST | /generate | 多模态生成:{"prompt": "...", "image_base64": "..."}(或 image_path),省略图片即为纯文本问答 |
调用示例:
# 1) 获取内置测试图片
curl -s http://127.0.0.1:8000/test_image > test_image.json
# 2) 视觉问答(图片 + 文本)
curl -s http://127.0.0.1:8000/generate \
-H "Content-Type: application/json" \
-d "{\"prompt\": \"Describe this image briefly.\", \"image_base64\": \"$(python -c "import json;print(json.load(open('test_image.json'))['image_base64'])")\"}"
# 3) 纯文本问答
curl -s http://127.0.0.1:8000/generate \
-H "Content-Type: application/json" \
-d '{"prompt": "What is 2+3?", "max_new_tokens": 32}'
# => {"answer":"5","device":"npu:0",...}本模型的迁移过程(对照 assets/agent_workflow.png)包含以下适配点:
inference.py 顶部)import torch_npu # 注册昇腾 NPU 后端
from torch_npu.contrib import transfer_to_npu # CUDA API → NPU API 自动映射本环境未安装 flash_attn(CUDA 专用),显式指定 transformers eager 注意力,纯 PyTorch 算子在 NPU 上直接执行:
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
MODEL_PATH, torch_dtype=torch.bfloat16, attn_implementation="eager"
).to("npu:0")模型目录缺少 vocab.json / tokenizer.json(仅含 merges.txt),需复用同系列 Qwen2.5-VL tokenizer:
# 从本地 Qwen2.5-VL 系列模型复制(词表 151643,special tokens 一致)
cp <qwen2.5-vl-dir>/vocab.json <model-dir>/vocab.json
cp <qwen2.5-vl-dir>/tokenizer.json <model-dir>/tokenizer.json校验:eos=<|im_end|>、pad=<|endoftext|> 与模型 config 一致。
Qwen2.5-VL 要求 prompt 中包含图像占位符,使用 chat template 自动注入:
messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": prompt}]}]
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = processor(text=text, images=image, return_tensors="pt")本机 transformers 的 masking_utils.py 被本地化修改为以 int 调用
past_key_values.get_mask_sizes(...),与 cache_utils.py(期望 Tensor)版本错配,
触发 'int' object has no attribute 'shape'。在脚本内以 monkey-patch 修复
(inference.py::_patch_cache_get_mask_sizes):
def _patched(self, cache_position, layer_idx):
if isinstance(cache_position, int):
cache_position = torch.arange(cache_position) # 语义等价
return _original(self, cache_position, layer_idx)| 指标 | NPU 实测 |
|---|---|
| 模型加载耗时 | ~4.5 s(16GB bf16 → npu:0) |
| 视觉问答输出 | 109 tokens(描述准确:红色背景、白色/蓝色形状) |
| 文本问答 | "5"(What is 2+3? 正确) |
| 推理设备 | Ascend910_9382 @ npu:0 |
| 接口测试 | /health /model_info /test_image /generate 全部通过 |
结论:VLM 多模态推理(图片理解 + 问答)在昇腾 NPU 端到端可用,服务化接口全部通过。
| 问题 | 解决方案 |
|---|---|
ValueError: Image features and image tokens do not match | 使用 7.4 节 chat template 注入图像占位符 |
TypeError: expected str... not NoneType(tokenizer 加载失败) | 模型目录缺 vocab.json,按 7.3 节补齐 |
AttributeError: 'int' object has no attribute 'shape' | 本环境 transformers 版本错配,7.5 节 monkey-patch 已内置 |
| 首次生成较慢 | 算子编译缓存,第二次起显著加速 |
| OOM | 单卡需 ≥ 32GB;可降低 max_new_tokens |
Qwen2_5_VLForConditionalGeneration)transfer_to_npu(from torch_npu.contrib import transfer_to_npu)