-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodel_builders.py
More file actions
executable file
·627 lines (495 loc) · 37.9 KB
/
model_builders.py
File metadata and controls
executable file
·627 lines (495 loc) · 37.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
# Description: This file contains the code to build the model and collator for each of the baseline models.
#================================================================
# Qwen-2.5-VL Model
#================================================================
class QwenCollator:
def __init__(self, processor, args, process_vision_info, train=False):
multi_image_prompts = {
"sequence_filling": "Pick the panel from the options that best fits the context space marked as MASK in the context. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"char_coherence": "Pick the panel from the options that best fits the context space marked as MASK in the context. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"visual_closure": "Pick the panel from the options that best fits the context space marked as MASK in the context. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"text_closure": "Pick the panel from the options that best fits the context space marked as MASK in the context. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"caption_relevance": "Pick the panel from the options that best follows the context caption. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
}
single_image_prompts = {
"sequence_filling": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"char_coherence": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"visual_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"text_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"caption_relevance": "Pick A Panel Task: In the image you have a row of comic panels. From the options pick the panel that best follows the context caption. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
}
train_single_image_prompts = {
"sequence_filling": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"char_coherence": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"visual_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"text_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"caption_relevance": "Pick A Panel Task: In the image you have a row of comic panels. From the options pick the panel that best follows the context caption. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
}
self.processor = processor
self.train = train
self.process_vision_info = process_vision_info
if self.train:
self.prompts = multi_image_prompts if not args.single_image else train_single_image_prompts
self.build_message = self._build_train_message_multi_panel if not args.single_image else self._build_train_message_single_image
else:
#self.prompts = multi_image_prompts if not args.single_image else single_image_prompts
self.prompts = multi_image_prompts if not args.single_image else train_single_image_prompts
self.build_message = self._build_message_multi_panel if not args.single_image else self._build_message_single_image
def _build_message_multi_panel(self, batch):
messages = []
for sample in batch:
message = {
"role": "user",
"content": [
{"type": "text", "text": self.prompts[sample["task_type"]]},
{"type": "text", "text": f"context: {sample['previous_panel_caption']}"}, # previous panel caption is empty in all skills except for caption_relevance
],
}
i = 0
for image in sample["context"]:
message["content"].append({"type": "text", "text": f"\n{i}:"})
if i == sample["index"]:
message["content"].append({"type": "text", "text": "MASK"})
i += 1
message["content"].append({"type": "text", "text": f"\n{i}:"})
message["content"].append({"type": "image", "image": image})
else:
message["content"].append({"type": "image", "image": image})
i += 1
message["content"].append({"type": "text", "text": "\n\noptions: "})
for i, image in enumerate(sample["options"]):
message["content"].append({"type": "text", "text": f" \n{i}:"})
message["content"].append({"type": "image", "image": image})
messages.append([message])
return messages
def _build_message_single_image(self, batch):
messages = []
for sample in batch:
message = {
"role": "user",
"content": [
{"type": "text", "text": self.prompts[sample["task_type"]]},
{"type": "text", "text": f"context: {sample['previous_panel_caption']}"}, # previous panel caption is empty in all skills except for caption_relevance
{"type": "image", "image": sample["single_image"]},
],
}
messages.append([message])
return messages
def _build_train_message_multi_panel(self, batch):
raise NotImplementedError
def _build_train_message_single_image(self, batch):
messages = []
for sample in batch:
message = {
"role": "user",
"content": [
{"type": "text", "text": self.prompts[sample["task_type"]]},
{"type": "text", "text": f"context: {sample['previous_panel_caption']}"}, # previous panel caption is empty in all skills except for caption_relevance
{"type": "image", "image": sample["single_image"]},
],
}
answer = {
"role": "assistant",
"content": [
{"type": "text", "text": f"answer: {sample['solution_index']}"},
],
}
messages.append([message, answer])
return messages
def __call__(self, batch):
messages = self.build_message(batch)
text = self.processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=False if self.train else True)
image_inputs, video_inputs = self.process_vision_info(messages)
inputs = self.processor(
text=text,
images=image_inputs,
videos=video_inputs,
padding=True,
padding_side='left',
truncation=True,
return_tensors="pt",
)
if self.train:
labels = inputs["input_ids"].clone()
labels[labels == self.processor.tokenizer.pad_token_id] = -100
image_tokens = [151652, 151653, 151654, 151655] # image tokens
for image_token_id in image_tokens:
labels[labels == image_token_id] = -100
inputs["labels"] = labels
return inputs
else:
return inputs, dict(labels=[sample["solution_index"] for sample in batch], sample_ids=[sample["sample_id"] for sample in batch], messages=messages)
def build_qwen(args):
import torch
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info
if 'lora' in args.model:
model_path = args.model.split('_lora')[0] if '_' in args.model else args.model.split('-lora')[0]
else:
model_path = args.model
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
device_map='auto' if args.max_steps == 0 else None
)
if 'lora' in args.model:
model.load_adapter(args.model)
processor = AutoProcessor.from_pretrained(model_path)
collator = QwenCollator(processor, args, process_vision_info)
if args.max_steps != 0:
train_collator = QwenCollator(processor, args, process_vision_info, train=True)
return model, collator, train_collator
return model, collator
#================================================================
# SmolVLM Model
#================================================================
class SmolVLMCollator:
def __init__(self, processor, args, train=False):
multi_image_prompts = {
"sequence_filling": "Pick the panel from the options that best fits the context space marked as MASK in the context. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"char_coherence": "Pick the panel from the options that best fits the context space marked as MASK in the context. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"visual_closure": "Pick the panel from the options that best fits the context space marked as MASK in the context. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"text_closure": "Pick the panel from the options that best fits the context space marked as MASK in the context. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"caption_relevance": "Pick the panel from the options that best follows the context caption. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
}
single_image_prompts = {
"sequence_filling": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"char_coherence": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"visual_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"text_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"caption_relevance": "Pick A Panel Task: In the image you have a row of comic panels. From the options pick the panel that best follows the context caption. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
}
train_single_image_prompts = {
"sequence_filling": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"char_coherence": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"visual_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"text_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"caption_relevance": "Pick A Panel Task: In the image you have a row of comic panels. From the options pick the panel that best follows the context caption. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
}
single_image_prompts_simple = {
"sequence_filling": "Which panel from the bottom row best fits the missing panel spot in the top row? Reply with a number. \n\n",
"char_coherence": "Which panel from the bottom row best fits the missing panel spot in the top row? Reply with a number. \n\n",
"visual_closure": "Which panel from the bottom row best fits the missing panel spot in the top row? Reply with a number. \n\n",
"text_closure": "Which panel from the bottom row best fits the missing panel spot in the top row? Reply with a number. \n\n",
"caption_relevance": "Which panel best follows the context caption? Reply with a number. \n\n",
}
self.train = train
self.create_images_list = self._create_images_list_multi_panel if not args.single_image else self._create_images_list_single_image
self.processor = processor
self.image_token_id = processor.tokenizer.convert_tokens_to_ids('<image>')
if self.train:
self.prompts = multi_image_prompts if not args.single_image else train_single_image_prompts
self.build_message = self._build_train_message_multi_panel if not args.single_image else self._build_train_message_single_image
else:
#self.prompts = multi_image_prompts if not args.single_image else single_image_prompts
self.prompts = multi_image_prompts if not args.single_image else train_single_image_prompts
self.build_message = self._build_message_multi_panel if not args.single_image else self._build_message_single_image
def _create_images_list_multi_panel(self, batch):
images = []
for sample in batch:
images.extend(sample["context"])
images.extend(sample["options"])
del sample["context"]
del sample["options"]
return images
def _create_images_list_single_image(self, batch):
return [sample["single_image"] for sample in batch]
def _build_message_multi_panel(self, batch):
messages = []
for sample in batch:
message = {
"role": "user",
"content": [
{"type": "text", "text": self.prompts[sample["task_type"]]},
{"type": "text", "text": f"context: {sample['previous_panel_caption']}"}, # previous panel caption is empty in all skills except for caption_relevance
],
}
i = 0
for image in sample["context"]:
message["content"].append({"type": "text", "text": f"\n{i}:"})
if i == sample["index"]:
message["content"].append({"type": "text", "text": "MASK"})
i += 1
message["content"].append({"type": "text", "text": f"\n{i}:"})
message["content"].append({"type": "image"})
else:
message["content"].append({"type": "image"})
i += 1
message["content"].append({"type": "text", "text": "\n\noptions: "})
for i, image in enumerate(sample["options"]):
message["content"].append({"type": "text", "text": f" \n{i}:"})
message["content"].append({"type": "image"})
messages.append([message])
return messages
def _build_message_single_image(self, batch):
messages = []
for sample in batch:
message = {
"role": "user",
"content": [
{"type": "text", "text": self.prompts[sample["task_type"]]},
{"type": "text", "text": f"context: {sample['previous_panel_caption']}"}, # previous panel caption is empty in all skills except for caption_relevance
{"type": "image"},
],
}
messages.append([message])
return messages
def _build_train_message_single_image(self, batch):
messages = []
for sample in batch:
message = {
"role": "user",
"content": [
{"type": "text", "text": self.prompts[sample["task_type"]]},
{"type": "text", "text": f"context: {sample['previous_panel_caption']}"}, # previous panel caption is empty in all skills except for caption_relevance
{"type": "image"},
],
}
answer = {
"role": "assistant",
"content": [
{"type": "text", "text": f"answer: {sample['solution_index']}"},
],
}
messages.append([message, answer])
return messages
def __call__(self, batch):
messages = self.build_message(batch)
text = self.processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = self.processor(
text=text,
images=self.create_images_list(batch),
padding=True,
padding_side='left',
truncation=True,
return_tensors="pt",
)
if self.train:
labels = inputs["input_ids"].clone()
labels[labels == self.processor.tokenizer.pad_token_id] = -100
image_tokens = [self.image_token_id] # image tokens
for image_token_id in image_tokens:
labels[labels == image_token_id] = -100
inputs["labels"] = labels
return inputs
else:
return inputs, dict(labels=[sample["solution_index"] for sample in batch], sample_ids=[sample["sample_id"] for sample in batch], messages=messages)
def build_smolvlm(args):
import torch
from transformers import AutoProcessor, AutoModelForImageTextToText
processor = AutoProcessor.from_pretrained(args.model)
model = AutoModelForImageTextToText.from_pretrained(
args.model,
torch_dtype=torch.bfloat16,
_attn_implementation="flash_attention_2",
device_map='auto' if args.max_steps == 0 else None
)
collator = SmolVLMCollator(processor, args)
if args.max_steps != 0:
train_collator = SmolVLMCollator(processor, args, train=True)
return model, collator, train_collator
return model, collator
#================================================================
# Llama Vision Model
#================================================================
class LlamaCollator:
def __init__(self, processor, args):
multi_image_prompts = {}
single_image_prompts = {
"sequence_filling": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"char_coherence": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"visual_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"text_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"caption_relevance": "Pick A Panel Task: In the image you have a row of comic panels. From the options pick the panel that best follows the context caption. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
}
self.prompts = multi_image_prompts if not args.single_image else single_image_prompts
self.processor = processor
self.build_message = self._build_message_multi_panel if not args.single_image else self._build_message_single_image
self.create_images_list = self._create_images_list_multi_panel if not args.single_image else self._create_images_list_single_image
def _create_images_list_multi_panel(self, batch):
images = []
for sample in batch:
images.extend(sample["context"])
images.extend(sample["options"])
return images
def _create_images_list_single_image(self, batch):
return [sample["single_image"] for sample in batch]
def _build_message_multi_panel(self, batch):
raise NotImplementedError("Llama model does not support multi images")
def _build_message_single_image(self, batch):
messages = []
for sample in batch:
message = {
"role": "user",
"content": [
{"type": "text", "text": self.prompts[sample["task_type"]]},
{"type": "text", "text": f"context: {sample['previous_panel_caption']}"}, # previous panel caption is empty in all skills except for caption_relevance
{"type": "image"},
],
}
messages.append([message])
return messages
def __call__(self, batch):
messages = self.build_message(batch)
text = self.processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = self.processor(
text=text,
images=self.create_images_list(batch),
padding=True,
padding_side='left',
truncation=True,
return_tensors="pt",
)
return inputs, dict(labels=[sample["solution_index"] for sample in batch], sample_ids=[sample["sample_id"] for sample in batch], messages=messages)
def build_llama(args):
import torch
from transformers import AutoProcessor, MllamaForConditionalGeneration
processor = AutoProcessor.from_pretrained(args.model)
model = MllamaForConditionalGeneration.from_pretrained(
args.model,
torch_dtype=torch.bfloat16,
device_map='auto'
).to("cuda")
collator = LlamaCollator(processor, args)
return model, collator
#================================================================
# Paligemma Model
#================================================================
class PaliGemmaCollator:
def __init__(self, processor, args, train=False):
single_image_prompts = {
"sequence_filling": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"char_coherence": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"visual_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"text_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
"caption_relevance": "Pick A Panel Task: In the image you have a row of comic panels. From the options pick the panel that best follows the context caption. You can reason about your answer, but you must return your final answer as a number with 'answer: <your answer here>'\n\n",
}
self.processor = processor
self.train = train
self.prompts = single_image_prompts
def __call__(self, batch):
messages = []
for sample in batch:
message = self.prompts[sample["task_type"]]
if sample["task_type"] == "caption_relevance":
message.format(caption=sample["previous_panel_caption"])
messages.append(message)
inputs = self.processor(text=messages, images=[sample["single_image"] for sample in batch], return_tensors="pt", padding="longest")
return inputs, dict(labels=[sample["solution_index"] for sample in batch], sample_ids=[sample["sample_id"] for sample in batch], messages=messages)
def build_paligemma(args):
import torch
from transformers import PaliGemmaProcessor, PaliGemmaForConditionalGeneration
model = PaliGemmaForConditionalGeneration.from_pretrained(
args.model,
torch_dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
device_map='auto' if args.max_steps == 0 else None
)
processor = PaliGemmaProcessor.from_pretrained(args.model)
collator = PaliGemmaCollator(processor, args)
return model, collator
#================================================================
# Molmo Model
#================================================================
class MolmoCollator:
def __init__(self, processor, args, train=False):
single_image_prompts = {
"sequence_filling": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"char_coherence": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"visual_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"text_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"caption_relevance": "Pick A Panel Task: In the image you have a row of comic panels. From the options pick the panel that best follows the context caption. You must return your final answer as a number with 'answer: <your answer here>'",
}
self.processor = processor
self.train = train
self.prompts = single_image_prompts
def __call__(self, batch):
assert len(batch) == 1, "Molmo only supports single sample batches. Why? Beats me, I started modifying their processor to support batches, but I was too lazy to finish it."
sample = batch[0]
message = self.prompts[sample["task_type"]]
if sample["task_type"] == "caption_relevance":
message += f"context: {sample["previous_panel_caption"]}\n\n"
inputs = self.processor.process(text=message, images=[sample["single_image"]], return_tensors="pt", padding="longest")
return inputs, dict(labels=[sample["solution_index"] for sample in batch], sample_ids=[sample["sample_id"] for sample in batch])
def build_molmo(args):
import transformers
assert transformers.__version__ == "4.43.3", "Molmo does not work with newer versions of transformers"
import torch
from transformers import AutoModelForCausalLM, AutoProcessor
model = AutoModelForCausalLM.from_pretrained(
args.model,
torch_dtype=torch.float32,
device_map='auto' if args.max_steps == 0 else None,
trust_remote_code=True,
)
processor = AutoProcessor.from_pretrained(args.model, trust_remote_code=True)
collator = MolmoCollator(processor, args)
return model, collator
#================================================================
# MiniCPM Model
#================================================================
class MiniCPMCollator:
def __init__(self, processor, args, train=False):
single_image_prompts = {
"sequence_filling": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"char_coherence": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"visual_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"text_closure": "Pick A Panel Task: In the image you have two rows of comic panels. The top row is the context and the bottom row is the options. The context row has a missing panel marked with a question mark. Choose the option that best fits the missing panel. You must return your final answer as a number with 'answer: <your answer here>'\n\n",
"caption_relevance": "Pick A Panel Task: In the image you have a row of comic panels. From the options pick the panel that best follows the context caption. You must return your final answer as a number with 'answer: <your answer here>'",
}
self.processor = processor
self.train = train
self.prompts = single_image_prompts
def __call__(self, batch):
assert len(batch) == 1, "MiniCPM model only supports single sample batches. Why? I don't know!!!!! People use batches right? Or am I the crazy one?"
sample = batch[0]
message = self.prompts[sample["task_type"]]
if sample["task_type"] == "caption_relevance":
message += f"context: {sample["previous_panel_caption"]}\n\n"
message = [{'role': 'user', 'content': message}]
images = sample["single_image"]
inputs = {
"msgs": message,
"image": images,
"context": None
}
return inputs, dict(labels=[sample["solution_index"] for sample in batch], sample_ids=[sample["sample_id"] for sample in batch], messages=message)
def build_minicpm(args):
import transformers
assert transformers.__version__ == "4.36.0", "MiniCPM does not work with newer versions of transformers"
import torch
from transformers import AutoModel, AutoProcessor
model = AutoModel.from_pretrained(
args.model,
torch_dtype=torch.float32,
attn_implementation="flash_attention_2",
device_map='auto' if args.max_steps == 0 else None,
trust_remote_code=True,
)
processor = AutoProcessor.from_pretrained(args.model, trust_remote_code=True)
collator = MiniCPMCollator(processor, args)
return model, collator
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--model", type=str, required=True)
parser.add_argument("--hf_repo", type=str, required=True)
args = parser.parse_args()
args.max_steps = 0
args.single_image = True
if "qwen" in args.model.lower():
model, collator = build_qwen(args)
elif "smolvlm" in args.model.lower():
model, collator = build_smolvlm(args)
elif "llama" in args.model.lower():
model, collator = build_llama(args)
elif "paligemma" in args.model.lower():
model, collator = build_paligemma(args)
elif "molmo" in args.model.lower():
model, collator = build_molmo(args)
elif "minicpm" in args.model.lower():
model, collator = build_minicpm(args)
else:
raise ValueError("Model not supported")
model.push_to_hub(args.hf_repo)