运行前准备
使用 Python 3.10+ 创建新环境。示例固定使用已包含 FastVLM 原生支持的 Transformers 5.0.0。安装适合硬件的 PyTorch;脚本会选择 CUDA、Apple MPS 或 CPU。CPU 推理可能较慢。
模型文件必须匹配运行库
apple/FastVLM-* 是 Apple 发布的文件。原生 Transformers 示例使用其文档引用的社区转换版 KamilaMila/FastVLM-0.5B;浏览器使用 onnx-community/FastVLM-0.5B-ONNX。先选运行方式,再下载对应的兼容文件。
python -m venv .venv
source .venv/bin/activate
python -m pip install "transformers==5.0.0" "timm==1.0.29" torch pillow
curl -fLO https://fastvlm.net/examples/fastvlm_transformers.py
python fastvlm_transformers.py image.png --prompt "Describe this image." 检查首次运行结果
将图片保存为 image.png,执行下方命令。成功后只会输出生成的回答。检查回答是否对应图片和问题;不同设备和版本下的文字可能不同。
常见问题
- 无法导入 FastVlmForConditionalGeneration:确认使用的是安装了 Transformers 5.0.0 的环境。
- 模型下载失败:检查 Hugging Face 网络连接与磁盘空间;首次加载需要下载权重。
- 内存不足:改用 0.5B、关闭其他 GPU 任务,并缩短输出长度。
- 回答混入原始问题:按示例只解码 input_ids 之后新生成的 token。
来源核对于 2026-09-12。实际运行性能取决于设备。
操作步骤
- 1
安装已包含 FastVLM 支持的 Transformers 版本。
- 2
加载兼容模型与 AutoProcessor。
- 3
用独立的 image 与 text 内容项构造消息。
- 4
调用 generate 前使用 apply_chat_template;不能只传普通字符串。
示例
"""Single-image FastVLM inference using the native Transformers integration.
Setup: python -m pip install 'transformers==5.0.0' 'timm==1.0.29' torch pillow
Run: python fastvlm_transformers.py image.png --prompt 'What is in this image?'
Source: https://huggingface.co/docs/transformers/model_doc/fast_vlm
The default is a community conversion used by that guide, not Apple's original ZIP.
"""
import argparse
from pathlib import Path
import torch
from transformers import AutoConfig, AutoProcessor, FastVlmForConditionalGeneration
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('image', type=Path)
parser.add_argument('--prompt', default='Describe this image briefly.')
parser.add_argument('--model', default='KamilaMila/FastVLM-0.5B')
args = parser.parse_args()
if not args.image.is_file():
parser.error('The image file does not exist.')
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
dtype = torch.float16 if device == 'cuda' else torch.float32
config = AutoConfig.from_pretrained(args.model)
if args.model == 'KamilaMila/FastVLM-0.5B':
# This older conversion records weight tying only in text_config.
# Transformers 5 also needs it on the outer config to restore lm_head.
config.tie_word_embeddings = config.text_config.tie_word_embeddings
model = FastVlmForConditionalGeneration.from_pretrained(args.model, config=config, dtype=dtype).to(device).eval()
processor = AutoProcessor.from_pretrained(args.model, use_fast=False)
messages = [{'role': 'user', 'content': [
{'type': 'image', 'path': str(args.image.resolve())},
{'type': 'text', 'text': args.prompt},
]}]
inputs = processor.apply_chat_template(
messages, add_generation_prompt=True, tokenize=True,
return_dict=True, return_tensors='pt',
).to(device)
if 'pixel_values' in inputs:
inputs['pixel_values'] = inputs['pixel_values'].to(dtype=dtype)
# Qwen chat turns may end with im_end instead of the legacy endoftext.
stop_tokens = [processor.tokenizer.eos_token_id]
chat_end = processor.tokenizer.get_vocab().get('<|im_end|>')
if chat_end is not None:
stop_tokens.append(chat_end)
with torch.inference_mode():
output = model.generate(
**inputs, max_new_tokens=192, do_sample=False, repetition_penalty=1.2,
eos_token_id=stop_tokens,
pad_token_id=processor.tokenizer.pad_token_id,
)
answer = output[:, inputs['input_ids'].shape[1]:]
print(processor.batch_decode(answer, skip_special_tokens=True)[0].strip())
if __name__ == '__main__':
main()
修复实际遇到的首次运行问题
这些问题在本站使用 KamilaMila/FastVLM-0.5B、Transformers 5.0.0 和 timm 1.0.29 的测试中复现。下方共享权重修复只针对该旧转换版本;其他 checkpoint 的配置可能不同。
模型加载成功,但回答是乱码
先检查加载报告是否提示缺少 lm_head.weight。此转换版把 tie_word_embeddings 放在 text_config 内,Transformers 5.0.0 还需要外层配置才能恢复共享输出权重。应像完整下载脚本一样,在加载前设置。
config = AutoConfig.from_pretrained(model_id)
if model_id == "KamilaMila/FastVLM-0.5B":
config.tie_word_embeddings = config.text_config.tie_word_embeddings
model = FastVlmForConditionalGeneration.from_pretrained(
model_id, config=config, dtype=dtype
) 回答重复,或继续生成下一轮对话
旧配置以 endoftext 为结束标记。存在 Qwen im_end 时也应将它作为结束 token,并限制新增 token 数,只解码输入之后的生成内容。重复惩罚能缓解重复,但不会提高事实准确性。
找不到 timm 或 FastVlmForConditionalGeneration
确认安装依赖与执行脚本使用同一个环境。视觉编码器需要 timm,较旧的 Transformers 可能没有原生 FastVLM 类。
python -m pip install "transformers==5.0.0" "timm==1.0.29" torch pillow
python -c "import sys, transformers, timm; print(sys.executable, transformers.__version__, timm.__version__)" 权重下载长时间不动
检查磁盘空间和 Hugging Face 网络连接。本站验证时遇到 Xet 传输停滞,通过 HF_HUB_DISABLE_XET=1 切到 HTTP 路径后下载成功;它不能解决所有网络或权限问题。
HF_HUB_DISABLE_XET=1 python fastvlm_transformers.py image.png 2026-09-12 验证:完整脚本对合成收据输出 $15.00。其他图片和运行环境仍需单独检查。