본문으로 이동

FastVLM 설치 및 첫 실행

브라우저에서는 이미지 데모를 사용하세요. 로컬 Python 환경에서는 아래 순서로 실행할 수 있습니다.

1. Python 환경 준비

Python 3.10 이상을 사용하세요. Transformers 5.0.0은 FastVLM을 기본 지원합니다. 이 예제는 Hugging Face 문서의 커뮤니티 변환 모델인 KamilaMila/FastVLM-0.5B를 사용하며, Apple의 원본 ZIP과 로딩 방식이 다릅니다.

macOS / Linux
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 "이 이미지를 설명해 주세요."

2. 이미지로 질문하기

이미지를 image.png로 저장하고 실행하세요. 처음에는 모델을 다운로드합니다. 성공하면 생성된 답변이 터미널에 표시됩니다. CUDA, Apple MPS, CPU 중 사용 가능한 장치를 선택하며 CPU에서는 느릴 수 있습니다.

fastvlm_transformers.py
"""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()
Python 스크립트 다운로드

3. Mac / iPhone 공식 앱

macOS 15.2+ 또는 iOS 18.2+와 호환 Xcode가 필요합니다. 모델 폴더가 비어 있는 상태에서 모델을 다운로드한 뒤 Xcode로 열어 실행하세요.

Apple Silicon
git clone https://github.com/apple-aiml-research/ml-fastvlm.git
cd ml-fastvlm
chmod +x app/get_pretrained_mlx_model.sh
app/get_pretrained_mlx_model.sh --model 0.5b --dest app/FastVLM/model
open app/FastVLM/FastVLM.xcodeproj

문제가 생기면

2026-09-12 출처 확인 · Transformers 문서 · Apple 앱 문서