Views
No views yet
| Type | Encoder | Decoder | IPU24-dataset (test) (Sentence SacreBLEU) |
|---|---|---|---|
| Pathumma-llm-vision-beta-0.0.0 | siglip-so400m-patch14-384 | Meta-Llama-3.1-8B-Instruct | 13.45412 |
| Pathumma-llm-vision-1.0.0 | siglip-so400m-patch14-384 | Meta-Llama-3.1-8B-Instruct | 17.66370 |
| Pathumma-llm-vision-2.0.0-preview | Qwen2-VL-7B-Instruct | Qwen2-VL-7B-Instruct | 19.112962 |
pip install transformers==4.48.1 accelerate peft bitsandbytes qwen-vl-utils[decord]==0.0.8transformers library:1import torch
2
3from peft import get_peft_model, LoraConfig
4from transformers import BitsAndBytesConfig
5from transformers import (
6 Qwen2VLForConditionalGeneration,
7 Qwen2VLProcessor,
8)1MODEL_ID = "nectec/Pathumma-llm-vision-2.0.0-preview"
2DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
3USE_QLORA = True
4
5lora_config = LoraConfig(
6 lora_alpha=16,
7 lora_dropout=0.05,
8 r=8,
9 bias="none",
10 target_modules=["q_proj", "v_proj"],
11 task_type="CAUSAL_LM",
12)
13
14if USE_QLORA:
15 bnb_config = BitsAndBytesConfig(
16 load_in_8bit=True,
17 # load_in_4bit=True,
18 # bnb_4bit_use_double_quant=True,
19 # bnb_4bit_quant_type="nf4",
20 # bnb_4bit_compute_type=torch.bfloat16
21 )
22
23
24model = Qwen2VLForConditionalGeneration.from_pretrained(
25 MODEL_ID,
26 device_map="auto",
27 quantization_config=bnb_config if USE_QLORA else None,
28 torch_dtype=torch.bfloat16
29)
30
31
32model = get_peft_model(model, lora_config)
33model.print_trainable_parameters()
34
35MIN_PIXELS = 256 * 28 * 28
36MAX_PIXELS = 1280 * 28 * 28
37
38processor = Qwen2VLProcessor.from_pretrained(MODEL_ID, min_pixels=MIN_PIXELS, max_pixels=MAX_PIXELS)
39
40def encode_via_processor(image, instruction, question):
41
42 if isinstance(image, str):
43 local_path = image
44 image = Image.open(local_path)
45
46 messages = [
47 {
48 "role": "system", "content": [{"type": "text", "text": instruction}]
49 },
50 {
51 "role": "user",
52 "content": [
53 {
54 "type": "image"
55 },
56 {
57 "type": "text",
58 "text": question
59 }
60 ]
61 },
62 ]
63
64 text = processor.apply_chat_template(
65 messages,
66 add_generation_prompt=True,
67 ).strip()
68
69 def convert_img(image):
70 width, height = image.size
71 factor = processor.image_processor.patch_size * processor.image_processor.merge_size
72 if width < factor:
73 image = image.copy().resize((factor, factor * height // width))
74 elif height < factor:
75 image = image.copy().resize((factor * width // height, factor))
76 return image
77 image_inputs = [convert_img(image)]
78
79 encoding = processor(
80 text=text,
81 images=image_inputs,
82 videos=None,
83 return_tensors="pt",
84 )
85
86 ## Remove batch dimension
87 # encoding = {k:v.squeeze(dim=0) for k,v in encoding.items()}
88 encoding = {k: v.to(DEVICE) for k, v in encoding.items()}
89 inputs = encoding
90 return inputs
91
92
93def encode_via_processor_extlib(local_path, instruction, question):
94 img_path = "file://" + local_path
95 messages = [
96 {
97 "role": "system", "content": [{"type": "text", "text": instruction}]
98 },
99 {
100 "role": "user",
101 "content": [
102 {
103 "type": "image",
104 "image": img_path,
105 },
106 {
107 "type": "text",
108 "text": question
109 }
110 ]
111 },
112 ]
113
114 text = processor.apply_chat_template(
115 messages,
116 add_generation_prompt=True,
117 ).strip()
118
119 image_inputs, video_inputs = process_vision_info(messages)
120
121 encoding = processor(
122 text=text,
123 images=image_inputs,
124 videos=video_inputs,
125 return_tensors="pt",
126 )
127
128 ## Remove batch dimension
129 # encoding = {k:v.squeeze(dim=0) for k,v in encoding.items()}
130 encoding = {k: v.to(DEVICE) for k, v in encoding.items()}
131 inputs = encoding
132 return inputs
133
134def inference(inputs):
135 start_time = time.time()
136 model.eval()
137 with torch.inference_mode():
138 # Generate
139 generated_ids = model.generate(
140 **inputs,
141 max_new_tokens=256,
142 temperature=.1,
143 # repetition_penalty=1.2,
144 # top_k=2,
145 # top_p=1,
146 )
147 generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
148 end_time = time.time()
149
150 ## Get letency_time...
151 latency_time = end_time - start_time
152
153 answer_prompt = [*map(
154 lambda x: re.sub(r"assistant(:|\n)?", "<||SEP-ASSIST||>", x).split('<||SEP-ASSIST||>')[-1].strip(),
155 generated_texts
156 )]
157 predict_output = generated_texts[0]
158 response = re.sub(r"assistant(:|\n)?", "<||SEP-ASSIST||>", predict_output).split('<||SEP-ASSIST||>')[-1].strip()
159
160 return predict_output, response, round(latency_time, 3)
161
162instruction = "You are a helpful assistant."
163
164def response_image(img_path, question, instruction=instruction):
165 image = Image.open(img_path)
166 _, response, latency_time = inference(encode_via_processor(image=image, instruction=instruction, question=question))
167 print("RESPONSE".center(60, "="))
168 print(response)
169 print(latency_time, "sec.")
170 print("IMAGE".center(60, "="))
171 plt.imshow(image)
172 plt.show()
173
174# Output processing (depends on task requirements)
175question = "อธิบายภาพนี้"
176img_path = "/content/The Most Beautiful Public High School in Every State in America.jpg"
177response_image(img_path, question)
178
179>>> ==========================RESPONSE==========================
180>>> อาคารสีน้ำตาลขนาดใหญ่ที่มีเสาไฟฟ้าอยู่ด้านหน้าและมีต้นไม้อยู่ด้านข้าง
181>>> 7.987 sec.
182>>> ===========================IMAGE============================
183>>> <IMAGE_MATPLOTLIB>1@misc{PathummaVision,
2 author = {Thirawarit Pitiphiphat and NECTEC Team},
3 title = {nectec/Pathumma-llm-vision-2.0.0-preview},
4 year = {2025},
5 url = {https://huggingface.co/nectec/Pathumma-llm-vision-2.0.0-preview}
6}1@article{Qwen2VL,
2 title={Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution},
3 author={Wang, Peng and Bai, Shuai and Tan, Sinan and Wang, Shijie and Fan, Zhihao and Bai, Jinze and Chen, Keqin and Liu, Xuejing and Wang, Jialin and Ge, Wenbin and Fan, Yang and Dang, Kai and Du, Mengfei and Ren, Xuancheng and Men, Rui and Liu, Dayiheng and Zhou, Chang and Zhou, Jingren and Lin, Junyang},
4 journal={arXiv preprint arXiv:2409.12191},
5 year={2024}
6}
7
8@article{Qwen-VL,
9 title={Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond},
10 author={Bai, Jinze and Bai, Shuai and Yang, Shusheng and Wang, Shijie and Tan, Sinan and Wang, Peng and Lin, Junyang and Zhou, Chang and Zhou, Jingren},
11 journal={arXiv preprint arXiv:2308.12966},
12 year={2023}
13}This formatting provides a clean, structured, and readable Markdown layout for these sections. Let me know if further adjustments are needed!