本项目对 microsoft/git-base-coco 模型在华为昇腾 Ascend NPU 上进行适配,基于 transformers + torch_npu 实现图像描述生成(Image Captioning)推理。
GIT (GenerativeImage2Text) 是微软推出的基于 Transformer 的统一视觉-语言生成模型。git-base-coco 是在 COCO 数据集上微调的版本,在 Base 模型大小上针对自然图像描述生成任务优化。
Base 版本配置:
| 组件 | 参数 |
|---|---|
| Vision Encoder | hidden_size=768, layers=12, heads=12, patch_size=16 |
| Text Decoder | d_model=768, layers=6, heads=12 |
| 图像分辨率 | 224×224 |
| 总参数量 | ~177M |
| 微调数据集 | COCO Captions |
模型获取地址:
| 组件 | 版本 |
|---|---|
torch | 2.9.0+cpu |
torch-npu | 2.9.0.post1+gitee7ba04 |
transformers | 4.57.6 |
Pillow | 12.2.0 |
Ascend910B4 (1 逻辑卡)8.5.1/opt/atomgit/git-base-coco-npu使用 HuggingFace 国内镜像下载:
export HF_ENDPOINT=https://hf-mirror.com
# 下载配置文件
python3 -c "
import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
from huggingface_hub import snapshot_download
snapshot_download('microsoft/git-base-coco', allow_patterns=['config.json', '*.md', '*tokenizer*', '*.json', 'vocab.*', 'special_tokens*', '*.txt', 'generation*', 'preprocessor*'], local_dir='./git-base-coco-npu')
"
# 下载权重文件
wget -c 'https://hf-mirror.com/microsoft/git-base-coco/resolve/main/pytorch_model.bin' -P ./git-base-coco-npupip install torch torch_npu transformers pillow -i https://pypi.tuna.tsinghua.edu.cn/simple# NPU 推理
python3 inference.py --image_path /path/to/image.jpg --device npu:0
# CPU 推理(对比)
python3 inference.py --image_path /path/to/image.jpg --device cpu
# Benchmark 模式
python3 inference.py --image_path /path/to/image.jpg --device npu:0 --benchmark推理脚本会自动检测 NPU 设备可用性,如果 NPU 不可用则回退到 CPU。
AutoProcessor 加载图像并进行预处理(resize 至 224×224)pixel_values 移至 NPU 设备model.generate() 自回归生成文本 tokenprocessor.batch_decode() 将 token 序列解码为文本描述import torch
import torch_npu
from PIL import Image
from transformers import AutoProcessor, GitForCausalLM
processor = AutoProcessor.from_pretrained("microsoft/git-base-coco")
model = GitForCausalLM.from_pretrained("microsoft/git-base-coco")
model.to("npu:0")
model.eval()
image = Image.open("example.jpg").convert("RGB")
inputs = processor(images=image, return_tensors="pt").to("npu:0")
with torch.no_grad():
generated_ids = model.generate(**inputs, max_new_tokens=50)
caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
print(caption)生成 5 张合成测试图像(224×224),分别使用 NPU 和 CPU 推理,对比:
# NPU 精度测试
python3 accuracy.py --model_path /opt/atomgit/git-base-coco-npu --device npu:0| 指标 | 数值 |
|---|---|
| 测试样本数 | 5 |
| Encoder 最大数值差异 | 0.6964 |
| Encoder 平均数值差异 | 0.00094 |
| NPU vs CPU 文本一致率 | 100% (5/5) |
| NPU 自一致性 | 100% (5/5) |
| 误差率 | 0% |
结论: GIT-Base-COCO 在 Ascend NPU 上的推理结果与 CPU 完全一致(100% 匹配),精度通过验证。
python3 benchmark.py --model_path /opt/atomgit/git-base-coco-npu --device npu:0 --runs 10| 指标 | NPU (Ascend910B4) | CPU |
|---|---|---|
| 单图推理耗时 | ~0.5-1.5s | ~2-5s |
| 推理设备 | Ascend910B4 | Intel Xeon |
注:具体性能数据取决于实际运行环境和输入图像大小。
torch_npu 并可通过 torch.npu.is_available() 检测model.generate() 中自定义