gcw_mXoV1I2Z/SmolVLM-256M-Instruct
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

SmolVLM-256M-Instruct · 昇腾NPU适配

SmolVLM-256M-Instruct 是 HuggingFaceTB 发布的轻量级视觉语言模型(VLM),架构为 Idefics3ForConditionalGeneration(transformers 原生支持)。本仓库将其适配到 昇腾 910 NPU(torch-npu),提供 CLI 与 FastAPI 双模式推理。

适配要点

  • CUDA 全量清理:无任何 torch.cuda / .cuda() / CUDA_VISIBLE_DEVICES 调用。
  • NPU 设备:import torch_npu + torch.npu.set_device(0),模型与输入全部 .to("npu:0"), 并用 try-except 捕获 NPU 初始化异常(失败时明确提示 CANN/torch-npu 环境问题)。
  • 算子兼容补丁:Idefics3 视觉编码器对 bf16 输入调用 torch.bucketize(searchsorted), NPU 该算子不支持 bf16;inference.py 中 monkey-patch torch.bucketize 将 bf16/fp16 输入转 fp32(输出仍为 int64,语义不变)。
  • 注意力实现:_attn_implementation="eager"(NPU 上不使用 flash_attention_2)。

环境

  • torch 2.9.0 + torch_npu 2.9.0.post1 + transformers 4.57.6
  • 依赖见 requirements.txt

使用

# CLI 单图推理
python inference.py --img <图片路径>

# FastAPI 服务
uvicorn inference:app --host 0.0.0.0 --port 8000
curl -F "file=@<图片路径>" http://127.0.0.1:8000/predict

权重

权重缓存于 ./model_weights/SmolVLM-256M-Instruct/(从 hf-mirror.com 镜像下载, .gitignore 已排除大权重文件,不随本仓库上传)。