-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels_modified.py
More file actions
1455 lines (1263 loc) · 47.5 KB
/
models_modified.py
File metadata and controls
1455 lines (1263 loc) · 47.5 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
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 types
import torch
from playground.models import LLaVA, JanusPro, Qwen2VL, QwenVL, LM
from playground.path_table import get_path_from_table
from parsers import BaseParser
from playground._utils._colors import *
from methods_utils.cache_table import ContextCDCandidates
from methods_utils.graber import Graber
from methods_utils.vcd_add_noise import add_diffusion_noise
from tqdm import tqdm
import random
import os
from abc import ABC
from typing import TYPE_CHECKING, Dict, Tuple, Optional
if TYPE_CHECKING:
from playground._utils._path import PathObj
GRABER = Graber()
class CTMixin(ABC):
ct: ContextCDCandidates
parser: BaseParser
def get_candidates_from_cache(
self,
image: "PathObj",
number: int,
ee_threshold: float,
ig_threshold: float,
ig_strategy: str,
show_progress: bool = False,
random_state: Optional[int] = None,
) -> list[str]:
datadict = self.ct.get_candidates(image, show_progress)
_, caption_objs, _, _ = self.parser.extract_nouns(datadict["caption"])
appeared = set(caption_objs)
appeared |= set(datadict["metric1"]["scores"].keys())
appeared |= set(datadict["metric2"]["scores"].keys())
related = set()
for word in appeared:
related.add(word)
for subword in self.parser.SAFE_WORDS[word]:
related.add(subword)
related_caption = set()
for word in caption_objs:
related_caption.add(word)
for subword in self.parser.SAFE_WORDS[word]:
related_caption.add(subword)
unrelated = set(self.parser.PARSER_WORDS) - related
unrelated = sorted(unrelated) # Ensure the reproducibility
candidates = {}
for obj, score in datadict["metric2"]["scores"].items():
score_strategy = score[ig_strategy]
if score_strategy > ig_threshold:
candidates[obj] = score_strategy
if show_progress:
tqdm.write(f"IG: {list(candidates.keys())}")
EE_list = []
for obj, score in datadict["metric1"]["scores"].items():
if score < ee_threshold and obj not in candidates.keys():
EE_list.append(obj)
candidates[obj] = -1.0
if show_progress:
tqdm.write(f"EE: {EE_list}")
candidates = sorted(candidates, key=candidates.get, reverse=True) # type:ignore
if random_state is not None:
random_generator = random.Random(random_state)
else:
random_generator = random
print_warning(
"`random_state` is set to `None` when generating candidates, which may lead to unreproducable results."
)
if number >= 1: # Added no add random candidates
if len(candidates) > number:
candidates = candidates[:number]
else:
candidates = candidates + random_generator.sample(
unrelated, min(number - len(candidates), len(unrelated))
)
candidates = sorted(candidates)
if show_progress:
tqdm.write(f"Final candidates: {candidates}")
return candidates
def preprocess_method(
self,
image,
method,
candidates_number,
ee_threshold,
ig_threshold,
ig_strategy,
question_id: Optional[int] = None,
) -> Tuple[Optional[Dict[str, float]], Optional[str]]:
GRABER.clear()
if method == "haltrapper":
assert image is not None
assert candidates_number is not None
assert ee_threshold is not None
assert ig_threshold is not None
candidates = {}
for obj in self.get_candidates_from_cache(
image,
candidates_number,
ee_threshold,
ig_threshold,
ig_strategy,
random_state=question_id,
show_progress=False,
):
candidates[obj] = 0.0
hallu_objs = candidates
else:
hallu_objs = None
if method == "code":
assert image is not None
caption = self.ct.get_candidates(image, show_progress=False)["caption"]
else:
caption = None
return hallu_objs, caption
def close_cache_table(self):
self.ct.close()
class LlavaModified(LLaVA, CTMixin):
def __init__(self, size="7b") -> None:
from transformers.generation.utils import (
GenerationMixin,
)
from transformers.models.llama.modeling_llama import (
LlamaModel,
LlamaSdpaAttention,
LlamaAttention,
)
from transformers.models.llama import LlamaForCausalLM
from methods_utils.search_methods_4_37_2 import (
new_greedy_search,
new_sample,
new_beam_search,
)
from methods_utils.new_llava_llama import (
new_LlavaLlamaForCausalLM_generate,
new_LlavaLlamaForCausalLM_forward,
)
from methods_utils.new_modeling_llama_4_37_2 import (
new_LlamaForCausalLM_forward,
new_LlamaModel_forward,
new_LlamaSdpaAttention_forward,
new_LlamaAttention_forward,
)
from llava import LlavaLlamaForCausalLM
# CD Algorithm
GenerationMixin.greedy_search = new_greedy_search
GenerationMixin.sample = new_sample
GenerationMixin.beam_search = new_beam_search
# Pre-processing
LlavaLlamaForCausalLM.generate = new_LlavaLlamaForCausalLM_generate
# Attention Scaling
LlamaSdpaAttention.forward = new_LlamaSdpaAttention_forward
LlamaAttention.forward = new_LlamaAttention_forward
# No substantial change, only adds and passes CD args
LlavaLlamaForCausalLM.forward = new_LlavaLlamaForCausalLM_forward
LlamaForCausalLM.forward = new_LlamaForCausalLM_forward
LlamaModel.forward = new_LlamaModel_forward
super().__init__("1.5", size)
def new_eval_model_pretrained(
self, args, disable_conv_mode_warning=False, **kwargs
):
# Copied and modified from LLaVA: llava/eval/run_llava.py
import torch
from llava.constants import (
IMAGE_TOKEN_INDEX,
DEFAULT_IMAGE_TOKEN,
DEFAULT_IM_START_TOKEN,
DEFAULT_IM_END_TOKEN,
IMAGE_PLACEHOLDER,
)
from llava.conversation import conv_templates
from llava.utils import disable_torch_init
from llava.mm_utils import (
process_images,
tokenizer_image_token,
)
import re
# Model
disable_torch_init()
qs = args.query
image_token_se = (
DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN
)
if args.image_file is not None:
if IMAGE_PLACEHOLDER in qs:
if self.model.config.mm_use_im_start_end:
qs = re.sub(IMAGE_PLACEHOLDER, image_token_se, qs)
else:
qs = re.sub(IMAGE_PLACEHOLDER, DEFAULT_IMAGE_TOKEN, qs)
else:
if self.model.config.mm_use_im_start_end:
qs = image_token_se + "\n" + qs
else:
qs = DEFAULT_IMAGE_TOKEN + "\n" + qs
if "llama-2" in self.model_name.lower():
conv_mode = "llava_llama_2"
elif "mistral" in self.model_name.lower():
conv_mode = "mistral_instruct"
elif "v1.6-34b" in self.model_name.lower():
conv_mode = "chatml_direct"
elif "v1" in self.model_name.lower():
conv_mode = "llava_v1"
elif "mpt" in self.model_name.lower():
conv_mode = "mpt"
else:
conv_mode = "llava_v0"
if (
conv_mode == "llava_v0"
and args.conv_mode is None
and not disable_conv_mode_warning
):
print_warning(
"The auto inferred conversation mode 'llava_v0' is currently being used for the LLaVA model. However, this is uncommon. This warning may appear because your model name does not match certain expected keywords. Using the incorrect conversation mode could result in performance decrease. Therefore, it is recommended to do a double-check. To disable this warning, you can pass `disable_conv_mode_warning=True` to this function."
)
if args.conv_mode is not None and conv_mode != args.conv_mode:
if not disable_conv_mode_warning:
print_warning(
"The auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}. To disable this warning, you can pass `disable_conv_mode_warning=True` to this function.".format(
conv_mode, args.conv_mode, args.conv_mode
)
)
else:
args.conv_mode = conv_mode
conv = conv_templates[args.conv_mode].copy()
conv.append_message(conv.roles[0], qs)
conv.append_message(conv.roles[1], None)
prompt = conv.get_prompt()
if args.image_file is None:
images_tensor = None
image_sizes = None
else:
image_files = self.image_parser(args)
images = self.load_images(image_files)
image_sizes = [x.size for x in images]
images_tensor = process_images(
images, self.image_processor, self.model.config
).to(self.model.device, dtype=torch.float16)
# HalTrapper: Modification Here
if args.append is not None:
input_ids_origin = (
tokenizer_image_token(
prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt"
)
.unsqueeze(0)
.cuda()
)
GRABER["input_ids_offset"] = len(input_ids_origin[0])
prompt += " " + args.append
# HalTrapper: Modification ends
input_ids = (
tokenizer_image_token(
prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt"
)
.unsqueeze(0)
.cuda()
)
# HalTrapper: Modification here
GRABER["input_ids"] = input_ids
if args.append is None:
GRABER["input_ids_offset"] = len(input_ids[0])
method = args.method
if (
method == "haltrapper"
and len(args.hallu_objs) != 0
and args.image_file is not None
):
# tqdm.write(str(args.hallu_objs))
hallu_objs = list(args.hallu_objs.keys())
hallu_scores = list(args.hallu_objs.values())
if args.repeat_mode == "continuous":
hallu_objs = [x for x in hallu_objs for _ in range(args.repeat)]
hallu_scores = [x for x in hallu_scores for _ in range(args.repeat)]
elif args.repeat_mode == "cross":
hallu_objs = hallu_objs * args.repeat
hallu_scores = hallu_scores * args.repeat
else:
raise ValueError(f"repeat_mode must in 'continuous' or 'cross'.")
context_ids = []
context_scaling = []
for obj, score in zip(hallu_objs, hallu_scores):
cur_context_ids = torch.tensor(
self.tokenizer.encode(obj), dtype=input_ids.dtype
)[1:]
context_ids.append(cur_context_ids)
context_scaling.append(torch.ones_like(cur_context_ids) * score)
context_ids = (
torch.cat(context_ids, dim=0).to(input_ids.dtype).to(input_ids.device)
)
context_scaling = (
torch.cat(context_scaling, dim=0).to(torch.float16).to(input_ids.device)
)
input_ids_cd = input_ids.clone()
input_scaling_cd = torch.zeros_like(input_ids, dtype=torch.float16)
image_token_at = torch.where(input_ids_cd == IMAGE_TOKEN_INDEX)[1]
# FIXME: Here assumes batch size == 0
input_ids_cd = torch.cat(
(
input_ids_cd[0][: image_token_at + 1],
context_ids,
input_ids_cd[0][image_token_at + 1 :],
),
dim=0,
).unsqueeze(0)
input_scaling_cd = torch.cat(
(
input_scaling_cd[0][: image_token_at + 1],
context_scaling,
input_scaling_cd[0][image_token_at + 1 :],
),
dim=0,
).unsqueeze(0)
if torch.all(input_scaling_cd.eq(0)):
input_scaling_cd = None # To save memory
input_scaling = None
images_tensor_cd = None
elif method == "vcd" and args.image_file is not None:
from methods_utils.vcd_add_noise import add_diffusion_noise
images_tensor_cd = add_diffusion_noise(images_tensor, args.noise_step)
input_ids_cd = None
input_scaling = None
input_scaling_cd = None
elif method == "icd" and args.image_file is not None:
qs_cd = (
"You are a confused objects detector to provide a fuzzy overview or impression of the image. "
+ args.query
)
if args.image_file is not None:
if IMAGE_PLACEHOLDER in qs:
if self.model.config.mm_use_im_start_end:
qs_cd = re.sub(IMAGE_PLACEHOLDER, image_token_se, qs_cd)
else:
qs_cd = re.sub(IMAGE_PLACEHOLDER, DEFAULT_IMAGE_TOKEN, qs_cd)
else:
if self.model.config.mm_use_im_start_end:
qs_cd = image_token_se + "\n" + qs_cd
else:
qs_cd = DEFAULT_IMAGE_TOKEN + "\n" + qs_cd
if args.conv_mode is not None and conv_mode != args.conv_mode:
pass
else:
args.conv_mode = conv_mode
conv_cd = conv_templates[args.conv_mode].copy()
conv_cd.append_message(conv.roles[0], qs_cd)
conv_cd.append_message(conv.roles[1], None)
prompt_cd = conv_cd.get_prompt()
input_ids_cd = (
tokenizer_image_token(
prompt_cd, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt"
)
.unsqueeze(0)
.cuda()
)
images_tensor_cd = None
input_scaling = None
input_scaling_cd = None
elif method == "pai" and args.image_file is not None:
from transformers.generation.logits_process import LogitsProcessorList
from methods_utils.pai_cfg import init_cfg_processor
input_scaling = torch.zeros_like(input_ids, dtype=torch.float16)
image_token_at = torch.where(input_ids == IMAGE_TOKEN_INDEX)[1]
# FIXME: Here assumes batch size == 0
input_scaling[0][image_token_at] = args.pai_alpha
kwargs["logits_processor"] = LogitsProcessorList(
[
init_cfg_processor(
self.tokenizer, self.model, [prompt], 1.1, 1, 2, 32
)
]
) # FIXME: Hardcode Here
input_scaling_cd = None
input_ids_cd = None
images_tensor_cd = None
elif method == "code" and args.image_file is not None:
caption = args.caption
qs_cd = args.query
if args.image_file is not None:
if IMAGE_PLACEHOLDER in qs:
if self.model.config.mm_use_im_start_end:
qs_cd = re.sub(IMAGE_PLACEHOLDER, caption, qs_cd)
else:
qs_cd = re.sub(IMAGE_PLACEHOLDER, caption, qs_cd)
else:
if self.model.config.mm_use_im_start_end:
qs_cd = caption + "\n" + qs_cd
else:
qs_cd = caption + "\n" + qs_cd
if args.conv_mode is not None and conv_mode != args.conv_mode:
pass
else:
args.conv_mode = conv_mode
conv_cd = conv_templates[args.conv_mode].copy()
conv_cd.append_message(conv.roles[0], qs_cd)
conv_cd.append_message(conv.roles[1], None)
prompt_cd = conv_cd.get_prompt()
input_ids_cd = (
tokenizer_image_token(
prompt_cd, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt"
)
.unsqueeze(0)
.cuda()
)
images_tensor_cd = None
input_scaling = None
input_scaling_cd = None
else:
input_ids_cd = None
images_tensor_cd = None
input_scaling = None
input_scaling_cd = None
# HalTrapper: Modification ends
GRABER["grid_hs"] = 24
GRABER["grid_ws"] = 24
with torch.inference_mode():
output = self.model.generate(
input_ids,
input_ids_cd=input_ids_cd,
images=images_tensor,
images_cd=images_tensor_cd,
image_sizes=image_sizes,
input_scaling=input_scaling,
input_scaling_cd=input_scaling_cd,
cd_type=args.cd_type,
**kwargs,
)
if (
"return_dict_in_generate" in kwargs.keys()
and kwargs["return_dict_in_generate"]
):
output_ids = output["sequences"] # type:ignore
response = self.tokenizer.batch_decode(
output_ids, skip_special_tokens=True
)[0].strip()
else:
response = self.tokenizer.batch_decode(output, skip_special_tokens=True)[
0
].strip()
output = None
return response, output
def submit(
self,
prompt,
image=None,
question_id=None,
method=None,
cd_type=None,
noise_step=None,
repeat=1,
repeat_mode="continuous",
pai_alpha=None,
append=None,
sep=" ",
candidates_number=None,
ee_threshold=None,
ig_threshold=None,
ig_strategy="cos_sim",
**kwargs,
):
hallu_objs, caption = self.preprocess_method(
image,
method,
candidates_number,
ee_threshold,
ig_threshold,
ig_strategy,
question_id,
)
if sep != " ":
raise NotImplementedError()
if method is None:
method = "baseline"
if hallu_objs is None and method == "haltrapper":
hallu_objs = []
args = type(
"Args",
(),
{
"model_path": self.model_path,
"model_base": None,
"model_name": self.get_model_name_from_path(self.model_path),
"query": prompt,
"conv_mode": None,
"image_file": image,
"sep": ",",
"noise_step": noise_step,
"hallu_objs": hallu_objs,
"repeat": repeat,
"repeat_mode": repeat_mode,
"pai_alpha": pai_alpha,
"method": method,
"caption": caption,
"cd_type": cd_type,
"append": append,
},
)()
response, output = self.new_eval_model_pretrained(args, **kwargs)
model_logs = {}
if hallu_objs:
model_logs["candidates"] = hallu_objs
if caption:
model_logs["caption"] = caption
return response, output, model_logs if model_logs else None
class JanusProModified(JanusPro, CTMixin):
def __init__(self) -> None:
from methods_utils.new_modeling_llama_4_48_3 import new_LlamaForCausalLM_forward
from methods_utils.search_methods_4_48_3 import new_sample, new_beam_search
from transformers.models.llama.modeling_llama import LlamaForCausalLM
from transformers.generation.utils import GenerationMixin
# CD algorithm
GenerationMixin._sample = new_sample # type: ignore
GenerationMixin._beam_search = new_beam_search # type: ignore
LlamaForCausalLM.forward = new_LlamaForCausalLM_forward
super().__init__()
def submit(
self,
prompt,
image=None,
question_id=None,
method=None,
cd_type=None,
noise_step=None,
repeat=1,
repeat_mode="continuous",
pai_alpha=None,
append=None,
sep=" ",
candidates_number=None,
ee_threshold=None,
ig_threshold=None,
ig_strategy="cos_sim",
**kwargs,
):
# 1. preprocess
hallu_objs, caption = self.preprocess_method(
image,
method,
candidates_number,
ee_threshold,
ig_threshold,
ig_strategy,
question_id,
)
if method is None:
method = "baseline"
if hallu_objs is None and method == "haltrapper":
hallu_objs = {}
# 2. Get conversation
if image is None:
method = "baseline"
use_vcd = False
if (
method == "haltrapper"
and hallu_objs is not None
and len(hallu_objs) != 0
and image is not None
):
# tqdm.write(str(hallu_objs))
hallu_scores = list(hallu_objs.values())
hallu_objs = list(hallu_objs.keys())
if repeat_mode == "continuous":
hallu_objs = [x for x in hallu_objs for _ in range(repeat)]
hallu_scores = [x for x in hallu_scores for _ in range(repeat)]
elif repeat_mode == "cross":
hallu_objs = hallu_objs * repeat
hallu_scores = hallu_scores * repeat
else:
raise ValueError(f"repeat_mode must in 'continuous' or 'cross'.")
for s in hallu_scores:
assert s == 0 # else not implemented
conversation_cd = [
{
"role": "User",
"content": f"<image_placeholder> {sep.join(hallu_objs)}\n{prompt}",
"images": [image],
},
{"role": "Assistant", "content": ""},
]
elif method == "vcd" and image is not None:
use_vcd = True
conversation_cd = [
{
"role": "User",
"content": f"<image_placeholder>\n{prompt}",
"images": [image],
},
{"role": "Assistant", "content": "" if append is None else append},
]
elif method == "icd" and image is not None:
conversation_cd = [
{
"role": "User",
"content": f"<image_placeholder>\nYou are a confused objects detector to provide a fuzzy overview or impression of the image. {prompt}",
"images": [image],
},
{"role": "Assistant", "content": ""},
]
elif method == "pai" and image is not None:
raise NotImplementedError()
conversation_cd = None
elif method == "code" and image is not None:
assert caption is not None
caption = caption.strip()
conversation_cd = [
{
"role": "User",
"content": f"{caption}\n{prompt}",
},
{"role": "Assistant", "content": ""},
]
else:
conversation_cd = None
# TODO: PAI
input_scaling = None
input_scaling_cd = None
import torch
from janus.utils.io import load_pil_images
if image is None:
conversation = [
{
"role": "User",
"content": prompt,
},
{"role": "Assistant", "content": "" if append is None else append},
]
else:
conversation = [
{
"role": "User",
"content": f"<image_placeholder>\n{prompt}",
"images": [image],
},
{"role": "Assistant", "content": "" if append is None else append},
]
# 3. submit
# load images and prepare for inputs
pil_images = load_pil_images(conversation)
prepare_inputs = self.processor(
conversations=conversation, images=pil_images, force_batchify=True
).to(self.model.device)
if append is not None:
prepare_inputs["input_ids"] = prepare_inputs["input_ids"][:, :-1]
prepare_inputs["images_seq_mask"] = prepare_inputs["images_seq_mask"][
:, :-1
]
GRABER["input_ids"] = prepare_inputs["input_ids"]
if image is None:
GRABER["image_start_pos"] = None
GRABER["image_end_pos"] = None
else:
GRABER["image_start_pos"] = (
int(torch.where(prepare_inputs["input_ids"][0] == 100016)[0]) + 1
)
GRABER["image_end_pos"] = int(
torch.where(prepare_inputs["input_ids"][0] == 100593)[0]
)
assert GRABER["image_end_pos"] - GRABER["image_start_pos"] == 576
if append is None:
GRABER["input_ids_offset"] = len(prepare_inputs["input_ids"][0])
else:
if image is None:
conversation_origin = [
{
"role": "User",
"content": prompt,
},
{"role": "Assistant", "content": ""},
]
else:
conversation_origin = [
{
"role": "User",
"content": f"<image_placeholder>\n{prompt}",
"images": [image],
},
{"role": "Assistant", "content": ""},
]
pil_images_origin = load_pil_images(conversation)
prepare_inputs_origin = self.processor(
conversations=conversation_origin,
images=pil_images_origin,
force_batchify=True,
).to(self.model.device)
GRABER["input_ids_offset"] = len(prepare_inputs_origin["input_ids"][0])
# run image encoder to get the image embeddings
inputs_embeds = self.model.prepare_inputs_embeds(**prepare_inputs)
if conversation_cd is not None:
pil_images_cd = load_pil_images(conversation_cd)
prepare_inputs_cd = self.processor(
conversations=conversation_cd, images=pil_images_cd, force_batchify=True
).to(self.model.device)
# run image encoder to get the image embeddings
inputs_embeds_cd = self.model.prepare_inputs_embeds(**prepare_inputs_cd)
use_cd = True
else:
inputs_embeds_cd = None
use_cd = False
if use_vcd:
assert inputs_embeds_cd is not None
image_start_pos = GRABER["image_start_pos"]
image_end_pos = GRABER["image_end_pos"]
inputs_embeds_cd[:, image_start_pos:image_end_pos, :] = add_diffusion_noise(
inputs_embeds_cd[:, image_start_pos:image_end_pos, :],
noise_step=noise_step,
)
GRABER["grid_hs"] = 24
GRABER["grid_ws"] = 24
# run the model to get the response
output = self.model.language_model.generate(
inputs_embeds=inputs_embeds,
inputs_embeds_cd=inputs_embeds_cd,
input_scaling=input_scaling,
input_scaling_cd=input_scaling_cd,
cd_type=cd_type,
use_cd=use_cd,
attention_mask=prepare_inputs.attention_mask,
pad_token_id=self.tokenizer.eos_token_id,
bos_token_id=self.tokenizer.bos_token_id,
eos_token_id=self.tokenizer.eos_token_id,
use_cache=True,
**kwargs,
)
if not isinstance(output, torch.Tensor):
output_ids = output["sequences"]
generated_ids = output_ids
else:
generated_ids = output
output = None
response: str = self.tokenizer.decode(
generated_ids[0].cpu().tolist(), skip_special_tokens=True
)
response = response.lstrip()
# 4. add logs and return
model_logs = {}
if hallu_objs:
model_logs["candidates"] = hallu_objs
if caption:
model_logs["caption"] = caption
return response, output, model_logs if model_logs else None
class Qwen2VLModified(Qwen2VL, CTMixin):
def __init__(self) -> None:
from transformers.models.qwen2_vl.modeling_qwen2_vl import (
Qwen2VLForConditionalGeneration,
)
from transformers.generation.utils import GenerationMixin
from methods_utils.new_modeling_qwen2_vl_4_45_0_dev0 import (
new_Qwen2VLForConditionalGeneration_forward,
)
from methods_utils.search_methods_4_45_0_dev0 import new_sample, new_beam_search
import qwen_vl_utils
qwen_vl_utils.vision_process.MAX_PIXELS = 409_920
Qwen2VLForConditionalGeneration.forward = (
new_Qwen2VLForConditionalGeneration_forward
)
GenerationMixin._sample = new_sample # type: ignore
GenerationMixin._beam_search = new_beam_search # type: ignore
super().__init__()
def submit(
self,
prompt,
image=None,
question_id=None,
method=None,
cd_type=None,
noise_step=None,
repeat=1,
repeat_mode="continuous",
pai_alpha=None,
append=None,
sep=" ",
candidates_number=None,
ee_threshold=None,
ig_threshold=None,
ig_strategy="cos_sim",
**kwargs,
):
from qwen_vl_utils import process_vision_info
# 0. get image or video kwargs.
if image is not None and isinstance(image, str):
if image.lower().endswith((".mp4", ".mov", ".avi", ".webm", ".mkv")):
content_main = {
"type": "video",
"video": image,
"max_pixels": 360 * 420,
"fps": 1 / 3,
}
else:
content_main = {
"type": "image",
"image": image,
}
else:
content_main = {}
# 1. preprocess
hallu_objs, caption = self.preprocess_method(
image,
method,
candidates_number,
ee_threshold,
ig_threshold,
ig_strategy,
question_id,
)
if method is None:
method = "baseline"
if hallu_objs is None and method == "haltrapper":
hallu_objs = {}
# 2. Get message
if image is None:
method = "baseline"
use_vcd = False
use_ccd = False
if (
method == "haltrapper"
and hallu_objs is not None
and len(hallu_objs) != 0
and image is not None
):
messages_cd = [
{
"role": "user",
"content": [
content_main,
{"type": "text", "text": prompt},
],
}
]
use_ccd = True
elif method == "vcd" and image is not None:
messages_cd = [
{
"role": "user",
"content": [
content_main,
{"type": "text", "text": prompt},
],
}
]
use_vcd = True
elif method == "icd" and image is not None:
messages_cd = [
{
"role": "user",
"content": [
content_main,
{
"type": "text",
"text": f"You are a confused objects detector to provide a fuzzy overview or impression of the image. {prompt}",
},
],
}
]
elif method == "pai" and image is not None:
raise NotImplementedError()
elif method == "code" and image is not None:
messages_cd = [
{
"role": "user",
"content": [
{"type": "text", "text": f"{caption} {prompt}"},
],
}
]
else:
messages_cd = None
if image is None:
messages = [