forked from google-research/google-research
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathckd.patch
3716 lines (3684 loc) · 143 KB
/
ckd.patch
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
diff --git a/lavis/__init__.py b/lavis/__init__.py
index ab17686..9ea82d3 100644
--- a/lavis/__init__.py
+++ b/lavis/__init__.py
@@ -24,7 +24,8 @@ default_cfg = OmegaConf.load(os.path.join(root_dir, "configs/default.yaml"))
registry.register_path("library_root", root_dir)
repo_root = os.path.join(root_dir, "..")
registry.register_path("repo_root", repo_root)
-cache_root = os.path.join(repo_root, default_cfg.env.cache_root)
+# cache_root = os.path.join(repo_root, default_cfg.env.cache_root)
+cache_root = default_cfg.env.cache_root
registry.register_path("cache_root", cache_root)
registry.register("MAX_INT", sys.maxsize)
diff --git a/lavis/common/utils.py b/lavis/common/utils.py
index 93b93c9..cf8482b 100644
--- a/lavis/common/utils.py
+++ b/lavis/common/utils.py
@@ -18,6 +18,7 @@ import urllib.error
import urllib.request
from typing import Optional
from urllib.parse import urlparse
+from pytz import timezone
import numpy as np
import pandas as pd
@@ -37,7 +38,11 @@ from torchvision.datasets.utils import (
def now():
from datetime import datetime
- return datetime.now().strftime("%Y%m%d%H%M")[:-1]
+ # return datetime.now().strftime("%Y%m%d%H%M")[:-1]
+ fmt = '%Y_%m_%d_%H_%M_%S'
+ # EST5EDT, Asia/Calcutta
+ job_id = str(datetime.now(timezone('PST8PDT')).strftime(fmt))
+ return job_id
def is_url(url_or_filename):
diff --git a/lavis/configs/datasets/vg/defaults_caption_instruct.yaml b/lavis/configs/datasets/vg/defaults_caption_instruct.yaml
index 8015e94..7460ab1 100644
--- a/lavis/configs/datasets/vg/defaults_caption_instruct.yaml
+++ b/lavis/configs/datasets/vg/defaults_caption_instruct.yaml
@@ -31,4 +31,4 @@ datasets:
url: https://storage.googleapis.com/sfr-vision-language-research/LAVIS/datasets/visual_genome/vg_caption.json
storage: vg/annotations/vg_caption.json
images:
- storage: /export/share/datasets/vision/visual-genome/ #vg/images/
+ storage: /export/share/datasets/vision/visual-genome/ # vg/images/
\ No newline at end of file
diff --git a/lavis_ckd/configs/datasets/vg/defaults_ckd.yaml b/lavis/configs/datasets/vg/defaults_ckd.yaml
new file mode 100644
index 0000000..a57a523
--- /dev/null
+++ b/lavis/configs/datasets/vg/defaults_ckd.yaml
@@ -0,0 +1,18 @@
+
+
+datasets:
+ vg_ckd:
+ # data_dir: ${env.data_dir}/datasets
+ data_type: images # [images|videos|features]
+
+ build_info:
+ # Be careful not to append minus sign (-) before split to avoid itemizing
+ annotations:
+ train:
+ url: ''
+ storage: vg/annotations/vg_objects_hallucinated_desc.json
+ images:
+ storage: vg/images/
diff --git a/lavis/configs/default.yaml b/lavis/configs/default.yaml
index f58d32e..17ba784 100644
--- a/lavis/configs/default.yaml
+++ b/lavis/configs/default.yaml
@@ -1,10 +1,5 @@
- # Copyright (c) 2022, salesforce.com, inc.
- # All rights reserved.
- # SPDX-License-Identifier: BSD-3-Clause
- # For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
-
env:
# For default users
# cache_root: "cache"
# For internal use with persistent storage
- cache_root: "/export/home/.cache/lavis"
+ cache_root: "cache/" # TODO: change it based on your cache/data source
diff --git a/lavis_ckd/configs/models/blip2/blip2_instruct_ckd_lora_vicuna7b.yaml b/lavis/configs/models/blip2/blip2_instruct_ckd_lora_vicuna7b.yaml
new file mode 100644
index 0000000..c4ae45f
--- /dev/null
+++ b/lavis/configs/models/blip2/blip2_instruct_ckd_lora_vicuna7b.yaml
@@ -0,0 +1,43 @@
+
+
+model:
+ arch: blip2_vicuna_instruct_ckd
+ load_finetuned: False
+ load_pretrained: True
+
+ pretrained: "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/InstructBLIP/instruct_blip_vicuna7b_trimmed.pth"
+ finetuned: ""
+
+ # vit encoder
+ image_size: 224
+ drop_path_rate: 0
+ use_grad_checkpoint: False
+ vit_precision: "fp16"
+ freeze_vit: True
+
+ # Q-Former
+ num_query_token: 32
+
+ # path to Vicuna checkpoint
+ llm_model: "lmsys/vicuna-7b-v1.1" # "./llm/vicuna-7b"
+
+ # generation configs
+ prompt: ""
+
+
+preprocess:
+ vis_processor:
+ train:
+ name: "blip2_image_train"
+ image_size: 224
+ eval:
+ name: "blip_image_eval"
+ image_size: 224
+ text_processor:
+ train:
+ name: "blip_caption_ckd"
+ eval:
+ name: "blip_caption_ckd"
diff --git a/lavis_ckd/configs/models/blip2/blip2_instruct_ckd_vicuna13b.yaml b/lavis/configs/models/blip2/blip2_instruct_ckd_vicuna13b.yaml
new file mode 100644
index 0000000..2c6d315
--- /dev/null
+++ b/lavis/configs/models/blip2/blip2_instruct_ckd_vicuna13b.yaml
@@ -0,0 +1,43 @@
+
+
+model:
+ arch: blip2_vicuna_instruct_ckd
+ load_finetuned: False
+ load_pretrained: True
+
+ pretrained: "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/InstructBLIP/instruct_blip_vicuna13b_trimmed.pth"
+ finetuned: ""
+
+ # vit encoder
+ image_size: 224
+ drop_path_rate: 0
+ use_grad_checkpoint: False
+ vit_precision: "fp16"
+ freeze_vit: True
+
+ # Q-Former
+ num_query_token: 32
+
+ # path to Vicuna checkpoint
+ llm_model: "lmsys/vicuna-13b-v1.1" # "./llm/vicuna-13b"
+
+ # generation configs
+ prompt: ""
+
+
+preprocess:
+ vis_processor:
+ train:
+ name: "blip2_image_train"
+ image_size: 224
+ eval:
+ name: "blip_image_eval"
+ image_size: 224
+ text_processor:
+ train:
+ name: "blip_caption_ckd"
+ eval:
+ name: "blip_caption_ckd"
diff --git a/lavis_ckd/configs/models/blip2/blip2_instruct_ckd_vicuna7b.yaml b/lavis/configs/models/blip2/blip2_instruct_ckd_vicuna7b.yaml
new file mode 100644
index 0000000..c4ae45f
--- /dev/null
+++ b/lavis/configs/models/blip2/blip2_instruct_ckd_vicuna7b.yaml
@@ -0,0 +1,43 @@
+
+
+model:
+ arch: blip2_vicuna_instruct_ckd
+ load_finetuned: False
+ load_pretrained: True
+
+ pretrained: "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/InstructBLIP/instruct_blip_vicuna7b_trimmed.pth"
+ finetuned: ""
+
+ # vit encoder
+ image_size: 224
+ drop_path_rate: 0
+ use_grad_checkpoint: False
+ vit_precision: "fp16"
+ freeze_vit: True
+
+ # Q-Former
+ num_query_token: 32
+
+ # path to Vicuna checkpoint
+ llm_model: "lmsys/vicuna-7b-v1.1" # "./llm/vicuna-7b"
+
+ # generation configs
+ prompt: ""
+
+
+preprocess:
+ vis_processor:
+ train:
+ name: "blip2_image_train"
+ image_size: 224
+ eval:
+ name: "blip_image_eval"
+ image_size: 224
+ text_processor:
+ train:
+ name: "blip_caption_ckd"
+ eval:
+ name: "blip_caption_ckd"
diff --git a/lavis/configs/models/blip2/blip2_instruct_vicuna13b.yaml b/lavis/configs/models/blip2/blip2_instruct_vicuna13b.yaml
index 1036539..b25c941 100644
--- a/lavis/configs/models/blip2/blip2_instruct_vicuna13b.yaml
+++ b/lavis/configs/models/blip2/blip2_instruct_vicuna13b.yaml
@@ -22,7 +22,7 @@ model:
num_query_token: 32
# path to Vicuna checkpoint
- llm_model: "./llm/vicuna-13b"
+ llm_model: "lmsys/vicuna-13b-v1.1" # "./llm/vicuna-13b"
# generation configs
prompt: ""
diff --git a/lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml b/lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml
index af67777..724ee21 100644
--- a/lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml
+++ b/lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml
@@ -22,7 +22,7 @@ model:
num_query_token: 32
# path to Vicuna checkpoint
- llm_model: "./llm/vicuna-7b"
+ llm_model: "lmsys/vicuna-7b-v1.1" # "./llm/vicuna-7b"
# generation configs
prompt: ""
diff --git a/lavis/datasets/builders/__init__.py b/lavis/datasets/builders/__init__.py
index baabb36..e97a687 100644
--- a/lavis/datasets/builders/__init__.py
+++ b/lavis/datasets/builders/__init__.py
@@ -73,6 +73,7 @@ from lavis.datasets.builders.vqa_builder import (
AOKVQAInstructBuilder,
VGVQABuilder,
VGVQAInstructBuilder,
+ VGCKDBuilder,
GQABuilder,
GQAInstructBuilder,
IconQABuilder,
@@ -205,6 +206,7 @@ __all__ = [
"CharadeCaptionInstructBuilder",
"COCOVQAInstructBuilder",
"VGVQAInstructBuilder",
+ "VGCKDBuilder",
"GQAInstructBuilder",
"IconQAInstructBuilder",
"SNLIVisualEntailmentInstructBuilder",
diff --git a/lavis/datasets/builders/vqa_builder.py b/lavis/datasets/builders/vqa_builder.py
index f2684bf..750abc7 100644
--- a/lavis/datasets/builders/vqa_builder.py
+++ b/lavis/datasets/builders/vqa_builder.py
@@ -10,7 +10,7 @@ from lavis.datasets.builders.base_dataset_builder import BaseDatasetBuilder
from lavis.common.registry import registry
from lavis.datasets.datasets.aok_vqa_datasets import AOKVQADataset, AOKVQAEvalDataset, AOKVQAInstructDataset
from lavis.datasets.datasets.coco_vqa_datasets import COCOVQADataset, COCOVQAEvalDataset, COCOVQAInstructDataset
-from lavis.datasets.datasets.vg_vqa_datasets import VGVQADataset, VGVQAInstructDataset
+from lavis.datasets.datasets.vg_vqa_datasets import VGVQADataset, VGVQAInstructDataset, VGDatasetCKD
from lavis.datasets.datasets.gqa_datasets import GQADataset, GQAEvalDataset, GQAInstructDataset
from lavis.datasets.datasets.iconqa_datasets import IconQADataset, IconQAEvalDataset, IconQAInstructDataset
from lavis.datasets.datasets.ocr_datasets import OCRVQADataset, OCRVQAInstructDataset
@@ -52,6 +52,12 @@ class VGVQAInstructBuilder(BaseDatasetBuilder):
"default": "configs/datasets/vg/defaults_vqa_instruct.yaml"}
[email protected]_builder("vg_ckd")
+class VGCKDBuilder(BaseDatasetBuilder):
+ train_dataset_cls = VGDatasetCKD
+ DATASET_CONFIG_DICT = {"default": "configs/datasets/vg/defaults_ckd.yaml"}
+
+
@registry.register_builder("ok_vqa")
class OKVQABuilder(COCOVQABuilder):
DATASET_CONFIG_DICT = {
diff --git a/lavis/datasets/datasets/aok_vqa_datasets.py b/lavis/datasets/datasets/aok_vqa_datasets.py
index 4306458..2fdedfd 100644
--- a/lavis/datasets/datasets/aok_vqa_datasets.py
+++ b/lavis/datasets/datasets/aok_vqa_datasets.py
@@ -73,9 +73,30 @@ class AOKVQAInstructDataset(AOKVQADataset):
return data
def collater(self, samples):
- data = super().collater(samples)
- data['text_output'] = data['answer']
- return data
+ image_list, question_list, answer_list, weight_list = [], [], [], []
+ full_answer_list = []
+ num_answers = []
+
+ for sample in samples:
+ image_list.append(sample["image"])
+ question_list.append(sample["text_input"])
+ full_answer_list.append(sample["text_output"])
+
+ weight_list.extend(sample["weights"])
+
+ answers = sample["answers"]
+
+ answer_list.extend(answers)
+ num_answers.append(len(answers))
+
+ return {
+ "image": torch.stack(image_list, dim=0),
+ "text_input": question_list,
+ "answer": answer_list,
+ "text_output": full_answer_list,
+ "weight": torch.Tensor(weight_list),
+ "n_answers": torch.LongTensor(num_answers),
+ }
class AOKVQAEvalDataset(VQAEvalDataset, __DisplMixin):
diff --git a/lavis/datasets/datasets/vg_vqa_datasets.py b/lavis/datasets/datasets/vg_vqa_datasets.py
index 85c8ee7..815e6fa 100644
--- a/lavis/datasets/datasets/vg_vqa_datasets.py
+++ b/lavis/datasets/datasets/vg_vqa_datasets.py
@@ -11,6 +11,7 @@ import random
from PIL import Image
from lavis.datasets.datasets.vqa_datasets import VQADataset
+import torch
class VGVQADataset(VQADataset):
@@ -49,3 +50,45 @@ class VGVQAInstructDataset(VGVQADataset):
data = super().collater(samples)
data['text_output'] = data['answer']
return data
+
+
+class VGDatasetCKD(VQADataset):
+ def __init__(self, vis_processor, text_processor, vis_root, ann_paths):
+ super().__init__(vis_processor, text_processor, vis_root, ann_paths)
+
+ def __getitem__(self, index):
+ ann = self.annotation[index]
+
+ image_path = os.path.join(self.vis_root, ann["image"])
+ image = Image.open(image_path).convert("RGB")
+
+ image = self.vis_processor(image)
+ # question = self.text_processor(ann["question"])
+ question = "Describe this image in detail."
+ question = self.text_processor(question)
+
+ pos_descrition = self.text_processor(' '.join(ann["pos_description"]))
+ neg_descrition = self.text_processor(' '.join(ann["neg_description"]))
+
+ return {
+ "image": image,
+ "text_input": question,
+ "pos_descrition": pos_descrition,
+ "neg_descrition": neg_descrition,
+ }
+
+ def collater(self, samples):
+ image_list, question_list, pos_descrition_list, neg_descrition_list = [], [], [], []
+
+ for sample in samples:
+ image_list.append(sample["image"])
+ question_list.append(sample["text_input"])
+ pos_descrition_list.append(sample["pos_descrition"])
+ neg_descrition_list.append(sample["neg_descrition"])
+
+ return {
+ "image": torch.stack(image_list, dim=0),
+ "text_input": question_list,
+ "pos_descrition": pos_descrition_list,
+ "neg_descrition": neg_descrition_list,
+ }
diff --git a/lavis/models/__init__.py b/lavis/models/__init__.py
index 26ac9b2..3bce7ed 100644
--- a/lavis/models/__init__.py
+++ b/lavis/models/__init__.py
@@ -54,6 +54,9 @@ from lavis.models.gpt_models.gpt_dialogue import GPTDialogue
from lavis.processors.base_processor import BaseProcessor
+from lavis.models.blip2_models.blip2_vicuna_instruct_ckd import Blip2VicunaInstructCKD
+from lavis.models.blip2_models.blip2_vicuna_instruct_ckd_lora import Blip2VicunaInstructCKDLoRA
+
__all__ = [
"load_model",
@@ -82,7 +85,7 @@ __all__ = [
"Blip2OPT",
"Blip2T5",
"Blip2T5Instruct",
- "Blip2VicunaInstruct",
+ "Blip2VicunaInstruct", "Blip2VicunaInstructCKD", "Blip2VicunaInstructCKDLoRA",
"Blip2VicunaXInstruct",
"PNPVQA",
"Img2PromptVQA",
diff --git a/lavis/models/base_model.py b/lavis/models/base_model.py
index 50e7c43..cda61b7 100644
--- a/lavis/models/base_model.py
+++ b/lavis/models/base_model.py
@@ -92,6 +92,7 @@ class BaseModel(nn.Module):
assert (
finetune_path is not None
), "Found load_finetuned is True, but finetune_path is None."
+ logging.info(f"loading finetuned weights from: {finetune_path}")
self.load_checkpoint(url_or_filename=finetune_path)
else:
load_pretrained = cfg.get("load_pretrained", True)
@@ -99,6 +100,8 @@ class BaseModel(nn.Module):
# load pre-trained weights
pretrain_path = cfg.get("pretrained", None)
assert "Found load_finetuned is False, but pretrain_path is None."
+ logging.info(
+ f"loading pretrained weights from: {pretrain_path}")
self.load_from_pretrained(
url_or_filename=pretrain_path, **kwargs)
diff --git a/lavis/models/blip2_models/blip2.py b/lavis/models/blip2_models/blip2.py
index 98a5071..de349dc 100644
--- a/lavis/models/blip2_models/blip2.py
+++ b/lavis/models/blip2_models/blip2.py
@@ -74,10 +74,10 @@ class Blip2Base(BaseModel):
visual_encoder = create_eva_vit_g(
img_size, drop_path_rate, use_grad_checkpoint, precision
)
-# elif model_name == "eva2_clip_L":
-# visual_encoder = create_eva2_vit_L(
-# img_size, drop_path_rate, use_grad_checkpoint, precision
-# )
+ # elif model_name == "eva2_clip_L":
+ # visual_encoder = create_eva2_vit_L(
+ # img_size, drop_path_rate, use_grad_checkpoint, precision
+ # )
elif model_name == "clip_L":
visual_encoder = create_clip_vit_L(
img_size, use_grad_checkpoint, precision)
diff --git a/lavis/models/blip2_models/blip2_t5_instruct.py b/lavis/models/blip2_models/blip2_t5_instruct.py
index 4aec003..073a8d1 100644
--- a/lavis/models/blip2_models/blip2_t5_instruct.py
+++ b/lavis/models/blip2_models/blip2_t5_instruct.py
@@ -123,6 +123,8 @@ class Blip2T5Instruct(Blip2Base):
# print(samples["text_output"])
# print('-----------------')
+ print(samples)
+
image = samples["image"]
with self.maybe_autocast():
image_embeds = self.ln_vision(self.visual_encoder(image))
@@ -205,6 +207,7 @@ class Blip2T5Instruct(Blip2Base):
attention_mask=encoder_atts,
decoder_attention_mask=output_tokens.attention_mask,
return_dict=True,
+ # FIXME: targets shape is problematic -> [9, 4]; 2, 43, 2048
labels=targets,
)
loss = outputs.loss
diff --git a/lavis_ckd/models/blip2_models/blip2_t5_instruct_ckd.py b/lavis/models/blip2_models/blip2_t5_instruct_ckd.py
new file mode 100644
index 0000000..b4c08d3
--- /dev/null
+++ b/lavis/models/blip2_models/blip2_t5_instruct_ckd.py
@@ -0,0 +1,963 @@
+import logging
+import string
+import random
+import copy
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from torch.cuda.amp import autocast as autocast
+from transformers import T5TokenizerFast
+
+from lavis.common.registry import registry
+from lavis.models.blip2_models.blip2 import Blip2Base, disabled_train
+from lavis.models.blip2_models.modeling_t5 import T5Config, T5ForConditionalGeneration
+from transformers.modeling_outputs import BaseModelOutput
+from torch.nn import CrossEntropyLoss
+
+
+
+
[email protected]_model("blip2_t5_instruct_ckd")
+class Blip2T5InstructCKD(Blip2Base):
+ """
+ BLIP2 T5 model.
+ Supported model types:
+ - flant5xl
+ - flant5xxl
+ Usage:
+ >>> from lavis.models import load_model
+ >>> model = load_model("blip2_t5_kd", "flant5xl")
+ """
+
+ PRETRAINED_MODEL_CONFIG_DICT = {
+ "flant5xl": "configs/models/blip2/blip2_instruct_ckd_flant5xl.yaml",
+ "flant5xxl": "configs/models/blip2/blip2_instruct_ckd_flant5xxl.yaml",
+ }
+
+ def __init__(
+ self,
+ vit_model="eva_clip_g",
+ img_size=224,
+ drop_path_rate=0,
+ use_grad_checkpoint=False,
+ vit_precision="fp16",
+ freeze_vit=True,
+ num_query_token=32,
+ t5_model="google/flan-t5-xl",
+ prompt="",
+ max_txt_len=128,
+ max_output_txt_len=256,
+ apply_lemmatizer=False,
+ num_few_shot_examples=0,
+ few_shot_prob=0,
+ qformer_text_input=True,
+ kd_loss='ckd',
+ alpha=0.5,
+ ):
+ """
+ apply_lemmatizer: when set to True, postprocess predict_answers() result with lemmas.
+ """
+ super().__init__()
+
+ assert kd_loss in ['kd', 'ckd']
+ self.kd_loss = kd_loss
+ self.alpha=alpha
+ self.tokenizer = self.init_tokenizer(truncation_side="left")
+
+ self.visual_encoder, self.ln_vision = self.init_vision_encoder(
+ vit_model, img_size, drop_path_rate, use_grad_checkpoint, vit_precision
+ )
+ if freeze_vit:
+ for name, param in self.visual_encoder.named_parameters():
+ param.requires_grad = False
+ self.visual_encoder = self.visual_encoder.eval()
+ self.visual_encoder.train = disabled_train
+ logging.info("freeze vision encoder")
+ else:
+ logging.info("train vision encoder")
+
+ self.Qformer, self.query_tokens = self.init_Qformer(
+ num_query_token, self.visual_encoder.num_features
+ )
+
+ if not qformer_text_input:
+ self.Qformer.bert.embeddings.word_embeddings = None
+ self.Qformer.bert.embeddings.position_embeddings = None
+ for layer in self.Qformer.bert.encoder.layer:
+ layer.output = None
+ layer.intermediate = None
+ else:
+ self.Qformer.resize_token_embeddings(len(self.tokenizer))
+ self.Qformer.cls = None
+
+ self.t5_tokenizer = T5TokenizerFast.from_pretrained(t5_model, truncation_side='left')
+ self.t5_output_tokenizer = T5TokenizerFast.from_pretrained(t5_model, truncation_side='right')
+
+ t5_config = T5Config.from_pretrained(t5_model)
+ t5_config.dense_act_fn = "gelu"
+ self.t5_model = T5ForConditionalGeneration.from_pretrained(
+ t5_model, config=t5_config
+ )
+
+ for name, param in self.t5_model.named_parameters():
+ param.requires_grad = False
+ param.data = param.data.bfloat16()
+
+ self.t5_proj = nn.Linear(
+ self.Qformer.config.hidden_size, self.t5_model.config.hidden_size
+ )
+
+ self.max_txt_len = max_txt_len
+ self.max_output_txt_len = max_output_txt_len
+ self.prompt = prompt
+
+ self._apply_lemmatizer = apply_lemmatizer
+ self._lemmatizer = None
+
+ self.num_few_shot_examples = num_few_shot_examples
+ self.few_shot_prob = few_shot_prob
+
+ self.qformer_text_input = qformer_text_input
+
+ n_parameters_train = sum(p.numel() for p in self.parameters() if p.requires_grad)/ 1.e6
+ n_parameters_total = sum(p.numel() for p in self.parameters())/ 1.e6
+ logging.info(f"total trainable parameter {n_parameters_train} million - total parameter {n_parameters_total} million")
+
+ def concat_pos_neg(self,
+ pos_ids, pos_atts,
+ neg_ids, neg_atts):
+ # total_len = pos_ids.shape[1]+neg_ids.shape[1]
+ # input_part_targets_len = []
+ bs=pos_ids.size(0)
+ sign = []
+ llm_tokens = {"input_ids": [], "attention_mask": []}
+ for i in range(bs):
+ # this_input_ones = input_atts[i].sum()
+ # input_part_targets_len.append(this_input_ones)
+
+ pos_len = pos_atts[i].sum()
+ neg_len = neg_atts[i].sum()
+ llm_tokens['input_ids'].append(
+ torch.cat([
+ pos_ids[i][:pos_len],
+ neg_ids[i][:neg_len],
+ # following are ignored parts
+ pos_ids[i][pos_len:],
+ neg_ids[i][neg_len:],
+ ])
+ )
+ llm_tokens['attention_mask'].append(
+ torch.cat([
+ pos_atts[i][:pos_len],
+ neg_atts[i][:neg_len],
+ # following are ignored parts
+ pos_atts[i][pos_len:],
+ neg_atts[i][neg_len:],
+ ])
+ )
+ sign.append(torch.cat([
+ torch.ones(pos_len)*1, # positive
+ torch.ones(neg_len)*-1, # negative
+ torch.ones((len(pos_atts[i])-pos_len)+
+ (len(neg_atts[i])-neg_len))*-100, # pads ignored
+ ]))
+
+ llm_tokens['input_ids'] = torch.stack(llm_tokens['input_ids'])
+ llm_tokens['attention_mask'] = torch.stack(llm_tokens['attention_mask'])
+ sign = torch.stack(sign)
+ return llm_tokens, sign
+
+
+
+ def forward(self, samples):
+ # print('-----------------')
+ # print(samples["text_input"])
+ # print(samples["text_output"])
+ # print('-----------------')
+ DEBUG = True if samples['epoch']==0 and samples['iters']==0 else False
+ use_negatives=False
+ if self.kd_loss.startswith('ckd'):
+ use_negatives=True
+
+ image = samples["image"]
+ with self.maybe_autocast():
+ image_embeds = self.ln_vision(self.visual_encoder(image))
+
+ image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(image.device)
+
+ bs = image.size(0)
+ text_input = samples['text_input']
+ pos_descrition = samples['pos_descrition']
+ if use_negatives:
+ neg_descrition = samples['neg_descrition']
+ else:
+ neg_descrition = ['None']
+
+ if DEBUG:
+ print(f"EPOCH {samples['epoch']}", 'text_input:', text_input[0])
+ print(f"EPOCH {samples['epoch']}",
+ 'text_output: Positive:', pos_descrition[0]+' Negative: '+neg_descrition[0])
+
+ # tokenize
+ query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
+ if self.qformer_text_input:
+ text_Qformer = self.tokenizer(
+ text_input,
+ padding='longest',
+ truncation=True,
+ max_length=self.max_txt_len,
+ return_tensors="pt",
+ ).to(image.device)
+ query_atts = torch.ones(query_tokens.size()[:-1], dtype=torch.long).to(image.device)
+ Qformer_atts = torch.cat([query_atts,text_Qformer.attention_mask],dim=1)
+
+ query_output = self.Qformer.bert(
+ text_Qformer.input_ids,
+ attention_mask=Qformer_atts,
+ query_embeds=query_tokens,
+ encoder_hidden_states=image_embeds,
+ encoder_attention_mask=image_atts,
+ return_dict=True,
+ )
+ else:
+ query_output = self.Qformer.bert(
+ query_embeds=query_tokens,
+ encoder_hidden_states=image_embeds,
+ encoder_attention_mask=image_atts,
+ return_dict=True,
+ )
+
+ inputs_t5 = self.t5_proj(query_output.last_hidden_state[:,:query_tokens.size(1),:])
+ atts_t5 = torch.ones(inputs_t5.size()[:-1], dtype=torch.long).to(image.device)
+
+ # few-shot is ignored in our setup
+ fs_embeds, fs_atts = None, None
+ # if self.few_shot_prob > 0 and "few_shot_samples" in samples.keys():
+ # fs_embeds, fs_atts = self.prepare_few_shot_embeds(samples['few_shot_samples'])
+
+ with self.maybe_autocast(dtype=torch.bfloat16):
+ input_tokens = self.t5_tokenizer(
+ text_input,
+ padding="longest",
+ truncation=True,
+ max_length=self.max_txt_len,
+ return_tensors="pt",
+ ).to(image.device)
+
+ pos_rat_tokens = self.t5_output_tokenizer(
+ pos_descrition,
+ padding="longest",
+ truncation=True,
+ max_length=self.max_output_txt_len,
+ return_tensors="pt",
+ ).to(image.device)
+ if use_negatives:
+ neg_rat_tokens = self.t5_output_tokenizer(
+ neg_descrition,
+ padding="longest",
+ truncation=True,
+ max_length=self.max_output_txt_len,
+ return_tensors="pt",
+ ).to(image.device)
+
+ output_tokens = {"input_ids": [], "attention_mask": []}
+ if use_negatives:
+ output_tokens, sign = self.concat_pos_neg(
+ pos_rat_tokens.input_ids,
+ pos_rat_tokens.attention_mask,
+ neg_rat_tokens.input_ids,
+ neg_rat_tokens.attention_mask,
+ )
+ sign = sign.type(torch.long).to(image.device)
+ else:
+ output_tokens['input_ids'] = pos_rat_tokens.input_ids
+ output_tokens['attention_mask'] = pos_rat_tokens.attention_mask
+
+
+ encoder_atts = torch.cat([atts_t5, input_tokens.attention_mask], dim=1)
+
+ targets = output_tokens['input_ids'].masked_fill(
+ output_tokens['input_ids'] == self.t5_tokenizer.pad_token_id, -100
+ )
+
+ inputs_embeds = self.t5_model.encoder.embed_tokens(input_tokens.input_ids)
+ inputs_embeds = torch.cat([inputs_t5, inputs_embeds], dim=1)
+
+ ####### no contrastive kd
+ if not use_negatives:
+
+ outputs = self.t5_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=encoder_atts,
+ decoder_attention_mask=output_tokens['attention_mask'],
+ return_dict=True,
+ return_lm_logits_seq_out=True,
+ labels=targets,
+ ) # loss, lm_logits, seq_out
+
+ loss = outputs[0]
+ return {"loss": loss, 'ce_loss': loss}
+
+ ####### contrastive kd
+
+ if self.kd_loss == 'ckd':
+
+ labels = targets
+
+ # do not calculate loss for the negative desc
+ targets = targets.masked_fill(
+ sign == -1, -100
+ )
+
+ outputs = self.t5_model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=encoder_atts,
+ decoder_attention_mask=output_tokens['attention_mask'],
+ return_dict=True,
+ return_lm_logits_seq_out=True,
+ labels=targets,
+ ) # loss, lm_logits, seq_out
+
+ pos_loss, lm_logits, seq_out = outputs
+
+ # contrastive loss
+ pos_logits=[]
+ neg_targets=[]
+
+ for k in range(bs):
+ # logit
+ _logit_sign = sign[k].cpu()
+ pos_len = (_logit_sign==1).sum().item()
+ pos_start = _logit_sign.numpy().tolist().index(1) # first found location
+
+ # target
+ _label_sign = sign[k].cpu()
+ neg_len = (_label_sign==-1).sum().item()
+ neg_start = _label_sign.numpy().tolist().index(-1) # first found location
+
+ # logit-target
+ _len = min(pos_len, neg_len) # we are avoiding zero-padding and trimming
+ _pos_logits = lm_logits[k, pos_start:pos_start+_len]
+ _neg_targets = labels[k, neg_start:neg_start+_len]
+ # pad to make size same
+
+ pos_logits.append(_pos_logits)
+ neg_targets.append(_neg_targets)
+
+ pos_logits = torch.cat(pos_logits)
+ neg_targets = torch.cat(neg_targets)
+
+ neg_loss = F.nll_loss(torch.log(torch.clamp((1.0 - F.softmax(pos_logits)), min=1e-5)), neg_targets, reduction='mean')
+ loss = pos_loss * self.alpha + neg_loss * (1-self.alpha)
+
+ return {"loss": loss, 'pos_loss': pos_loss, 'neg_loss': neg_loss}
+
+
+ def pad_zero_to_match_shape(self,
+ tensor_a, # larger
+ tensor_b, # smaller
+ ):
+
+ # tensor_a = torch.randn(32, 43)
+ # tensor_b = torch.randn(32, 33)
+
+ assert tensor_a.shape[1]>tensor_b.shape[1], "first item should be the larger one"
+
+ tensor_b_padded = torch.zeros_like(tensor_a)
+ tensor_b_padded[:, :tensor_b.shape[1]] = tensor_b
+
+ return tensor_b_padded
+
+ # def prepare_few_shot_embeds(self, samples):
+ # this_n_fs = random.choices(
+ # list(range(self.num_few_shot_examples + 1)),
+ # weights=[1 - self.few_shot_prob] + [self.few_shot_prob / self.num_few_shot_examples] * self.num_few_shot_examples
+ # )[0]
+
+ # if this_n_fs == 0:
+ # return None, None
+
+ # images = []
+ # text_input = []
+ # for sample in samples:
+ # for n in range(this_n_fs):
+ # images.append(sample['image'][n])
+ # text_input.append(sample['text_input'][n])
+ # images = torch.stack(images, dim=0)
+
+ # image = images
+
+ # with self.maybe_autocast():
+ # image_embeds = self.ln_vision(self.visual_encoder(image))
+ # image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(
+ # image.device
+ # )
+
+ # query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
+ # if self.qformer_text_input:
+ # text_Qformer = self.tokenizer(
+ # text_input,
+ # padding='longest',
+ # truncation=True,
+ # max_length=self.max_txt_len,
+ # return_tensors="pt",
+ # ).to(image.device)
+ # query_atts = torch.ones(query_tokens.size()[:-1], dtype=torch.long).to(image.device)
+ # Qformer_atts = torch.cat([query_atts,text_Qformer.attention_mask],dim=1)
+ # query_output = self.Qformer.bert(
+ # text_Qformer.input_ids,
+ # attention_mask = Qformer_atts,
+ # query_embeds=query_tokens,
+ # encoder_hidden_states=image_embeds,
+ # encoder_attention_mask=image_atts,
+ # return_dict=True,
+ # )
+ # else:
+ # query_output = self.Qformer.bert(
+ # query_embeds=query_tokens,
+ # encoder_hidden_states=image_embeds,
+ # encoder_attention_mask=image_atts,
+ # return_dict=True,
+ # )
+
+ # inputs_t5 = self.t5_proj(query_output.last_hidden_state[:,:query_tokens.size(1),:])
+ # atts_t5 = torch.ones(inputs_t5.size()[:-1], dtype=torch.long).to(image.device)
+
+ # with self.maybe_autocast(dtype=torch.bfloat16):
+ # input_tokens = self.t5_tokenizer(
+ # text_input,
+ # padding="longest",
+ # truncation=True,
+ # max_length=self.max_txt_len,
+ # return_tensors="pt",
+ # ).to(image.device)
+
+ # encoder_atts = torch.cat([atts_t5, input_tokens.attention_mask], dim=1)
+
+ # inputs_embeds = self.t5_model.encoder.embed_tokens(input_tokens.input_ids)
+ # inputs_embeds = torch.cat([inputs_t5, inputs_embeds], dim=1)
+
+ # if this_n_fs > 1:
+ # encoder_atts = encoder_atts.reshape(encoder_atts.size(0) // this_n_fs, encoder_atts.size(1) * this_n_fs)
+ # inputs_embeds = inputs_embeds.reshape(inputs_embeds.size(0) // this_n_fs, inputs_embeds.size(1) * this_n_fs, inputs_embeds.size(2))
+
+ # return inputs_embeds, encoder_atts
+
+ @torch.no_grad()
+ def generate(
+ self,
+ samples,
+ use_nucleus_sampling=False,
+ num_beams=5,
+ max_length=256,
+ min_length=1,
+ top_p=0.9,
+ repetition_penalty=1.5,
+ length_penalty=1.0,
+ num_captions=1,
+ temperature=1,
+ ):
+ if "prompt" in samples.keys():
+ prompt = samples["prompt"]
+ else:
+ prompt = self.prompt
+
+ image = samples["image"]
+
+ bs = image.size(0)
+
+ if isinstance(prompt, str):
+ prompt = [prompt] * bs
+ else:
+ assert len(prompt) == bs, "The number of prompts must be equal to the batch size."
+
+ # For TextCaps
+ if "ocr_tokens" in samples.keys() and "{}" in prompt[0]:
+ prompt = [p.format(', '.join(samples['ocr_tokens'][i][:30])) for i, p in enumerate(prompt)]
+
+ query_tokens = self.query_tokens.expand(bs, -1, -1)
+ if self.qformer_text_input:
+ # remove ocr tokens in q_former (for eval textvqa)
+ # qformer_prompt = prompt
+ # qformer_prompt = ['Question: ' + qp.split(' Question: ')[1] for qp in qformer_prompt]
+
+ text_Qformer = self.tokenizer(
+ prompt,
+ padding='longest',
+ truncation=True,
+ max_length=self.max_txt_len,
+ return_tensors="pt",
+ ).to(image.device)
+ query_atts = torch.ones(query_tokens.size()[:-1], dtype=torch.long).to(image.device)
+ Qformer_atts = torch.cat([query_atts,text_Qformer.attention_mask],dim=1)
+
+ # For video data
+ if image.dim() == 5:
+ inputs_t5, atts_t5 = [], []
+ for j in range(image.size(2)):
+ this_frame = image[:,:,j,:,:]
+ with self.maybe_autocast():
+ frame_embeds = self.ln_vision(self.visual_encoder(this_frame))
+ frame_atts = torch.ones(frame_embeds.size()[:-1], dtype=torch.long).to(image.device)
+
+ if self.qformer_text_input:
+ frame_query_output = self.Qformer.bert(
+ text_Qformer.input_ids,
+ attention_mask = Qformer_atts,
+ query_embeds=query_tokens,
+ encoder_hidden_states=frame_embeds,
+ encoder_attention_mask=frame_atts,
+ return_dict=True,
+ )
+ else:
+ frame_query_output = self.Qformer.bert(
+ query_embeds=query_tokens,
+ encoder_hidden_states=frame_embeds,