-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpredict.py
2092 lines (1843 loc) · 115 KB
/
predict.py
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import openai
import pandas as pd
import argparse
import random
import requests
from tqdm import tqdm
import numpy as np
from tenacity import (
retry,
stop_after_attempt,
wait_fixed,
)
import concurrent.futures
import torch
from PIL import Image
import requests
from lavis.models import load_model_and_preprocess
from transformers import T5Tokenizer, T5ForConditionalGeneration
from multimodal_eval_main.modeling import InstructBlipT5Model, BlipModel
from multimodal_eval_main.data_loading import MultimodalPart, MultimodalSequence
from multimodal_eval_main.modeling import FromageModel
from multimodal_eval_main.modeling import OpenFlamingoModel
import re
##Lavin
import sys
import time
from typing import Tuple
import json
import fairscale.nn.model_parallel.initialize as fs_init
import torch.distributed as dist
from pathlib import Path
from fairscale.nn.model_parallel.initialize import initialize_model_parallel as LaVIN_initialize_model_parallel
from multimodal_eval_main.models.LaVIN.lavin.eval_model import ModelArgs as LaVIN_ModelArgs, Transformer as LaVIN_Transformer
from multimodal_eval_main.models.LaVIN.lavin.tokenizer import Tokenizer as LaVIN_Tokenizer
from multimodal_eval_main.models.LaVIN.lavin.generator import LaVIN_Generator
from multimodal_eval_main.models.LaVIN.lavin.mm_adapter import set_MMAdapter as LaVIN_set_MMAdapter,set_Clip_Adapter as LaVIN_set_Clip_Adapter
from multimodal_eval_main.models.LaVIN.util.apply_delta import apply_model_delta_online
from torchvision.transforms import transforms
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
##for lynx_llm
from multimodal_eval_main.models.lynx_llm.models.lynx import LynxBase
import ruamel.yaml as yaml
from multimodal_eval_main.models.lynx_llm.dataset import create_dataset, create_loader
import csv
import datetime
## for mmgpt
from multimodal_eval_main.models.Multimodal_GPT.app import Inferencer as mmgpt_Inferencer
## for llama
from multimodal_eval_main.models.llama_recipes.inference.model_utils import load_model as load_model_for_llama, load_peft_model as load_peft_model_for_llama
from transformers.models.llama.tokenization_llama import LlamaTokenizer
## for mplug_owl
from transformers import AutoTokenizer
from multimodal_eval_main.models.mPLUG_Owl.mplug_owl.modeling_mplug_owl import MplugOwlForConditionalGeneration
from multimodal_eval_main.models.mPLUG_Owl.mplug_owl.processing_mplug_owl import MplugOwlImageProcessor, MplugOwlProcessor
##miniGPT4
from multimodal_eval_main.models.MiniGPT4.minigpt4.common.config import Config as minigpt4_Config
from multimodal_eval_main.models.MiniGPT4.minigpt4.common.dist_utils import get_rank
from multimodal_eval_main.models.MiniGPT4.minigpt4.common.registry import registry as miniGPT4_registry
from multimodal_eval_main.models.MiniGPT4.minigpt4.conversation.conversation import Chat as minigpt4_Chat, CONV_VISION as minigpt4_CONV_VISION
## for llama_adapter
from multimodal_eval_main.models.LLaMA_Adapter import llama as llama_adapter
import cv2
## for vpgtrans
from multimodal_eval_main.models.VPGTrans.lavis.common.config import Config as VPGTans_Config
from multimodal_eval_main.models.VPGTrans.lavis.common.dist_utils import get_rank
from multimodal_eval_main.models.VPGTrans.lavis.common.registry import registry as vpgtrans_registry
from multimodal_eval_main.models.VPGTrans.lavis.conversation.conversation import Chat as VPGTans_Chat, CONV_VISION as VPGTans_CONV_VISION
# imports modules for registration
from multimodal_eval_main.models.VPGTrans.lavis.datasets.builders import *
from multimodal_eval_main.models.VPGTrans.lavis.models import *
from multimodal_eval_main.models.VPGTrans.lavis.processors import *
from multimodal_eval_main.models.VPGTrans.lavis.runners import *
from multimodal_eval_main.models.VPGTrans.lavis.tasks import *
# llava
from multimodal_eval_main.models.LLaVA.llava.conversation import conv_templates, SeparatorStyle
from multimodal_eval_main.models.LLaVA.llava.utils import disable_torch_init
from transformers import CLIPVisionModel, CLIPImageProcessor, StoppingCriteria
from multimodal_eval_main.models.LLaVA.llava.model import *
from multimodal_eval_main.models.LLaVA.llava.model.utils import KeywordsStoppingCriteria
## chatgpt
from tenacity import (
retry,
stop_after_attempt,
wait_fixed,
)
DEFAULT_IMAGE_TOKEN = "<image>"
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
DEFAULT_IM_START_TOKEN = "<im_start>"
DEFAULT_IM_END_TOKEN = "<im_end>"
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
def get_parameter_number(model):
total_num = sum(p.numel() for p in model.parameters())
trainable_num = sum(p.numel() for p in model.parameters() if p.requires_grad)
return {'Total': total_num, 'Trainable': trainable_num}
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--num_workers", type=int, default=1, help="Number of samples to use, better under 3")
parser.add_argument("--setting", type=str, default="zero-shot", help="[zero-shot, few-shot, majority, random]")
parser.add_argument("--seed", type=int, default=42, help="[0, 1, 42]")
parser.add_argument("--shots", type=int, default=-1, help="[1, 5, 10]")
parser.add_argument('--use_api', action='store_true', help='use api or not')
parser.add_argument("--api", type=str, default=None, help="api key")
parser.add_argument("--selected_tasks", type=str, default=None, help="list of string of tasks, e.g '[\"sc\"]'")
parser.add_argument("--selected_datasets", type=str, default=None, help="list of string of datasets")
parser.add_argument("--ignored_datasets", type=str, default=None, help="list of string of datasets")
parser.add_argument("--model_name", type=str, default="blip2_t5", help="[blip2_t5, blip2_vicuna_instruct, instructblip]")
parser.add_argument("--model_type", type=str, default=None, help="[pretrain_flant5xxl, vicuna7b, flant5xxl]")
parser.add_argument("--skip_runned", action="store_true", help="skip runned dataset")
parser.add_argument("--root_path", type=str, default="multimodal_data", help="the path of multimodal data")
parser.add_argument("--test_path", type=str, default="test_0_10.csv", help="the path of multimodal data")
parser.add_argument("--prompt_type", type=str, default="1", help="the type of prompt")
parser.add_argument("--use_context", action="store_true", help="whether use context for ScienceQA")
parser.add_argument("--max_output_new_length", type=int, help="the length of max new generative tokens")
##for lavin
parser.add_argument("--ckpt_dir", type=str, default="/datas/multimodal_LLMs/LLaMA-7B", help="the path of checkpoint")
parser.add_argument("--tokenizer_path", type=str, default="/datas/multimodal_LLMs/LLaMA-7B/tokenizer.model", help="the path of tokenizer")
parser.add_argument("--adapter_path", type=str, default='/data/xiaocui/code/Multimodal_LLMs/LaVIN/weights/sqa-llama-7b.pth', help="the path of tokenizer")
parser.add_argument("--temperature", type=float, default=0.8, help="")
parser.add_argument("--generation_temperature", type=float, default=0.1, help="")
parser.add_argument("--n_prompt", type=int, default=6, help="")
parser.add_argument("--top_p", type=float, default=0.75, help="")
parser.add_argument("--max_seq_len", type=int, default=512, help="")
parser.add_argument("--max_gen_len", type=int, default=128, help="")
parser.add_argument("--max_batch_size", type=int, default=1, help="")
parser.add_argument("--local_rank", type=str, default="1", help="")
parser.add_argument("--llm_model", type=str, default="LLaMA-13B", help="")
parser.add_argument("--visual_adapter_type", type=str, default="router", help="")
parser.add_argument("--adapter_type", type=str, default="repattn", help="")
parser.add_argument("--bits", type=str, default="16bits", help="")
##for lynx_llm
parser.add_argument("--llama_path", type=str, default="/data/xiaocui/weights/decapoda-research/llama-7b-hf", help="the path of llama-7b")
## ''decapoda-llama-7b-hf' --llama_path "/data/xiaocui/weights/decapoda-research/llama-7b-hf"
## ''decapoda-llama-13b-hf' --llama_path "/data/xiaocui/weights/decapoda-research/llama-13b-hf"
parser.add_argument("--open_flamingo_path", type=str, default="/data/xiaocui/weights/openflamingo/OpenFlamingo-9B/checkpoint.pt", help="the path of openflamingo")
parser.add_argument("--finetune_path", type=str, default="/data/xiaocui/weights/Multimodal_GPT/mmgpt-lora-v0-release.pt", help="the path of mmgpt_lora")
## for llama
parser.add_argument('--use_quantization', action='store_true', help='use quantization or not in llama')
parser.add_argument('--peft_model', type=str, default=None, help='the path of peft_model in llama')
parser.add_argument("--top_k", type=int, default=1, help="")
parser.add_argument("--repetition_penalty", type=float, default=1.0, help="")
parser.add_argument("--length_penalty", type=int, default=1, help="")
##for mplug_owl
parser.add_argument('--mplug_owl_pretrained_ckpt', type=str, default='/data/xiaocui/weights/mplug/MAGAer13/mplug-owl-llama-7b', help='the path of the pretrained weights for mplug_owl')
##for minigpt4
parser.add_argument("--cfg_path", type=str, default="multimodal_eval_main/models/MiniGPT4/eval_configs/minigpt4_eval.yaml", help="path to configuration file.")
parser.add_argument( "--options", help="override some settings in the used config, the key-value pair "
"in xxx=yyy format will be merged into config file (deprecate), "
"change to --cfg-options instead.",)
parser.add_argument("--minigpt4_pretrained_ckpt", type=str, default="/data/xiaocui/weights/MiniGPT4/pretrained_minigpt4.pth", help="path to minigpt4 pretrained weights.")
## for llama_adapter
parser.add_argument("--llama_path_for_llama_adapter", type=str, default="/data/xiaocui/weights/LLaMA-7B", help="the path of llama-7b")
## for vpgtrans
# parser.add_argument("--cfg_path", type=str, default="multimodal_eval_main/models/VPGTrans/lavis/projects/blip2/demo/vl_vicuna_demo.yaml", help="path to configuration file.")
## for llava
parser.add_argument("--llava_model_path", type=str, default="/data/xiaocui/weights/llava-7b", help="/path/to/model")
parser.add_argument("--conv_mode", type=str, default='multimodal')
## for chatgpt
parser.add_argument("--chatgpt_engine", type=str, default="", help="the engine for chatgpt")
parser.add_argument("--api_key", type=str, default="", help="your API Key for chatgpt")
return parser.parse_args()
args = parse_args()
device = torch.device("cuda") if torch.cuda.is_available() else "cpu"
##for LaVIN
os.environ["LOCAL_RANK"]=args.local_rank
def before_retry_fn(retry_state):
if retry_state.attempt_number > 1:
print(f"Retrying API call. Attempt #{retry_state.attempt_number}, f{retry_state}")
@retry(wait=wait_fixed(5), stop=stop_after_attempt(6), before=before_retry_fn)
def query_chatgpt_model(api_key: str, engine: str, prompt: str, model: str = "gpt-3.5-turbo", max_tokens: int = 256, temperature: float = 0):
openai.api_type = "azure"
openai.api_base = "https://research2.openai.azure.com/"
openai.api_version = "2023-03-15-preview"
openai.api_key =api_key
try:
completions = openai.ChatCompletion.create(
engine=engine,
model=model,
messages=[{"role": "user", "content": prompt}],
max_tokens=max_tokens,
n=1,
stop=None,
temperature=temperature,
)
output = completions.choices[0].message.content.strip()
except Exception as e:
print(e)
return output
def parallel_query_chatgpt_model(api_key, engine, prompt):
return query_chatgpt_model(api_key, engine, prompt)
def setup_model_parallel() -> Tuple[int, int]:
local_rank = int(os.environ.get("LOCAL_RANK", -1))
world_size = int(os.environ.get("WORLD_SIZE", -1))
dist.init_process_group(backend='nccl', init_method='env://')
print('+++++++++++++++++++++local_rank is {}+++++++++++'.format(local_rank))
print('+++++++++++++++++++++WORLD_SIZE is {}+++++++++++'.format(world_size))
# torch.distributed.init_process_group("nccl")
LaVIN_initialize_model_parallel(world_size)
torch.cuda.set_device(local_rank)
# seed must be the same in all processes
torch.manual_seed(42)
return local_rank, world_size
def _load_and_redistribute_checkpoint(llama_model_path, model_name):
with open(Path(llama_model_path) / model_name / 'params.json') as f:
params = json.load(f)
tokenizer = LaVIN_Tokenizer(model_path=str(Path(llama_model_path) / model_name / 'tokenizer.model'))
print('Using model path: %s, model_name: %s' % (llama_model_path, model_name))
if model_name=='7B':
checkpoint = torch.load(llama_model_path + model_name + '/consolidated.00.pth', map_location="cpu")
return checkpoint, tokenizer, params
checkpoints = (Path(llama_model_path) / model_name).glob('*.pth')
checkpoints = sorted(checkpoints)
mp_world_size = fs_init.get_model_parallel_world_size()
mp_rank = fs_init.get_model_parallel_rank()
if mp_world_size == len(checkpoints):
print('same number of shards of checkpoints and training, loading directly...')
dist.barrier()
print('[rank=%d, mp_rank=%d] loading from %s' % (dist.get_rank(), mp_rank, checkpoints[mp_rank]))
checkpoint = torch.load(checkpoints[mp_rank], map_location='cpu')
else:
print('different number of shards of checkpoints and training, redistributing...')
if dist.get_rank() == 0:
loaded = []
for x in checkpoints:
print('loading from', x)
loaded.append(torch.load(x, map_location='cpu'))
full_state_dict = {}
split_dims = {}
def add_weight_with_split_dim(name, dim):
if dim < 0: # bcast without split
full_state_dict[name] = loaded[0][name].clone()
else:
full_state_dict[name] = torch.cat([x[name] for x in loaded], dim=dim)
for x in loaded:
del x[name]
split_dims[name] = dim
add_weight_with_split_dim('tok_embeddings.weight', 1)
add_weight_with_split_dim('norm.weight', -1)
add_weight_with_split_dim('output.weight', 0)
for i in range(params['n_layers']):
print('gathering layer %d of %d' % (i, params['n_layers']))
layer_prefix = f'layers.{i}.'
bcast_names = [
'attention_norm.weight',
'ffn_norm.weight',
]
column_parallel_names = [
'attention.wq.weight',
'attention.wk.weight',
'attention.wv.weight',
'feed_forward.w1.weight',
'feed_forward.w3.weight',
]
row_parallel_names = [
'attention.wo.weight',
'feed_forward.w2.weight',
]
for key in bcast_names:
add_weight_with_split_dim(layer_prefix + key, -1)
for key in column_parallel_names:
add_weight_with_split_dim(layer_prefix + key, 0)
for key in row_parallel_names:
add_weight_with_split_dim(layer_prefix + key, 1)
full_state_dict_meta = dict((k, v.shape) for k, v in full_state_dict.items())
dist.broadcast_object_list([full_state_dict_meta, split_dims], src=0)
else: # dist.get_rank() != 0
recv_objs = [None, None]
dist.broadcast_object_list(recv_objs, src=0)
full_state_dict_meta, split_dims = recv_objs
local_state_dict = {}
for k in sorted(full_state_dict_meta.keys()):
print('redistributing weights: %s' % k)
if dist.get_rank() == 0:
value = full_state_dict[k].cuda().half()
del full_state_dict[k]
else:
value = torch.empty(full_state_dict_meta[k], device='cuda', dtype=torch.half)
dist.broadcast(value, src=0)
value = value.cpu()
if split_dims[k] < 0:
local_state_dict[k] = value
else:
dim = split_dims[k]
assert dim >= 0 and dim < value.ndim and value.size(dim) % mp_world_size == 0
shard_size = value.size(dim) // mp_world_size
shard_st, shard_ed = shard_size * mp_rank, shard_size * (mp_rank + 1)
# TODO: make more general
if dim == 0:
value = value[shard_st: shard_ed]
elif dim == 1:
value = value[:, shard_st: shard_ed]
else:
raise NotImplementedError()
local_state_dict[k] = value.clone()
checkpoint = local_state_dict
return checkpoint, tokenizer, params
def load_LaVIN_model(ckpt_dir: str='/data/xiaocui/weights',
llm_model:str='7B',
tokenizer_path: str='/datas/multimodal_LLMs/LLaMA-7B/tokenizer.model',
adapter_path: str='/data/xiaocui/weights/LaVIN/LaIN-7B/weights/sqa-llama-7b.pth',
local_rank: int=0,
world_size: int=1,
max_seq_len: int=128,
max_batch_size: int=1,
adapter_type: str='repattn',
adapter_dim:int=8,
adapter_scale:float=1,
hidden_proj:int=128,
visual_adapter_type: str='router',
temperature: float=0.8,
use_vicuna: bool=False,
bits: str='16bits',
cpu_load:bool=False,
) -> LaVIN_Generator:
start_time = time.time()
checkpoint, tokenizer, params = _load_and_redistribute_checkpoint(ckpt_dir, llm_model)
print("Loading")
adapter_checkpoint = torch.load(adapter_path, map_location="cpu")
model_args: LaVIN_ModelArgs = LaVIN_ModelArgs(
max_seq_len=max_seq_len, max_batch_size=max_batch_size,hidden_proj=hidden_proj, **params
)
model_args.vocab_size = tokenizer.n_words
if cpu_load:
#cpu load is slow, but is freindly for GPU with limited memory.
torch.set_default_tensor_type(torch.HalfTensor)
else:
torch.set_default_tensor_type(torch.cuda.HalfTensor)
model = LaVIN_Transformer(model_args)
#delete language encoder
del model.backbone.transformer
torch.set_default_tensor_type(torch.FloatTensor)
if bits in ['4bit','8bit']:
from multimodal_eval_main.models.LaVIN.util.quantization import quant_model_bnb
model.layers = quant_model_bnb(model.layers, quant_bit='4bit')
LaVIN_set_MMAdapter(model, adapter_type, dim=adapter_dim, s=adapter_scale,t=temperature)
LaVIN_set_Clip_Adapter(model.backbone.visual, visual_adapter_type, dim=adapter_dim, s=adapter_scale,t=temperature)
model.load_state_dict(checkpoint, strict=False)
if use_vicuna:
apply_model_delta_online(model,'../data/weights/vicuna_'+llm_model)
state_dict={}
for key in adapter_checkpoint['model']:
state_dict[key.replace('module.','')]=adapter_checkpoint['model'][key]
model.load_state_dict(state_dict, strict=False)
model.to(torch.device('cuda'))
# parameters = get_parameter_number(model)
# print("+++++++++++++++++++++++++++++++++++++++++++=")
# print(parameters)
generator = LaVIN_Generator(model, tokenizer)
print(f"Loaded in {time.time() - start_time:.2f} seconds")
return generator
def load_model(args, loacal_rank=None, world_size=None):
'''
name="blip2_t5", model_type="pretrain_flant5xxl"
'''
print(f"++++++++++++++++Loading model is {args.model_name}+++++++")
###Flan-T5
if args.model_name == 'text_flan-t5-xxl':
model_type = 'google/flan-t5-xxl'
tokenizer = T5Tokenizer.from_pretrained(model_type)
model = T5ForConditionalGeneration.from_pretrained(model_type, device_map="auto")
args.model_type = model_type
return tokenizer, model, model_type
##LLaMA-V1
elif 'decapoda-llama'in args.model_name or 'meta-llama2' in args.model_name:
if args.model_name == 'decapoda-llama-7b-hf':
## llama_path = 'decapoda-research/llama-7b-hf' or 'your local path'
model_type = 'LLaMA-V1-7B'
elif args.model_name == 'decapoda-llama-13b-hf':
model_type = 'LLaMA-V1-13B'
## llama_path = 'decapoda-research/llama-13b-hf' or 'your local path'
elif args.model_name == 'meta-llama2-7b-hf':
model_type = 'LLaMA-V2-7B'
## llama_path = 'meta-llama/Llama-2-7b-hf' or 'your local path'
elif args.model_name == 'meta-llama2-13b-hf':
model_type = 'LLaMA-V2-13B'
## llama_path = 'meta-llama/Llama-2-13b-hf' or 'your local path'
model = load_model_for_llama(args.llama_path, args.use_quantization)
tokenizer = LlamaTokenizer.from_pretrained(args.llama_path)
tokenizer.add_special_tokens(
{
"pad_token": "[PAD]",
}
)
if args.peft_model:
model = load_peft_model_for_llama(model, args.peft_model)
model.eval()
args.model_type = model_type
return tokenizer, model, model_type
## BLIP2
elif args.model_name == 'blip2_t5':
model_type='blip2-flan-t5-xxl'
model = BlipModel(path_model="/data/xiaocui/weights/Salesforce/{}".format(model_type), max_output_length=args.max_output_new_length)
args.model_type = model_type
return model, model_type
###InstructBLIP
elif args.model_name == 'blip2_instruct_flant5xxl':
model_type="flant5xxl"
model = InstructBlipT5Model(path_model=model_type, max_output_length=args.max_output_new_length)
args.model_type = model_type
return model, model_type
##Fromage
elif args.model_name == 'fromage':
model_type="Fromage-9B"
model = FromageModel(model_type=model_type, max_output_length=args.max_output_new_length)
args.model_type = model_type
return model, model_type
##OpenFlamingo
elif args.model_name == 'openflamingo':
model_type='OpenFlamingo-9B'
model = OpenFlamingoModel(model_type=model_type, max_output_length=args.max_output_new_length)
args.model_type = model_type
return model, model_type
##MultimodalGPT
elif args.model_name == 'mmgpt':
model_type = 'mmgpt_lora_v0_release_9B'
model = mmgpt_Inferencer(
llama_path=args.llama_path,
open_flamingo_path=args.open_flamingo_path,
finetune_path=args.finetune_path)
args.model_type = model_type
return model, model_type
###LaVIN
elif 'LaVIN' in args.model_name:
if args.model_name == 'LaVIN_7B':
model_type = '7B'
elif args.model_name == 'LaVIN_13B':
model_type = '13B'
model = load_LaVIN_model(ckpt_dir=args.ckpt_dir,
llm_model=args.llm_model,
tokenizer_path=args.tokenizer_path,
adapter_path=args.adapter_path,
local_rank=loacal_rank,
world_size=world_size,
max_seq_len=args.max_seq_len,
max_batch_size=args.max_batch_size,
adapter_type=args.adapter_type,
bits=args.bits,
visual_adapter_type=args.visual_adapter_type,
temperature=args.temperature,
)
args.model_type = model_type
return model, model_type
###mPLUG-Owl
elif args.model_name == 'mplug_owl':
model_type = 'mplug_owl_llama_7b'
model = MplugOwlForConditionalGeneration.from_pretrained(
args.mplug_owl_pretrained_ckpt,
torch_dtype=torch.bfloat16,
).to(device)
model.tie_weights()
image_processor = MplugOwlImageProcessor.from_pretrained(args.mplug_owl_pretrained_ckpt)
tokenizer = LlamaTokenizer.from_pretrained(args.mplug_owl_pretrained_ckpt)
processor = MplugOwlProcessor(image_processor, tokenizer)
args.model_type = model_type
return tokenizer, model, processor, model_type
### MiniGPT4
elif args.model_name == 'minigpt4':
model_type = 'MiniGPT4_Vicuna13B'
args.model_type = model_type
cfg = minigpt4_Config(args)
model_config = cfg.model_cfg
model_config.ckpt = args.minigpt4_pretrained_ckpt
# model_config.device_8bit = args.gpu_id
model_cls = miniGPT4_registry.get_model_class(model_config.arch)
model = model_cls.from_config(model_config).to(device)
vis_processor_cfg = cfg.datasets_cfg.cc_sbu_align.vis_processor.train
vis_processor = miniGPT4_registry.get_processor_class(vis_processor_cfg.name).from_config(vis_processor_cfg)
return model, vis_processor, model_type
## LLaMA_Adapterv2
elif args.model_name == 'llama_adapterv2':
model_type = 'LLaMA_AdapterV2_7B'
args.model_type = model_type
model, vis_processor = llama_adapter.load("BIAS-7B", args.llama_path_for_llama_adapter, device)
return model, vis_processor, model_type
## VPGTrans
elif args.model_name == 'vpgtrans':
model_type = 'VPGTrans_Vicuna7B'
args.model_type = model_type
cfg = VPGTans_Config(args)
model_config = cfg.model_cfg
model_cls = vpgtrans_registry.get_model_class(model_config.arch)
model = model_cls.from_config(model_config).to(device)
vis_processor_cfg = cfg.datasets_cfg.minigpt4_self_instruct_caption.vis_processor.train
print(f'=========================the vis_processor_cfg is {vpgtrans_registry.get_processor_class(vis_processor_cfg.name)}')
vis_processor = vpgtrans_registry.get_processor_class(vis_processor_cfg.name).from_config(vis_processor_cfg)
return model, vis_processor, model_type
## LLaVA
elif 'llava' in args.model_name:
if args.model_name == 'llava_7b':
model_type = 'llava_7b'
elif args.model_name == 'llava_13b':
model_type = 'llava_13b'
args.model_type = model_type
tokenizer = AutoTokenizer.from_pretrained(args.llava_model_path)
if "mpt" in args.llava_model_path.lower():
model = LlavaMPTForCausalLM.from_pretrained(args.llava_model_path, low_cpu_mem_usage=True, torch_dtype=torch.float16,
use_cache=True).to(device)
else:
model = LlavaLlamaForCausalLM.from_pretrained(args.llava_model_path, low_cpu_mem_usage=True, torch_dtype=torch.float16,
use_cache=True).to(device)
image_processor = CLIPImageProcessor.from_pretrained(model.config.mm_vision_tower, torch_dtype=torch.float16)
mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
return tokenizer, model, image_processor, model_type, mm_use_im_start_end
else:
print("++++++++++++++++++++++++You can add the other large language models that you want to evaluated!!!! ++++++++++++++++++++++++++++++++++++++++++++")
# Get label space
def get_label_space(task: str, dataset: str) -> list:
if task == 'MABSA':
if dataset == 'Twitter_2015' or dataset == "Twitter_2017":
label_space = ["positive", "neutral", "negative"]
elif dataset == 'MASAD':
label_space = ["positive", "negative"]
elif task == 'MSA':
if dataset == 'MVSA_Multiple' or dataset == 'MVSA_Single' or dataset == "MOSI_3":
label_space = ["positive", "neutral", "negative"]
elif dataset == "MOSI_2" or dataset == "MOSEI_2":
label_space = ["positive", "negative"]
elif "MOSI_7" in dataset or dataset == "MOSEI_7":
label_space = ["strongly positive", "positive", "weakly positive", "neutral", "weakly negative", "negative", "strongly negative"]
elif dataset == 'TumEmo':
label_space = ["angry", "bored", "calm", "fear", "happy", "love", "sad"]
elif task == "MRE":
'''
{'held_on': 18, 'couple': 19, 'member_of': 110, 'alternate_names': 29, 'peer': 156, 'contain': 99, 'nationality': 10, 'subsidiary': 16, 'part_of': 14, 'locate_at': 46, 'place_of_birth': 7, 'present_in': 74, 'charges': 1, 'parent': 4, 'place_of_residence': 29, 'awarded': 4, 'siblings': 1, 'religion': 1, 'neighbor': 2})
'''
entity_cat_space = ['loction', 'organization', 'person', 'misc']
label_space = ['held_on', 'couple', 'member_of', 'alternate_names', 'peer', 'contain', 'nationality', 'subsidiary', 'part_of', 'locate_at', 'place_of_birth', 'present_in', 'charges', 'parent', 'place_of_residence', 'awarded', 'siblings', 'religion', 'neighbor']
if "JMNRE" in dataset:
label_space = (sorted(label_space), sorted(entity_cat_space))
return label_space
elif task== "MHM":
##Multimodal_Hateful_Memes
label_space = ["yes", "no"]
elif task=="MSR":
label_space = ["yes", "no"]
elif task=="QA":
if dataset == "ScienceQA" or dataset == "ScienceQA_no_image" or dataset=="ScienceQA_1":
label_space = ["0", '1', "2", "3", "4"]
else:
raise NotImplementedError
return sorted(label_space)
# Function to get the task name and stance target based on the task and dataset
def get_task_name(task: str, dataset: str) -> str:
if task == 'MABSA':
if dataset == 'Twitter_2015' or dataset == "Twitter_2017" or dataset == 'MASAD' :
task_name = "multimodal aspect-based sentiment classification"
elif task == 'MSA':
if dataset == 'MVSA_Multiple' or dataset == 'MVSA_Single' or dataset == 'TumEmo' or dataset == "MOSI_3" or ("MOSI_7" in dataset) or dataset == "MOSI_2" or dataset == "MOSEI_2" or dataset == "MOSEI_7":
task_name = "multimodal sentiment classification"
elif task == "MRE":
if 'JMNRE' in dataset:
task_name = "joint multimodal entity-relation extraction"
elif dataset == "MNRE":
task_name = "multimodal relation extraction"
elif task == "MHMR":
task_name = "multimodal hateful detection"
elif task == "MSR":
task_name = "multimodal irony detection"
elif task == "QA":
task_name ="multimodal question answer"
else:
raise NotImplementedError
return task_name.title()
def generate_fake_data(task, dataset, label_space, row):
# fake data for dev
if any(substring in dataset for substring in ["uabsa", "aste", "asqp"]):
try:
pred = [random.choice(eval(row["label_text"]))]
except:
pred = []
else:
pred = str(random.choice(label_space))
return pred
# Define templates for different tasks and datasets
def generate_multimodal_template(key, label_space, task_name, **kwargs):
task_definitions = {
"MABSA": "Given the text-image pair and the aspect, assign a sentiment label towards \"{target}\" from {label_space}.",
"MSA": "Given the text-image pair, assign a sentiment label from {label_space}.",
"MNRE": "Given the text-image pair, assign a relation label towards the head entity \"{head_entity}\" belongs to \"{head_cat}\" and the tail entity \"{tail_entity}\" belongs to \"{tail_cat}\" from {label_space}.",
'MHM': "Given the text-image pair, please determine whether or not it contains hate. Assign a label from {label_space}.",
"MSR": "Given the text-image pair, please determine whether or not it contains irony. Assign a label from {label_space}.",
"QA": "Given the question, "
}
output_formats = {
"MABSA": "Return label only without any other text.",
"MSA": "Return label only without any other text.",
"MNRE": "Return label only without any other text.",
"MHM": "Return label only without any other text.",
"MSR": "Return label only without any other text.",
"QA": "Return answer only without any other text.",
}
if key == "stance":
task_name += " ({target})".format(**kwargs)
task_definition = task_definitions[key].format(**kwargs, label_space=label_space)
output_format = output_formats[key]
return task_name, task_definition, output_format
def generate_text_template(key, label_space, task_name, **kwargs):
task_definitions = {
"MABSA": "Given the text and the aspect, assign a sentiment label towards \"{target}\" from {label_space}.",
"MSA": "Given the text, assign a sentiment label from {label_space}.",
"MRE": "Given the text, assign a relation label towards the head entity \"{head_entity}\" belongs to \"{head_cat}\" and the tail entity \"{tail_entity}\" belongs to \"{tail_cat}\" from {label_space}.",
'MHMR': "Given the text, please determine whether or not it contains hate. Assign a label from {label_space}.",
"MSR": "Given the text, please determine whether or not it contains irony. Assign a label from {label_space}.",
"QA": "Given the question, "
}
output_formats = {
"MABSA": "Return label only without any other text.",
"MSA": "Return label only without any other text.",
"MRE": "Return label only without any other text.",
"MHMR": "Return label only without any other text.",
"MSR": "Return label only without any other text.",
"QA": "Return answer only without any other text.",
}
if key == "stance":
task_name += " ({target})".format(**kwargs)
task_definition = task_definitions[key].format(**kwargs, label_space=label_space)
output_format = output_formats[key]
return task_name, task_definition, output_format
# generate demos
def generate_fix_demo(train_df, task, dataset):
tuple_list = []
if dataset in ['Twitter_2015', "Twitter_2017", 'MASAD']:
for i, row in train_df.iterrows():
aspect = row["aspect"]
text = row["text"].replace('$T$', aspect)
label = row["label_text"]
text += f" (sentiment towards Aspect: \"{aspect}\")"
image_path = row['image']
image_description = row['image_description']
tuple_list.append((text, label, image_path, image_description))
elif dataset in ['MVSA_Single', 'MVSA_Multiple', 'TumEmo', 'MOSI_3', "MOSI_7", "MOSI_2", "MOSI_7_1", "MOSEI_2", 'MOSEI_7']:
for i, row in train_df.iterrows():
text = row["text"]
image_path = row['image']
label = row["label_text"]
image_description = row['image_description']
tuple_list.append((text, label, image_path, image_description))
elif dataset in ['hate', 'MSD']:
for i, row in train_df.iterrows():
text = row["text"]
image_path = row['image']
label = row["label_text"]
image_description = row['image_description']
tuple_list.append((text, label, image_path, image_description))
elif dataset == "MNRE":
for i, row in train_df.iterrows():
text = row["text"]
head_entity = row['head_entity']
head_cat = row['head_cat']
tail_entity = row['tail_entity']
tail_cat = row['tail_cat']
label = row["label_text"]
text += f" (relation towards the head entity \"{head_entity}\" belongs to \"{head_cat}\" and the tail entity \"{tail_entity}\" belongs to \"{tail_cat}\")"
image_path = row['image']
image_description = row['image_description']
tuple_list.append((text, label, image_path, image_description))
else:
sub_df = train_df[['text', 'label_text']]
tuple_list = [tuple(x) for x in sub_df.to_records(index=False)]
return tuple_list
# Function to generate prompt for the OpenAI model
def generate_prompt(setting, task, dataset, label_space, row, demo_tuples, model_name, prompt_type, args):
if task!="QA":
text = row["text"]
if task == 'MABSA':
aspect = row['aspect']
task_name = get_task_name(task, dataset)
if task == "MABSA":
if model_name == 'text_flan-t5-xxl' or 'decapoda-llama'in args.model_name or model_name == 'chatgpt':
task_name, task_definition, output_format = generate_text_template("MABSA", label_space, task_name=task_name, target=row["aspect"])
else:
task_name, task_definition, output_format = generate_multimodal_template("MABSA", label_space, task_name=task_name, target=row["aspect"])
elif task == "MSA":
if model_name == 'text_flan-t5-xxl' or 'decapoda-llama'in args.model_name or model_name == 'chatgpt':
task_name, task_definition, output_format = generate_text_template("MSA", label_space, task_name=task_name)
else:
task_name, task_definition, output_format = generate_multimodal_template("MSA", label_space, task_name=task_name)
elif task=='MRE':
head_entity = row['head_entity']
head_cat = row['head_cat']
tail_entity = row['tail_entity']
tail_cat = row['tail_cat']
if dataset == "MRE":
relation_label_space = label_space
if model_name == 'text_flan-t5-xxl' or 'decapoda-llama'in args.model_name or model_name == 'chatgpt':
task_name, task_definition, output_format = generate_text_template("MRE", relation_label_space, task_name=task_name, head_entity=head_entity, head_cat=head_cat, tail_entity=tail_entity, tail_cat=tail_cat)
else:
task_name, task_definition, output_format = generate_multimodal_template("MRE", relation_label_space, task_name=task_name, head_entity=head_entity, head_cat=head_cat, tail_entity=tail_entity, tail_cat=tail_cat)
elif task == "MHMR":
if model_name == 'text_flan-t5-xxl' or 'decapoda-llama'in args.model_name or model_name == 'chatgpt':
task_name, task_definition, output_format = generate_text_template("MHMR", label_space, task_name=task_name)
else:
task_name, task_definition, output_format = generate_multimodal_template("MHMR", label_space, task_name=task_name)
elif task == "MSR":
if model_name == 'text_flan-t5-xxl' or 'decapoda-llama'in args.model_name or model_name == 'chatgpt':
task_name, task_definition, output_format = generate_text_template("MSR", label_space, task_name=task_name)
else:
task_name, task_definition, output_format = generate_multimodal_template("MSR", label_space, task_name=task_name)
else:
raise NotImplementedError
else:
##original_index,question,image,answer,answer_text,choices,hint
text = row['question']
choices = eval(row['choices'])
task_name = get_task_name(task, dataset)
if model_name == 'text_flan-t5-xxl' or 'decapoda-llama'in args.model_name or model_name == 'chatgpt':
task_name, task_definition, output_format = generate_text_template("QA", label_space='', task_name=task_name)
else:
task_name, task_definition, output_format = generate_multimodal_template("QA", label_space='', task_name=task_name)
option_num = ["(a)", "(b)", "(c)", "(d)", "(e)","(f)", "(g)", "(h)" ]
options =''
# question = "What is the answer about the above question?"
for i, choice in enumerate(choices):
option = option_num[i]+ " " + choice + " "
options +=option
task_definition = task_definition + f"please choose the answer from \"{options}\" to the following question."
if setting == "zero-shot":
if prompt_type == "1":
if task=="MABSA":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text} Aspect: {aspect}\nLabel:"
question = ""
elif task == "MRE":
head_entity = row['head_entity']
head_cat = row['head_cat']
tail_entity = row['tail_entity']
tail_cat = row['tail_cat']
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text} The head entity: {head_entity} belongs to {head_cat}; The tail entity: {tail_entity} belongs to {tail_cat}.\n"
prompt = prompt+"Label:"
elif task=='QA':
context = row['hint']
if dataset == 'ScienceQA' or dataset == 'ScienceQA_no_image':
if args.use_context:
prompt = f"Please perform {task_name} task.\n{task_definition} {output_format}\nQuestion: {text}\nContext: {context}\nLabel:"
question = ""
else:
prompt = f"Please perform {task_name} task.\n{task_definition} {output_format}\nQuestion: {text}\nLabel:"
question = ""
else:
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text}\nLabel:"
elif prompt_type == "2":
if task=="MABSA":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text} Aspect: {aspect}\n"
question = "what is the sentiment about the aspect based on the text-image pair?\n"
elif task == "MSA":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text}\n"
question = "what is the sentiment about the text-image pair?\n"
elif task == "MRE":
head_entity = row['head_entity']
head_cat = row['head_cat']
tail_entity = row['tail_entity']
tail_cat = row['tail_cat']
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text} The head entity: {head_entity} belongs to {head_cat}; The tail entity: {tail_entity} belongs to {tail_cat}.\n"
question = "what has relation between the head entity and the tail entity based on the text-image pair?\n"
elif task == "MHMR":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text}\n"
question = "whether or not the text-image pair contains the hate?\n"
elif task == "MSR":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text}\n"
question = "whether or notthe text-image pair contains irony?\n"
elif task=='QA':
context = row['hint']
if dataset == 'ScienceQA' or dataset == 'ScienceQA_no_image':
if args.use_context:
prompt = f"Please perform {task_name} task.\n{task_definition} {output_format}\nQuestion: {text}\nContext: {context}\n"
else:
prompt = f"Please perform {task_name} task.\n{task_definition} {output_format}\nQuestion: {text}\n"
if task=="QA":
prompt = prompt + "The answer is:"
else:
prompt = prompt + "Question: " + question + "Answer:"
elif prompt_type == "3":
task_predefinition = "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n"
if task=="MABSA":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text} Aspect: {aspect}\n"
question = "what is the sentiment about the aspect based on the text-image pair?\n"
if dataset == 'MASAD':
options = "(a) negative (b) positive"
else:
options = "(a) neutral (b) negative (c) positive"
elif task == "MSA":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text}\n"
question = "what is the sentiment about the text-image pair?\n"
if dataset =="TumEmo":
options = "(a) angry (b) bored (c) calm (d) fear (e) happy (f) love (g) sad"
elif dataset == "MOSI_2" or dataset == "MOSEI_2":
options = "(a) negative (b) positive"
elif "MOSI_7" in dataset or dataset == "MOSEI_7":
# options = "(a) strongly positive (b) positive (c) weakly positive (d) neutral (e) weakly negative (f) negative (g) strongly negative"
options = "(a) negative (b) neutral (c) positive (d) strongly negative (e) strongly positive (f) weakly negative (g) weakly positive"
else:
options = "(a) neutral (b) negative (c) positive"
elif task == "MRE":
head_entity = row['head_entity']
head_cat = row['head_cat']
tail_entity = row['tail_entity']
tail_cat = row['tail_cat']
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text} The head entity: {head_entity} belongs to {head_cat}; The tail entity: {tail_entity} belongs to {tail_cat}.\n"
question = "what has relation between the head entity and the tail entity based on the text-image pair?\n"
options = "(a) held_on (b) couple (c) member_of (d) alternate_names (e) peer (f) contain (g) nationality (h) subsidiary (i) part_of (j) locate_at (k) place_of_birth (l) present_in (m) charges (n) parent (o) place_of_residence (p)awarded (q) siblings (r) religion (s) neighbor'"
elif task == "MHMR":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text}\n"
question = "whether or not the text-image pair contains the hate?\n"
options = "(a) yes (b) no"
elif task == "MSR":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text}\n"
question = "whether or not the text-image pair contains irony?\n"
options = "(a) yes (b) no"
elif task=='QA':
context = row['hint']
if args.use_context:
prompt = f"Please perform {task_name} task.\n{task_definition} {output_format}\n Question: {text}\nContext: {context}\n"
else:
prompt = f"Please perform {task_name} task.\n{task_definition} {output_format}\n Question: {text}\n"
if task=="QA":
prompt = task_predefinition + "### Instruction: \n" + prompt + f"Options: {options}\n" + "### Response:"
else:
prompt = task_predefinition + "### Instruction: \n" + prompt + "### Instruction: \n" + question + f"Options: {options}\n" + "### Response:"
elif prompt_type == "4":
if task=="MABSA":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text} Aspect: {aspect}\n"
question = "what is the sentiment about the aspect based on the text-image pair?\n"
elif task == "MSA":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text}\n"
question = "what is the sentiment about the text-image pair?\n"
elif task == "MRE":
head_entity = row['head_entity']
head_cat = row['head_cat']
tail_entity = row['tail_entity']
tail_cat = row['tail_cat']
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text} The head entity: {head_entity} belongs to {head_cat}; The tail entity: {tail_entity} belongs to {tail_cat}.\n"
question = "what has relation between the head entity and the tail entity based on the text-image pair?\n"
elif task == "MHMR":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text}\n"
question = "whether or not the text-image pair contains the hate?\n"
elif task == "MSR":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text}\n"
question = "whether or not the text-image pair contains irony?\n"
elif task=='QA':
context = row['hint']
if args.use_context:
prompt = f"Please perform {task_name} task.\n{task_definition} {output_format}\nQuestion: {text}\nContext: {context}\n"
question = "What is the answer about the above question?"
else:
prompt = f"Please perform {task_name} task.\n{task_definition} {output_format}\nQuestion: {text}\n"
question = "What is the answer about the above question?"
prompt = prompt + question
elif prompt_type == "5":
if task=="MABSA":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text} Aspect: {aspect}\n"
question = "what is the sentiment about the aspect based on the text-image pair?\n"
if dataset == 'MASAD':
options = "(a) negative (b) positive"
else:
options = "(a) neutral (b) negative (c) positive"
elif task == "MSA":
prompt = f"Please perform {task_name} task.\n{task_definition}\n{output_format}\nSentence: {text}\n"
question = "what is the sentiment about the text-image pair?\n"
if dataset =="TumEmo":
options = "(a) angry (b) bored (c) calm (d) fear (e) happy (f) love (g) sad"
elif dataset == "MOSI_2" or dataset == "MOSEI_2":
options = "(a) negative (b) positive"
elif "MOSI_7" in dataset or dataset == "MOSEI_7":
# options = "(a) strongly positive (b) positive (c) weakly positive (d) neutral (e) weakly negative (f) negative (g) strongly negative"
options = "(a) negative (b) neutral (c) positive (d) strongly negative (e) strongly positive (f) weakly negative (g) weakly positive"
else:
options = "(a) neutral (b) negative (c) positive"
elif task == "MRE":
head_entity = row['head_entity']
head_cat = row['head_cat']
tail_entity = row['tail_entity']
tail_cat = row['tail_cat']