Before you run
Use Python 3.10+ in a new environment. This example pins Transformers 5.0.0, which includes native FastVLM support. Install a PyTorch build appropriate for your hardware. The script chooses CUDA, Apple MPS or CPU; CPU inference can be slow.
Match the checkpoint to the library
apple/FastVLM-* contains Apple’s released model files. The native Transformers example uses KamilaMila/FastVLM-0.5B, the community conversion referenced by Hugging Face documentation. The browser uses onnx-community/FastVLM-0.5B-ONNX. Choose the runtime first, then its compatible files.
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." Check your first result
Save an image as image.png and run the command below. Success prints only the generated answer. Confirm that it describes the image and responds to your prompt; wording is not deterministic across devices and versions.
Troubleshooting
- ImportError for FastVlmForConditionalGeneration: check that the command uses the environment where Transformers 5.0.0 was installed.
- Model download fails: check Hugging Face connectivity and disk space; the first load downloads weights.
- Out of memory: use 0.5B, close other GPU workloads and reduce output length.
- Prompt copied into the answer: decode only tokens generated after input_ids, as this example does.
Source checked September 12, 2026. Runtime performance depends on your device.
Step by step
- 1
Install a Transformers version that includes FastVLM support.
- 2
Load a compatible model and AutoProcessor.
- 3
Build messages with separate image and text content items.
- 4
Use apply_chat_template before generate; a plain prompt string is not sufficient.
Example
"""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()
Fix real first-run failures
These cases were reproduced while testing KamilaMila/FastVLM-0.5B with Transformers 5.0.0 and timm 1.0.29 on this site. The workaround below is scoped to that older conversion; other checkpoints may have different configuration.
The model loads but answers are gibberish
Check the loading report for a missing lm_head.weight. This conversion stores tie_word_embeddings inside text_config; Transformers 5.0.0 also needs the outer setting to restore the shared output weights. Apply it before loading, as the downloadable script does.
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
) The answer keeps repeating or starts another turn
The legacy configuration stops on endoftext. Include the Qwen im_end chat marker when present, limit new tokens, and decode only tokens generated after the input. A repetition penalty can help, but it does not improve factual accuracy.
Missing timm or FastVlmForConditionalGeneration
Install dependencies in the same environment that runs the script. The vision backbone needs timm; an old Transformers version may not export the native FastVLM class.
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__)" Checkpoint download appears stuck
Check disk space and Hugging Face connectivity. During our validation an Xet transfer stalled; retrying with HF_HUB_DISABLE_XET=1 used the HTTP download path successfully. This does not resolve all network or permission failures.
HF_HUB_DISABLE_XET=1 python fastvlm_transformers.py image.png Verified on September 12, 2026: the complete script produced $15.00 for the synthetic receipt. Other images and runtimes require their own checks.
Verify against the primary source
APIs, model files and dependency versions can change. Treat this page as an implementation map, then confirm the current command and license in the linked official documentation.
Open official source