Views
No views yet
1import torch
2from transformers import AutoProcessor, AutoModelForImageTextToText
3from peft import PeftModel
4from PIL import Image
5import requests
6
7# 1) Load base model + processor, then apply the LoRA adapter
8base_model_id = "HuggingFaceTB/SmolVLM2-256M-Video-Instruct"
9adapter_model_id = "berkeruveyik/smolvlm2-256m-FoodExtract-Vision-v1" # Replace with your model ID
10
11print("Loading processor and base model...")
12processor = AutoProcessor.from_pretrained(base_model_id)
13model = AutoModelForImageTextToText.from_pretrained(
14 base_model_id,
15 torch_dtype=torch.bfloat16,
16 device_map="auto",
17)
18
19print("Loading LoRA adapter...")
20model = PeftModel.from_pretrained(model, adapter_model_id)
21model.eval()
22print("Model ready!")
23
24# 2) Prompts
25SYSTEM_MESSAGE = """You are an expert food and drink image extractor.
26You provide structured data to visual inputs classifying them as edible food/drink or not.
27as well as titling the image with a simple simple food/drink related caption.
28Finally you extract any and all visible food/drink items to lists."""
29
30USER_PROMPT = """Classify the given input image into food or not, and if edible food or drink items are present, extract them into lists. If no food/drink items are visible, return an empty list.
31
32Only return valid JSON in the following form:
33
34```json
35{
36 "is_food": 0,
37 "image_title": "",
38 "food_items": [],
39 "drink_items": []
40}
41```"""
42
43# 3) Load image
44image_url = "https://img.freepik.com/free-psd/roasted-chicken-dinner-platter-delicious-feast_632498-25445.jpg"
45
46print(f"\nLoading image from: {image_url}")
47resp = requests.get(image_url, stream=True, headers={"User-Agent": "Mozilla/5.0"})
48resp.raise_for_status()
49image = Image.open(resp.raw).convert("RGB")
50
51# 4) Prepare inputs
52messages = [
53 {
54 "role": "user",
55 "content": [
56 {"type": "image", "image": image},
57 {"type": "text", "text": SYSTEM_MESSAGE + "\n\n" + USER_PROMPT},
58 ],
59 }
60]
61
62text = processor.apply_chat_template(
63 messages,
64 add_generation_prompt=True,
65 tokenize=False,
66)
67
68inputs = processor(
69 text=text,
70 images=image,
71 return_tensors="pt",
72)
73
74# Move tensors to model device and dtype
75inputs = {k: v.to(model.device) for k, v in inputs.items()}
76inputs = {
77 k: (v.to(dtype=model.dtype) if torch.is_floating_point(v) and v.dtype == torch.float32 else v)
78 for k, v in inputs.items()
79}
80
81# 5) Generate
82print("\nGenerating output...")
83with torch.no_grad():
84 generated_ids = model.generate(**inputs, max_new_tokens=256, do_sample=False)
85
86# 6) Decode only the newly generated tokens
87prompt_len = inputs["input_ids"].shape[1]
88output_text = processor.batch_decode(
89 generated_ids[:, prompt_len:],
90 skip_special_tokens=True
91)[0]
92
93print("\n" + "="*60)
94print("OUTPUT:")
95print("="*60)
96print(output_text)
97print("="*60)1@misc{vonwerra2022trl,
2 title = {{TRL: Transformer Reinforcement Learning}},
3 author = {Leandro von Werra and Younes Belkada and Lewis Tunstall and Edward Beeching and Tristan Thrush and Nathan Lambert and Shengyi Huang and Kashif Rasul and Quentin Gallou{\'e}dec},
4 year = 2020,
5 journal = {GitHub repository},
6 publisher = {GitHub},
7 howpublished = {\url{[https://github.com/huggingface/trl](https://github.com/huggingface/trl)}}
8}
9
10@misc{mangrulkar2022peft,
11 title = {PEFT: State-of-the-art Parameter-Efficient Fine-Tuning methods},
12 author = {Sourab Mangrulkar and Sylvain Gugger and Lysandre Debut and Younes Belkada and Sayak Paul and Benjamin Bossan},
13 year = {2022},
14 publisher = {Hugging Face},
15 howpublished = {\url{[https://github.com/huggingface/peft](https://github.com/huggingface/peft)}},
16}