qingsonglv commited on
Commit
b714305
1 Parent(s): 7201d1c

update checkpoint

Browse files
model-00001-of-00008.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:15c2451e4e0dd5caae61e91de67ea0dac7b554c4e2b39d54e67ffbe232460063
3
- size 4974581824
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c408b956a98c7e9925d6000b6372842aa0f9dc666803ea7fc544a87668ed5194
3
+ size 4974580360
model-00002-of-00008.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:351e987e5f1f28124a8c839085aeb3111e8f956393d3092439e07c7a285a5d90
3
- size 4982995648
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b43fc2b2d06591647ad69980eb442c831488bdbd0f458407afc11fa1e5944762
3
+ size 4982994176
model-00003-of-00008.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ff93f061698e4a8bbc042d9f243efd9647b19889f0e5f87188cd6bfc0400f839
3
- size 4982995728
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e8c9dee8e7f7a0b923bd56bac7939d3118a9e50db04cca4145e59a18e008447
3
+ size 4982994248
model-00004-of-00008.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:54c8f6eca491986fb61914029014d80a7813c1538807a55296530c6337fe2829
3
- size 4982995728
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b72e64848d71955d7757337727fb2713cde228720df9806f7a530b5af8e2b4c
3
+ size 4982994248
model-00005-of-00008.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:4218cb8e5bda353d4491a70054b2e8f384f00c55bcc453807309982760fc48fd
3
- size 4982995728
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6767d0c1c385e75badba18a0d9d4188e72871c1104fb5fc786573b4cb7378d87
3
+ size 4982994248
model-00006-of-00008.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:23f2f3123c49dc4fe16fa44f6ee3dd388b18490fa05966f9dd21e806e3cbd22d
3
- size 4950060832
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a90a33e6c06ad58a7abc073b555d1a22f573e78b4f4b87a1a252df8a02d3dea
3
+ size 4950060344
model.safetensors.index.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "metadata": {
3
- "total_size": 36585351552
4
  },
5
  "weight_map": {
6
  "lm_head.weight": "model-00008-of-00008.safetensors",
@@ -523,7 +523,6 @@
523
  "model.layers.0.cross_attn.dense.weight": "model-00001-of-00008.safetensors",
524
  "model.layers.0.cross_attn.key_value.weight": "model-00001-of-00008.safetensors",
525
  "model.layers.0.cross_attn.query.weight": "model-00001-of-00008.safetensors",
526
- "model.layers.0.cross_attn.rotary_emb.inv_freq": "model-00001-of-00008.safetensors",
527
  "model.layers.0.input_layernorm.weight": "model-00001-of-00008.safetensors",
528
  "model.layers.0.mlp.language_mlp.down_proj.weight": "model-00001-of-00008.safetensors",
529
  "model.layers.0.mlp.language_mlp.gate_proj.weight": "model-00001-of-00008.safetensors",
@@ -541,7 +540,6 @@
541
  "model.layers.1.cross_attn.dense.weight": "model-00001-of-00008.safetensors",
542
  "model.layers.1.cross_attn.key_value.weight": "model-00001-of-00008.safetensors",
543
  "model.layers.1.cross_attn.query.weight": "model-00001-of-00008.safetensors",
544
- "model.layers.1.cross_attn.rotary_emb.inv_freq": "model-00001-of-00008.safetensors",
545
  "model.layers.1.input_layernorm.weight": "model-00001-of-00008.safetensors",
546
  "model.layers.1.mlp.language_mlp.down_proj.weight": "model-00001-of-00008.safetensors",
547
  "model.layers.1.mlp.language_mlp.gate_proj.weight": "model-00001-of-00008.safetensors",
@@ -559,7 +557,6 @@
559
  "model.layers.10.cross_attn.dense.weight": "model-00002-of-00008.safetensors",
560
  "model.layers.10.cross_attn.key_value.weight": "model-00002-of-00008.safetensors",
561
  "model.layers.10.cross_attn.query.weight": "model-00002-of-00008.safetensors",
562
- "model.layers.10.cross_attn.rotary_emb.inv_freq": "model-00002-of-00008.safetensors",
563
  "model.layers.10.input_layernorm.weight": "model-00002-of-00008.safetensors",
564
  "model.layers.10.mlp.language_mlp.down_proj.weight": "model-00002-of-00008.safetensors",
565
  "model.layers.10.mlp.language_mlp.gate_proj.weight": "model-00002-of-00008.safetensors",
@@ -577,7 +574,6 @@
577
  "model.layers.11.cross_attn.dense.weight": "model-00002-of-00008.safetensors",
578
  "model.layers.11.cross_attn.key_value.weight": "model-00002-of-00008.safetensors",
579
  "model.layers.11.cross_attn.query.weight": "model-00002-of-00008.safetensors",
580
- "model.layers.11.cross_attn.rotary_emb.inv_freq": "model-00002-of-00008.safetensors",
581
  "model.layers.11.input_layernorm.weight": "model-00003-of-00008.safetensors",
582
  "model.layers.11.mlp.language_mlp.down_proj.weight": "model-00002-of-00008.safetensors",
583
  "model.layers.11.mlp.language_mlp.gate_proj.weight": "model-00002-of-00008.safetensors",
@@ -595,7 +591,6 @@
595
  "model.layers.12.cross_attn.dense.weight": "model-00003-of-00008.safetensors",
596
  "model.layers.12.cross_attn.key_value.weight": "model-00003-of-00008.safetensors",
597
  "model.layers.12.cross_attn.query.weight": "model-00003-of-00008.safetensors",
598
- "model.layers.12.cross_attn.rotary_emb.inv_freq": "model-00003-of-00008.safetensors",
599
  "model.layers.12.input_layernorm.weight": "model-00003-of-00008.safetensors",
600
  "model.layers.12.mlp.language_mlp.down_proj.weight": "model-00003-of-00008.safetensors",
601
  "model.layers.12.mlp.language_mlp.gate_proj.weight": "model-00003-of-00008.safetensors",
@@ -613,7 +608,6 @@
613
  "model.layers.13.cross_attn.dense.weight": "model-00003-of-00008.safetensors",
614
  "model.layers.13.cross_attn.key_value.weight": "model-00003-of-00008.safetensors",
615
  "model.layers.13.cross_attn.query.weight": "model-00003-of-00008.safetensors",
616
- "model.layers.13.cross_attn.rotary_emb.inv_freq": "model-00003-of-00008.safetensors",
617
  "model.layers.13.input_layernorm.weight": "model-00003-of-00008.safetensors",
618
  "model.layers.13.mlp.language_mlp.down_proj.weight": "model-00003-of-00008.safetensors",
619
  "model.layers.13.mlp.language_mlp.gate_proj.weight": "model-00003-of-00008.safetensors",
@@ -631,7 +625,6 @@
631
  "model.layers.14.cross_attn.dense.weight": "model-00003-of-00008.safetensors",
632
  "model.layers.14.cross_attn.key_value.weight": "model-00003-of-00008.safetensors",
633
  "model.layers.14.cross_attn.query.weight": "model-00003-of-00008.safetensors",
634
- "model.layers.14.cross_attn.rotary_emb.inv_freq": "model-00003-of-00008.safetensors",
635
  "model.layers.14.input_layernorm.weight": "model-00003-of-00008.safetensors",
636
  "model.layers.14.mlp.language_mlp.down_proj.weight": "model-00003-of-00008.safetensors",
637
  "model.layers.14.mlp.language_mlp.gate_proj.weight": "model-00003-of-00008.safetensors",
@@ -649,7 +642,6 @@
649
  "model.layers.15.cross_attn.dense.weight": "model-00003-of-00008.safetensors",
650
  "model.layers.15.cross_attn.key_value.weight": "model-00003-of-00008.safetensors",
651
  "model.layers.15.cross_attn.query.weight": "model-00003-of-00008.safetensors",
652
- "model.layers.15.cross_attn.rotary_emb.inv_freq": "model-00003-of-00008.safetensors",
653
  "model.layers.15.input_layernorm.weight": "model-00003-of-00008.safetensors",
654
  "model.layers.15.mlp.language_mlp.down_proj.weight": "model-00003-of-00008.safetensors",
655
  "model.layers.15.mlp.language_mlp.gate_proj.weight": "model-00003-of-00008.safetensors",
@@ -667,7 +659,6 @@
667
  "model.layers.16.cross_attn.dense.weight": "model-00003-of-00008.safetensors",
668
  "model.layers.16.cross_attn.key_value.weight": "model-00003-of-00008.safetensors",
669
  "model.layers.16.cross_attn.query.weight": "model-00003-of-00008.safetensors",
670
- "model.layers.16.cross_attn.rotary_emb.inv_freq": "model-00003-of-00008.safetensors",
671
  "model.layers.16.input_layernorm.weight": "model-00003-of-00008.safetensors",
672
  "model.layers.16.mlp.language_mlp.down_proj.weight": "model-00003-of-00008.safetensors",
673
  "model.layers.16.mlp.language_mlp.gate_proj.weight": "model-00003-of-00008.safetensors",
@@ -685,7 +676,6 @@
685
  "model.layers.17.cross_attn.dense.weight": "model-00003-of-00008.safetensors",
686
  "model.layers.17.cross_attn.key_value.weight": "model-00003-of-00008.safetensors",
687
  "model.layers.17.cross_attn.query.weight": "model-00003-of-00008.safetensors",
688
- "model.layers.17.cross_attn.rotary_emb.inv_freq": "model-00003-of-00008.safetensors",
689
  "model.layers.17.input_layernorm.weight": "model-00004-of-00008.safetensors",
690
  "model.layers.17.mlp.language_mlp.down_proj.weight": "model-00003-of-00008.safetensors",
691
  "model.layers.17.mlp.language_mlp.gate_proj.weight": "model-00003-of-00008.safetensors",
@@ -703,7 +693,6 @@
703
  "model.layers.18.cross_attn.dense.weight": "model-00004-of-00008.safetensors",
704
  "model.layers.18.cross_attn.key_value.weight": "model-00004-of-00008.safetensors",
705
  "model.layers.18.cross_attn.query.weight": "model-00004-of-00008.safetensors",
706
- "model.layers.18.cross_attn.rotary_emb.inv_freq": "model-00004-of-00008.safetensors",
707
  "model.layers.18.input_layernorm.weight": "model-00004-of-00008.safetensors",
708
  "model.layers.18.mlp.language_mlp.down_proj.weight": "model-00004-of-00008.safetensors",
709
  "model.layers.18.mlp.language_mlp.gate_proj.weight": "model-00004-of-00008.safetensors",
@@ -721,7 +710,6 @@
721
  "model.layers.19.cross_attn.dense.weight": "model-00004-of-00008.safetensors",
722
  "model.layers.19.cross_attn.key_value.weight": "model-00004-of-00008.safetensors",
723
  "model.layers.19.cross_attn.query.weight": "model-00004-of-00008.safetensors",
724
- "model.layers.19.cross_attn.rotary_emb.inv_freq": "model-00004-of-00008.safetensors",
725
  "model.layers.19.input_layernorm.weight": "model-00004-of-00008.safetensors",
726
  "model.layers.19.mlp.language_mlp.down_proj.weight": "model-00004-of-00008.safetensors",
727
  "model.layers.19.mlp.language_mlp.gate_proj.weight": "model-00004-of-00008.safetensors",
@@ -739,7 +727,6 @@
739
  "model.layers.2.cross_attn.dense.weight": "model-00001-of-00008.safetensors",
740
  "model.layers.2.cross_attn.key_value.weight": "model-00001-of-00008.safetensors",
741
  "model.layers.2.cross_attn.query.weight": "model-00001-of-00008.safetensors",
742
- "model.layers.2.cross_attn.rotary_emb.inv_freq": "model-00001-of-00008.safetensors",
743
  "model.layers.2.input_layernorm.weight": "model-00001-of-00008.safetensors",
744
  "model.layers.2.mlp.language_mlp.down_proj.weight": "model-00001-of-00008.safetensors",
745
  "model.layers.2.mlp.language_mlp.gate_proj.weight": "model-00001-of-00008.safetensors",
@@ -757,7 +744,6 @@
757
  "model.layers.20.cross_attn.dense.weight": "model-00004-of-00008.safetensors",
758
  "model.layers.20.cross_attn.key_value.weight": "model-00004-of-00008.safetensors",
759
  "model.layers.20.cross_attn.query.weight": "model-00004-of-00008.safetensors",
760
- "model.layers.20.cross_attn.rotary_emb.inv_freq": "model-00004-of-00008.safetensors",
761
  "model.layers.20.input_layernorm.weight": "model-00004-of-00008.safetensors",
762
  "model.layers.20.mlp.language_mlp.down_proj.weight": "model-00004-of-00008.safetensors",
763
  "model.layers.20.mlp.language_mlp.gate_proj.weight": "model-00004-of-00008.safetensors",
@@ -775,7 +761,6 @@
775
  "model.layers.21.cross_attn.dense.weight": "model-00004-of-00008.safetensors",
776
  "model.layers.21.cross_attn.key_value.weight": "model-00004-of-00008.safetensors",
777
  "model.layers.21.cross_attn.query.weight": "model-00004-of-00008.safetensors",
778
- "model.layers.21.cross_attn.rotary_emb.inv_freq": "model-00004-of-00008.safetensors",
779
  "model.layers.21.input_layernorm.weight": "model-00004-of-00008.safetensors",
780
  "model.layers.21.mlp.language_mlp.down_proj.weight": "model-00004-of-00008.safetensors",
781
  "model.layers.21.mlp.language_mlp.gate_proj.weight": "model-00004-of-00008.safetensors",
@@ -793,7 +778,6 @@
793
  "model.layers.22.cross_attn.dense.weight": "model-00004-of-00008.safetensors",
794
  "model.layers.22.cross_attn.key_value.weight": "model-00004-of-00008.safetensors",
795
  "model.layers.22.cross_attn.query.weight": "model-00004-of-00008.safetensors",
796
- "model.layers.22.cross_attn.rotary_emb.inv_freq": "model-00004-of-00008.safetensors",
797
  "model.layers.22.input_layernorm.weight": "model-00004-of-00008.safetensors",
798
  "model.layers.22.mlp.language_mlp.down_proj.weight": "model-00004-of-00008.safetensors",
799
  "model.layers.22.mlp.language_mlp.gate_proj.weight": "model-00004-of-00008.safetensors",
@@ -811,7 +795,6 @@
811
  "model.layers.23.cross_attn.dense.weight": "model-00004-of-00008.safetensors",
812
  "model.layers.23.cross_attn.key_value.weight": "model-00004-of-00008.safetensors",
813
  "model.layers.23.cross_attn.query.weight": "model-00004-of-00008.safetensors",
814
- "model.layers.23.cross_attn.rotary_emb.inv_freq": "model-00004-of-00008.safetensors",
815
  "model.layers.23.input_layernorm.weight": "model-00005-of-00008.safetensors",
816
  "model.layers.23.mlp.language_mlp.down_proj.weight": "model-00004-of-00008.safetensors",
817
  "model.layers.23.mlp.language_mlp.gate_proj.weight": "model-00004-of-00008.safetensors",
@@ -829,7 +812,6 @@
829
  "model.layers.24.cross_attn.dense.weight": "model-00005-of-00008.safetensors",
830
  "model.layers.24.cross_attn.key_value.weight": "model-00005-of-00008.safetensors",
831
  "model.layers.24.cross_attn.query.weight": "model-00005-of-00008.safetensors",
832
- "model.layers.24.cross_attn.rotary_emb.inv_freq": "model-00005-of-00008.safetensors",
833
  "model.layers.24.input_layernorm.weight": "model-00005-of-00008.safetensors",
834
  "model.layers.24.mlp.language_mlp.down_proj.weight": "model-00005-of-00008.safetensors",
835
  "model.layers.24.mlp.language_mlp.gate_proj.weight": "model-00005-of-00008.safetensors",
@@ -847,7 +829,6 @@
847
  "model.layers.25.cross_attn.dense.weight": "model-00005-of-00008.safetensors",
848
  "model.layers.25.cross_attn.key_value.weight": "model-00005-of-00008.safetensors",
849
  "model.layers.25.cross_attn.query.weight": "model-00005-of-00008.safetensors",
850
- "model.layers.25.cross_attn.rotary_emb.inv_freq": "model-00005-of-00008.safetensors",
851
  "model.layers.25.input_layernorm.weight": "model-00005-of-00008.safetensors",
852
  "model.layers.25.mlp.language_mlp.down_proj.weight": "model-00005-of-00008.safetensors",
853
  "model.layers.25.mlp.language_mlp.gate_proj.weight": "model-00005-of-00008.safetensors",
@@ -865,7 +846,6 @@
865
  "model.layers.26.cross_attn.dense.weight": "model-00005-of-00008.safetensors",
866
  "model.layers.26.cross_attn.key_value.weight": "model-00005-of-00008.safetensors",
867
  "model.layers.26.cross_attn.query.weight": "model-00005-of-00008.safetensors",
868
- "model.layers.26.cross_attn.rotary_emb.inv_freq": "model-00005-of-00008.safetensors",
869
  "model.layers.26.input_layernorm.weight": "model-00005-of-00008.safetensors",
870
  "model.layers.26.mlp.language_mlp.down_proj.weight": "model-00005-of-00008.safetensors",
871
  "model.layers.26.mlp.language_mlp.gate_proj.weight": "model-00005-of-00008.safetensors",
@@ -883,7 +863,6 @@
883
  "model.layers.27.cross_attn.dense.weight": "model-00005-of-00008.safetensors",
884
  "model.layers.27.cross_attn.key_value.weight": "model-00005-of-00008.safetensors",
885
  "model.layers.27.cross_attn.query.weight": "model-00005-of-00008.safetensors",
886
- "model.layers.27.cross_attn.rotary_emb.inv_freq": "model-00005-of-00008.safetensors",
887
  "model.layers.27.input_layernorm.weight": "model-00005-of-00008.safetensors",
888
  "model.layers.27.mlp.language_mlp.down_proj.weight": "model-00005-of-00008.safetensors",
889
  "model.layers.27.mlp.language_mlp.gate_proj.weight": "model-00005-of-00008.safetensors",
@@ -901,7 +880,6 @@
901
  "model.layers.28.cross_attn.dense.weight": "model-00005-of-00008.safetensors",
902
  "model.layers.28.cross_attn.key_value.weight": "model-00005-of-00008.safetensors",
903
  "model.layers.28.cross_attn.query.weight": "model-00005-of-00008.safetensors",
904
- "model.layers.28.cross_attn.rotary_emb.inv_freq": "model-00005-of-00008.safetensors",
905
  "model.layers.28.input_layernorm.weight": "model-00005-of-00008.safetensors",
906
  "model.layers.28.mlp.language_mlp.down_proj.weight": "model-00005-of-00008.safetensors",
907
  "model.layers.28.mlp.language_mlp.gate_proj.weight": "model-00005-of-00008.safetensors",
@@ -919,7 +897,6 @@
919
  "model.layers.29.cross_attn.dense.weight": "model-00005-of-00008.safetensors",
920
  "model.layers.29.cross_attn.key_value.weight": "model-00005-of-00008.safetensors",
921
  "model.layers.29.cross_attn.query.weight": "model-00005-of-00008.safetensors",
922
- "model.layers.29.cross_attn.rotary_emb.inv_freq": "model-00005-of-00008.safetensors",
923
  "model.layers.29.input_layernorm.weight": "model-00006-of-00008.safetensors",
924
  "model.layers.29.mlp.language_mlp.down_proj.weight": "model-00005-of-00008.safetensors",
925
  "model.layers.29.mlp.language_mlp.gate_proj.weight": "model-00005-of-00008.safetensors",
@@ -937,7 +914,6 @@
937
  "model.layers.3.cross_attn.dense.weight": "model-00001-of-00008.safetensors",
938
  "model.layers.3.cross_attn.key_value.weight": "model-00001-of-00008.safetensors",
939
  "model.layers.3.cross_attn.query.weight": "model-00001-of-00008.safetensors",
940
- "model.layers.3.cross_attn.rotary_emb.inv_freq": "model-00001-of-00008.safetensors",
941
  "model.layers.3.input_layernorm.weight": "model-00001-of-00008.safetensors",
942
  "model.layers.3.mlp.language_mlp.down_proj.weight": "model-00001-of-00008.safetensors",
943
  "model.layers.3.mlp.language_mlp.gate_proj.weight": "model-00001-of-00008.safetensors",
@@ -955,7 +931,6 @@
955
  "model.layers.30.cross_attn.dense.weight": "model-00006-of-00008.safetensors",
956
  "model.layers.30.cross_attn.key_value.weight": "model-00006-of-00008.safetensors",
957
  "model.layers.30.cross_attn.query.weight": "model-00006-of-00008.safetensors",
958
- "model.layers.30.cross_attn.rotary_emb.inv_freq": "model-00006-of-00008.safetensors",
959
  "model.layers.30.input_layernorm.weight": "model-00006-of-00008.safetensors",
960
  "model.layers.30.mlp.language_mlp.down_proj.weight": "model-00006-of-00008.safetensors",
961
  "model.layers.30.mlp.language_mlp.gate_proj.weight": "model-00006-of-00008.safetensors",
@@ -973,7 +948,6 @@
973
  "model.layers.31.cross_attn.dense.weight": "model-00006-of-00008.safetensors",
974
  "model.layers.31.cross_attn.key_value.weight": "model-00006-of-00008.safetensors",
975
  "model.layers.31.cross_attn.query.weight": "model-00006-of-00008.safetensors",
976
- "model.layers.31.cross_attn.rotary_emb.inv_freq": "model-00006-of-00008.safetensors",
977
  "model.layers.31.input_layernorm.weight": "model-00006-of-00008.safetensors",
978
  "model.layers.31.mlp.language_mlp.down_proj.weight": "model-00006-of-00008.safetensors",
979
  "model.layers.31.mlp.language_mlp.gate_proj.weight": "model-00006-of-00008.safetensors",
@@ -991,7 +965,6 @@
991
  "model.layers.4.cross_attn.dense.weight": "model-00001-of-00008.safetensors",
992
  "model.layers.4.cross_attn.key_value.weight": "model-00001-of-00008.safetensors",
993
  "model.layers.4.cross_attn.query.weight": "model-00001-of-00008.safetensors",
994
- "model.layers.4.cross_attn.rotary_emb.inv_freq": "model-00001-of-00008.safetensors",
995
  "model.layers.4.input_layernorm.weight": "model-00001-of-00008.safetensors",
996
  "model.layers.4.mlp.language_mlp.down_proj.weight": "model-00001-of-00008.safetensors",
997
  "model.layers.4.mlp.language_mlp.gate_proj.weight": "model-00001-of-00008.safetensors",
@@ -1009,7 +982,6 @@
1009
  "model.layers.5.cross_attn.dense.weight": "model-00001-of-00008.safetensors",
1010
  "model.layers.5.cross_attn.key_value.weight": "model-00001-of-00008.safetensors",
1011
  "model.layers.5.cross_attn.query.weight": "model-00001-of-00008.safetensors",
1012
- "model.layers.5.cross_attn.rotary_emb.inv_freq": "model-00001-of-00008.safetensors",
1013
  "model.layers.5.input_layernorm.weight": "model-00002-of-00008.safetensors",
1014
  "model.layers.5.mlp.language_mlp.down_proj.weight": "model-00001-of-00008.safetensors",
1015
  "model.layers.5.mlp.language_mlp.gate_proj.weight": "model-00001-of-00008.safetensors",
@@ -1027,7 +999,6 @@
1027
  "model.layers.6.cross_attn.dense.weight": "model-00002-of-00008.safetensors",
1028
  "model.layers.6.cross_attn.key_value.weight": "model-00002-of-00008.safetensors",
1029
  "model.layers.6.cross_attn.query.weight": "model-00002-of-00008.safetensors",
1030
- "model.layers.6.cross_attn.rotary_emb.inv_freq": "model-00002-of-00008.safetensors",
1031
  "model.layers.6.input_layernorm.weight": "model-00002-of-00008.safetensors",
1032
  "model.layers.6.mlp.language_mlp.down_proj.weight": "model-00002-of-00008.safetensors",
1033
  "model.layers.6.mlp.language_mlp.gate_proj.weight": "model-00002-of-00008.safetensors",
@@ -1045,7 +1016,6 @@
1045
  "model.layers.7.cross_attn.dense.weight": "model-00002-of-00008.safetensors",
1046
  "model.layers.7.cross_attn.key_value.weight": "model-00002-of-00008.safetensors",
1047
  "model.layers.7.cross_attn.query.weight": "model-00002-of-00008.safetensors",
1048
- "model.layers.7.cross_attn.rotary_emb.inv_freq": "model-00002-of-00008.safetensors",
1049
  "model.layers.7.input_layernorm.weight": "model-00002-of-00008.safetensors",
1050
  "model.layers.7.mlp.language_mlp.down_proj.weight": "model-00002-of-00008.safetensors",
1051
  "model.layers.7.mlp.language_mlp.gate_proj.weight": "model-00002-of-00008.safetensors",
@@ -1063,7 +1033,6 @@
1063
  "model.layers.8.cross_attn.dense.weight": "model-00002-of-00008.safetensors",
1064
  "model.layers.8.cross_attn.key_value.weight": "model-00002-of-00008.safetensors",
1065
  "model.layers.8.cross_attn.query.weight": "model-00002-of-00008.safetensors",
1066
- "model.layers.8.cross_attn.rotary_emb.inv_freq": "model-00002-of-00008.safetensors",
1067
  "model.layers.8.input_layernorm.weight": "model-00002-of-00008.safetensors",
1068
  "model.layers.8.mlp.language_mlp.down_proj.weight": "model-00002-of-00008.safetensors",
1069
  "model.layers.8.mlp.language_mlp.gate_proj.weight": "model-00002-of-00008.safetensors",
@@ -1081,7 +1050,6 @@
1081
  "model.layers.9.cross_attn.dense.weight": "model-00002-of-00008.safetensors",
1082
  "model.layers.9.cross_attn.key_value.weight": "model-00002-of-00008.safetensors",
1083
  "model.layers.9.cross_attn.query.weight": "model-00002-of-00008.safetensors",
1084
- "model.layers.9.cross_attn.rotary_emb.inv_freq": "model-00002-of-00008.safetensors",
1085
  "model.layers.9.input_layernorm.weight": "model-00002-of-00008.safetensors",
1086
  "model.layers.9.mlp.language_mlp.down_proj.weight": "model-00002-of-00008.safetensors",
1087
  "model.layers.9.mlp.language_mlp.gate_proj.weight": "model-00002-of-00008.safetensors",
 
1
  {
2
  "metadata": {
3
+ "total_size": 36585347456
4
  },
5
  "weight_map": {
6
  "lm_head.weight": "model-00008-of-00008.safetensors",
 
523
  "model.layers.0.cross_attn.dense.weight": "model-00001-of-00008.safetensors",
524
  "model.layers.0.cross_attn.key_value.weight": "model-00001-of-00008.safetensors",
525
  "model.layers.0.cross_attn.query.weight": "model-00001-of-00008.safetensors",
 
526
  "model.layers.0.input_layernorm.weight": "model-00001-of-00008.safetensors",
527
  "model.layers.0.mlp.language_mlp.down_proj.weight": "model-00001-of-00008.safetensors",
528
  "model.layers.0.mlp.language_mlp.gate_proj.weight": "model-00001-of-00008.safetensors",
 
540
  "model.layers.1.cross_attn.dense.weight": "model-00001-of-00008.safetensors",
541
  "model.layers.1.cross_attn.key_value.weight": "model-00001-of-00008.safetensors",
542
  "model.layers.1.cross_attn.query.weight": "model-00001-of-00008.safetensors",
 
543
  "model.layers.1.input_layernorm.weight": "model-00001-of-00008.safetensors",
544
  "model.layers.1.mlp.language_mlp.down_proj.weight": "model-00001-of-00008.safetensors",
545
  "model.layers.1.mlp.language_mlp.gate_proj.weight": "model-00001-of-00008.safetensors",
 
557
  "model.layers.10.cross_attn.dense.weight": "model-00002-of-00008.safetensors",
558
  "model.layers.10.cross_attn.key_value.weight": "model-00002-of-00008.safetensors",
559
  "model.layers.10.cross_attn.query.weight": "model-00002-of-00008.safetensors",
 
560
  "model.layers.10.input_layernorm.weight": "model-00002-of-00008.safetensors",
561
  "model.layers.10.mlp.language_mlp.down_proj.weight": "model-00002-of-00008.safetensors",
562
  "model.layers.10.mlp.language_mlp.gate_proj.weight": "model-00002-of-00008.safetensors",
 
574
  "model.layers.11.cross_attn.dense.weight": "model-00002-of-00008.safetensors",
575
  "model.layers.11.cross_attn.key_value.weight": "model-00002-of-00008.safetensors",
576
  "model.layers.11.cross_attn.query.weight": "model-00002-of-00008.safetensors",
 
577
  "model.layers.11.input_layernorm.weight": "model-00003-of-00008.safetensors",
578
  "model.layers.11.mlp.language_mlp.down_proj.weight": "model-00002-of-00008.safetensors",
579
  "model.layers.11.mlp.language_mlp.gate_proj.weight": "model-00002-of-00008.safetensors",
 
591
  "model.layers.12.cross_attn.dense.weight": "model-00003-of-00008.safetensors",
592
  "model.layers.12.cross_attn.key_value.weight": "model-00003-of-00008.safetensors",
593
  "model.layers.12.cross_attn.query.weight": "model-00003-of-00008.safetensors",
 
594
  "model.layers.12.input_layernorm.weight": "model-00003-of-00008.safetensors",
595
  "model.layers.12.mlp.language_mlp.down_proj.weight": "model-00003-of-00008.safetensors",
596
  "model.layers.12.mlp.language_mlp.gate_proj.weight": "model-00003-of-00008.safetensors",
 
608
  "model.layers.13.cross_attn.dense.weight": "model-00003-of-00008.safetensors",
609
  "model.layers.13.cross_attn.key_value.weight": "model-00003-of-00008.safetensors",
610
  "model.layers.13.cross_attn.query.weight": "model-00003-of-00008.safetensors",
 
611
  "model.layers.13.input_layernorm.weight": "model-00003-of-00008.safetensors",
612
  "model.layers.13.mlp.language_mlp.down_proj.weight": "model-00003-of-00008.safetensors",
613
  "model.layers.13.mlp.language_mlp.gate_proj.weight": "model-00003-of-00008.safetensors",
 
625
  "model.layers.14.cross_attn.dense.weight": "model-00003-of-00008.safetensors",
626
  "model.layers.14.cross_attn.key_value.weight": "model-00003-of-00008.safetensors",
627
  "model.layers.14.cross_attn.query.weight": "model-00003-of-00008.safetensors",
 
628
  "model.layers.14.input_layernorm.weight": "model-00003-of-00008.safetensors",
629
  "model.layers.14.mlp.language_mlp.down_proj.weight": "model-00003-of-00008.safetensors",
630
  "model.layers.14.mlp.language_mlp.gate_proj.weight": "model-00003-of-00008.safetensors",
 
642
  "model.layers.15.cross_attn.dense.weight": "model-00003-of-00008.safetensors",
643
  "model.layers.15.cross_attn.key_value.weight": "model-00003-of-00008.safetensors",
644
  "model.layers.15.cross_attn.query.weight": "model-00003-of-00008.safetensors",
 
645
  "model.layers.15.input_layernorm.weight": "model-00003-of-00008.safetensors",
646
  "model.layers.15.mlp.language_mlp.down_proj.weight": "model-00003-of-00008.safetensors",
647
  "model.layers.15.mlp.language_mlp.gate_proj.weight": "model-00003-of-00008.safetensors",
 
659
  "model.layers.16.cross_attn.dense.weight": "model-00003-of-00008.safetensors",
660
  "model.layers.16.cross_attn.key_value.weight": "model-00003-of-00008.safetensors",
661
  "model.layers.16.cross_attn.query.weight": "model-00003-of-00008.safetensors",
 
662
  "model.layers.16.input_layernorm.weight": "model-00003-of-00008.safetensors",
663
  "model.layers.16.mlp.language_mlp.down_proj.weight": "model-00003-of-00008.safetensors",
664
  "model.layers.16.mlp.language_mlp.gate_proj.weight": "model-00003-of-00008.safetensors",
 
676
  "model.layers.17.cross_attn.dense.weight": "model-00003-of-00008.safetensors",
677
  "model.layers.17.cross_attn.key_value.weight": "model-00003-of-00008.safetensors",
678
  "model.layers.17.cross_attn.query.weight": "model-00003-of-00008.safetensors",
 
679
  "model.layers.17.input_layernorm.weight": "model-00004-of-00008.safetensors",
680
  "model.layers.17.mlp.language_mlp.down_proj.weight": "model-00003-of-00008.safetensors",
681
  "model.layers.17.mlp.language_mlp.gate_proj.weight": "model-00003-of-00008.safetensors",
 
693
  "model.layers.18.cross_attn.dense.weight": "model-00004-of-00008.safetensors",
694
  "model.layers.18.cross_attn.key_value.weight": "model-00004-of-00008.safetensors",
695
  "model.layers.18.cross_attn.query.weight": "model-00004-of-00008.safetensors",
 
696
  "model.layers.18.input_layernorm.weight": "model-00004-of-00008.safetensors",
697
  "model.layers.18.mlp.language_mlp.down_proj.weight": "model-00004-of-00008.safetensors",
698
  "model.layers.18.mlp.language_mlp.gate_proj.weight": "model-00004-of-00008.safetensors",
 
710
  "model.layers.19.cross_attn.dense.weight": "model-00004-of-00008.safetensors",
711
  "model.layers.19.cross_attn.key_value.weight": "model-00004-of-00008.safetensors",
712
  "model.layers.19.cross_attn.query.weight": "model-00004-of-00008.safetensors",
 
713
  "model.layers.19.input_layernorm.weight": "model-00004-of-00008.safetensors",
714
  "model.layers.19.mlp.language_mlp.down_proj.weight": "model-00004-of-00008.safetensors",
715
  "model.layers.19.mlp.language_mlp.gate_proj.weight": "model-00004-of-00008.safetensors",
 
727
  "model.layers.2.cross_attn.dense.weight": "model-00001-of-00008.safetensors",
728
  "model.layers.2.cross_attn.key_value.weight": "model-00001-of-00008.safetensors",
729
  "model.layers.2.cross_attn.query.weight": "model-00001-of-00008.safetensors",
 
730
  "model.layers.2.input_layernorm.weight": "model-00001-of-00008.safetensors",
731
  "model.layers.2.mlp.language_mlp.down_proj.weight": "model-00001-of-00008.safetensors",
732
  "model.layers.2.mlp.language_mlp.gate_proj.weight": "model-00001-of-00008.safetensors",
 
744
  "model.layers.20.cross_attn.dense.weight": "model-00004-of-00008.safetensors",
745
  "model.layers.20.cross_attn.key_value.weight": "model-00004-of-00008.safetensors",
746
  "model.layers.20.cross_attn.query.weight": "model-00004-of-00008.safetensors",
 
747
  "model.layers.20.input_layernorm.weight": "model-00004-of-00008.safetensors",
748
  "model.layers.20.mlp.language_mlp.down_proj.weight": "model-00004-of-00008.safetensors",
749
  "model.layers.20.mlp.language_mlp.gate_proj.weight": "model-00004-of-00008.safetensors",
 
761
  "model.layers.21.cross_attn.dense.weight": "model-00004-of-00008.safetensors",
762
  "model.layers.21.cross_attn.key_value.weight": "model-00004-of-00008.safetensors",
763
  "model.layers.21.cross_attn.query.weight": "model-00004-of-00008.safetensors",
 
764
  "model.layers.21.input_layernorm.weight": "model-00004-of-00008.safetensors",
765
  "model.layers.21.mlp.language_mlp.down_proj.weight": "model-00004-of-00008.safetensors",
766
  "model.layers.21.mlp.language_mlp.gate_proj.weight": "model-00004-of-00008.safetensors",
 
778
  "model.layers.22.cross_attn.dense.weight": "model-00004-of-00008.safetensors",
779
  "model.layers.22.cross_attn.key_value.weight": "model-00004-of-00008.safetensors",
780
  "model.layers.22.cross_attn.query.weight": "model-00004-of-00008.safetensors",
 
781
  "model.layers.22.input_layernorm.weight": "model-00004-of-00008.safetensors",
782
  "model.layers.22.mlp.language_mlp.down_proj.weight": "model-00004-of-00008.safetensors",
783
  "model.layers.22.mlp.language_mlp.gate_proj.weight": "model-00004-of-00008.safetensors",
 
795
  "model.layers.23.cross_attn.dense.weight": "model-00004-of-00008.safetensors",
796
  "model.layers.23.cross_attn.key_value.weight": "model-00004-of-00008.safetensors",
797
  "model.layers.23.cross_attn.query.weight": "model-00004-of-00008.safetensors",
 
798
  "model.layers.23.input_layernorm.weight": "model-00005-of-00008.safetensors",
799
  "model.layers.23.mlp.language_mlp.down_proj.weight": "model-00004-of-00008.safetensors",
800
  "model.layers.23.mlp.language_mlp.gate_proj.weight": "model-00004-of-00008.safetensors",
 
812
  "model.layers.24.cross_attn.dense.weight": "model-00005-of-00008.safetensors",
813
  "model.layers.24.cross_attn.key_value.weight": "model-00005-of-00008.safetensors",
814
  "model.layers.24.cross_attn.query.weight": "model-00005-of-00008.safetensors",
 
815
  "model.layers.24.input_layernorm.weight": "model-00005-of-00008.safetensors",
816
  "model.layers.24.mlp.language_mlp.down_proj.weight": "model-00005-of-00008.safetensors",
817
  "model.layers.24.mlp.language_mlp.gate_proj.weight": "model-00005-of-00008.safetensors",
 
829
  "model.layers.25.cross_attn.dense.weight": "model-00005-of-00008.safetensors",
830
  "model.layers.25.cross_attn.key_value.weight": "model-00005-of-00008.safetensors",
831
  "model.layers.25.cross_attn.query.weight": "model-00005-of-00008.safetensors",
 
832
  "model.layers.25.input_layernorm.weight": "model-00005-of-00008.safetensors",
833
  "model.layers.25.mlp.language_mlp.down_proj.weight": "model-00005-of-00008.safetensors",
834
  "model.layers.25.mlp.language_mlp.gate_proj.weight": "model-00005-of-00008.safetensors",
 
846
  "model.layers.26.cross_attn.dense.weight": "model-00005-of-00008.safetensors",
847
  "model.layers.26.cross_attn.key_value.weight": "model-00005-of-00008.safetensors",
848
  "model.layers.26.cross_attn.query.weight": "model-00005-of-00008.safetensors",
 
849
  "model.layers.26.input_layernorm.weight": "model-00005-of-00008.safetensors",
850
  "model.layers.26.mlp.language_mlp.down_proj.weight": "model-00005-of-00008.safetensors",
851
  "model.layers.26.mlp.language_mlp.gate_proj.weight": "model-00005-of-00008.safetensors",
 
863
  "model.layers.27.cross_attn.dense.weight": "model-00005-of-00008.safetensors",
864
  "model.layers.27.cross_attn.key_value.weight": "model-00005-of-00008.safetensors",
865
  "model.layers.27.cross_attn.query.weight": "model-00005-of-00008.safetensors",
 
866
  "model.layers.27.input_layernorm.weight": "model-00005-of-00008.safetensors",
867
  "model.layers.27.mlp.language_mlp.down_proj.weight": "model-00005-of-00008.safetensors",
868
  "model.layers.27.mlp.language_mlp.gate_proj.weight": "model-00005-of-00008.safetensors",
 
880
  "model.layers.28.cross_attn.dense.weight": "model-00005-of-00008.safetensors",
881
  "model.layers.28.cross_attn.key_value.weight": "model-00005-of-00008.safetensors",
882
  "model.layers.28.cross_attn.query.weight": "model-00005-of-00008.safetensors",
 
883
  "model.layers.28.input_layernorm.weight": "model-00005-of-00008.safetensors",
884
  "model.layers.28.mlp.language_mlp.down_proj.weight": "model-00005-of-00008.safetensors",
885
  "model.layers.28.mlp.language_mlp.gate_proj.weight": "model-00005-of-00008.safetensors",
 
897
  "model.layers.29.cross_attn.dense.weight": "model-00005-of-00008.safetensors",
898
  "model.layers.29.cross_attn.key_value.weight": "model-00005-of-00008.safetensors",
899
  "model.layers.29.cross_attn.query.weight": "model-00005-of-00008.safetensors",
 
900
  "model.layers.29.input_layernorm.weight": "model-00006-of-00008.safetensors",
901
  "model.layers.29.mlp.language_mlp.down_proj.weight": "model-00005-of-00008.safetensors",
902
  "model.layers.29.mlp.language_mlp.gate_proj.weight": "model-00005-of-00008.safetensors",
 
914
  "model.layers.3.cross_attn.dense.weight": "model-00001-of-00008.safetensors",
915
  "model.layers.3.cross_attn.key_value.weight": "model-00001-of-00008.safetensors",
916
  "model.layers.3.cross_attn.query.weight": "model-00001-of-00008.safetensors",
 
917
  "model.layers.3.input_layernorm.weight": "model-00001-of-00008.safetensors",
918
  "model.layers.3.mlp.language_mlp.down_proj.weight": "model-00001-of-00008.safetensors",
919
  "model.layers.3.mlp.language_mlp.gate_proj.weight": "model-00001-of-00008.safetensors",
 
931
  "model.layers.30.cross_attn.dense.weight": "model-00006-of-00008.safetensors",
932
  "model.layers.30.cross_attn.key_value.weight": "model-00006-of-00008.safetensors",
933
  "model.layers.30.cross_attn.query.weight": "model-00006-of-00008.safetensors",
 
934
  "model.layers.30.input_layernorm.weight": "model-00006-of-00008.safetensors",
935
  "model.layers.30.mlp.language_mlp.down_proj.weight": "model-00006-of-00008.safetensors",
936
  "model.layers.30.mlp.language_mlp.gate_proj.weight": "model-00006-of-00008.safetensors",
 
948
  "model.layers.31.cross_attn.dense.weight": "model-00006-of-00008.safetensors",
949
  "model.layers.31.cross_attn.key_value.weight": "model-00006-of-00008.safetensors",
950
  "model.layers.31.cross_attn.query.weight": "model-00006-of-00008.safetensors",
 
951
  "model.layers.31.input_layernorm.weight": "model-00006-of-00008.safetensors",
952
  "model.layers.31.mlp.language_mlp.down_proj.weight": "model-00006-of-00008.safetensors",
953
  "model.layers.31.mlp.language_mlp.gate_proj.weight": "model-00006-of-00008.safetensors",
 
965
  "model.layers.4.cross_attn.dense.weight": "model-00001-of-00008.safetensors",
966
  "model.layers.4.cross_attn.key_value.weight": "model-00001-of-00008.safetensors",
967
  "model.layers.4.cross_attn.query.weight": "model-00001-of-00008.safetensors",
 
968
  "model.layers.4.input_layernorm.weight": "model-00001-of-00008.safetensors",
969
  "model.layers.4.mlp.language_mlp.down_proj.weight": "model-00001-of-00008.safetensors",
970
  "model.layers.4.mlp.language_mlp.gate_proj.weight": "model-00001-of-00008.safetensors",
 
982
  "model.layers.5.cross_attn.dense.weight": "model-00001-of-00008.safetensors",
983
  "model.layers.5.cross_attn.key_value.weight": "model-00001-of-00008.safetensors",
984
  "model.layers.5.cross_attn.query.weight": "model-00001-of-00008.safetensors",
 
985
  "model.layers.5.input_layernorm.weight": "model-00002-of-00008.safetensors",
986
  "model.layers.5.mlp.language_mlp.down_proj.weight": "model-00001-of-00008.safetensors",
987
  "model.layers.5.mlp.language_mlp.gate_proj.weight": "model-00001-of-00008.safetensors",
 
999
  "model.layers.6.cross_attn.dense.weight": "model-00002-of-00008.safetensors",
1000
  "model.layers.6.cross_attn.key_value.weight": "model-00002-of-00008.safetensors",
1001
  "model.layers.6.cross_attn.query.weight": "model-00002-of-00008.safetensors",
 
1002
  "model.layers.6.input_layernorm.weight": "model-00002-of-00008.safetensors",
1003
  "model.layers.6.mlp.language_mlp.down_proj.weight": "model-00002-of-00008.safetensors",
1004
  "model.layers.6.mlp.language_mlp.gate_proj.weight": "model-00002-of-00008.safetensors",
 
1016
  "model.layers.7.cross_attn.dense.weight": "model-00002-of-00008.safetensors",
1017
  "model.layers.7.cross_attn.key_value.weight": "model-00002-of-00008.safetensors",
1018
  "model.layers.7.cross_attn.query.weight": "model-00002-of-00008.safetensors",
 
1019
  "model.layers.7.input_layernorm.weight": "model-00002-of-00008.safetensors",
1020
  "model.layers.7.mlp.language_mlp.down_proj.weight": "model-00002-of-00008.safetensors",
1021
  "model.layers.7.mlp.language_mlp.gate_proj.weight": "model-00002-of-00008.safetensors",
 
1033
  "model.layers.8.cross_attn.dense.weight": "model-00002-of-00008.safetensors",
1034
  "model.layers.8.cross_attn.key_value.weight": "model-00002-of-00008.safetensors",
1035
  "model.layers.8.cross_attn.query.weight": "model-00002-of-00008.safetensors",
 
1036
  "model.layers.8.input_layernorm.weight": "model-00002-of-00008.safetensors",
1037
  "model.layers.8.mlp.language_mlp.down_proj.weight": "model-00002-of-00008.safetensors",
1038
  "model.layers.8.mlp.language_mlp.gate_proj.weight": "model-00002-of-00008.safetensors",
 
1050
  "model.layers.9.cross_attn.dense.weight": "model-00002-of-00008.safetensors",
1051
  "model.layers.9.cross_attn.key_value.weight": "model-00002-of-00008.safetensors",
1052
  "model.layers.9.cross_attn.query.weight": "model-00002-of-00008.safetensors",
 
1053
  "model.layers.9.input_layernorm.weight": "model-00002-of-00008.safetensors",
1054
  "model.layers.9.mlp.language_mlp.down_proj.weight": "model-00002-of-00008.safetensors",
1055
  "model.layers.9.mlp.language_mlp.gate_proj.weight": "model-00002-of-00008.safetensors",
modeling_cogagent.py CHANGED
@@ -1,958 +1,974 @@
1
- """largely copy from llama and adapt for CogAgent"""
2
- import warnings
3
- from typing import TYPE_CHECKING, Optional, Tuple, List, Union, Literal, Dict, Any
4
-
5
- import math
6
- import torch
7
- from torch import nn
8
- from torch.nn import CrossEntropyLoss
9
- from torchvision import transforms
10
- from einops import rearrange
11
-
12
- from transformers import PreTrainedModel, PreTrainedTokenizer
13
- from transformers.utils.logging import get_logger
14
- from transformers.activations import ACT2FN
15
- from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
16
-
17
- from .configuration_cogagent import CogAgentConfig
18
- # from .util import FastRotaryEmbedding
19
- from torch.nn import functional as F
20
- from .visual import EVA2CLIPModel
21
- from .cross_visual import CrossVisionModel
22
-
23
- if TYPE_CHECKING:
24
- from transformers.utils import ModelOutput
25
-
26
- logger = get_logger(__name__)
27
-
28
- LANGUAGE_TOKEN_TYPE = 0
29
- VISION_TOKEN_TYPE = 1
30
-
31
-
32
- # Copied from transformers.models.bart.modeling_bart._make_causal_mask
33
- def _make_causal_mask(
34
- input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
35
- ):
36
- """
37
- Make causal mask used for bi-directional self-attention.
38
- """
39
- bsz, tgt_len = input_ids_shape
40
- mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
41
- mask_cond = torch.arange(mask.size(-1), device=device)
42
- mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
43
- mask = mask.to(dtype)
44
-
45
- if past_key_values_length > 0:
46
- mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
47
- return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
48
-
49
-
50
- # Copied from transformers.models.bart.modeling_bart._expand_mask
51
- def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
52
- """
53
- Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
54
- """
55
- bsz, src_len = mask.size()
56
- tgt_len = tgt_len if tgt_len is not None else src_len
57
-
58
- expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
59
-
60
- inverted_mask = 1.0 - expanded_mask
61
-
62
- return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
63
-
64
-
65
- class RMSNorm(nn.Module):
66
- def __init__(self, hidden_size, eps=1e-6):
67
- super().__init__()
68
- self.weight = nn.Parameter(torch.ones(hidden_size))
69
- self.variance_epsilon = eps
70
-
71
- def forward(self, hidden_states):
72
- input_dtype = hidden_states.dtype
73
- hidden_states = hidden_states.to(torch.float32)
74
- variance = hidden_states.pow(2).mean(-1, keepdim=True)
75
- hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
76
- return (self.weight * hidden_states).to(input_dtype)
77
-
78
-
79
- class MLP(nn.Module):
80
- def __init__(self, config):
81
- super().__init__()
82
- self.hidden_size = config.hidden_size
83
- self.intermediate_size = config.intermediate_size
84
- self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
85
- self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
86
- self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
87
- self.act_fn = ACT2FN[config.hidden_act]
88
-
89
- def forward(self, x):
90
- down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
91
- return down_proj
92
-
93
-
94
- def get_expert_mask(token_type_ids: "torch.LongTensor(B, L)") -> "[torch.BoolTensor(B, L), torch.BoolTensor(B, L)]":
95
- vision_token_mask = torch.zeros_like(token_type_ids, dtype=torch.bool)
96
- vision_token_mask[:, :-1] = (token_type_ids[:, :-1] == VISION_TOKEN_TYPE) & (token_type_ids[:, 1:] == VISION_TOKEN_TYPE)
97
- language_token_mask = ~vision_token_mask
98
- return vision_token_mask, language_token_mask
99
-
100
-
101
- class VisionExpertMLP(nn.Module):
102
- def __init__(self, config):
103
- super().__init__()
104
- self.language_mlp = MLP(config)
105
- self.vision_mlp = MLP(config)
106
-
107
- def forward(self, hidden_states: "torch.Tensor(B, L, D)", token_type_ids: "torch.LongTensor(B, L)"):
108
- output = torch.empty(hidden_states.shape, dtype=hidden_states.dtype, device=hidden_states.device)
109
- vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
110
- output[vision_token_mask] = self.vision_mlp(hidden_states[vision_token_mask])
111
- output[language_token_mask] = self.language_mlp(hidden_states[language_token_mask])
112
- return output
113
-
114
-
115
- def attention_fn(
116
- query_layer: "torch.tensor(B, H, L, HD)",
117
- key_layer: "torch.tensor(B, H, L, HD)",
118
- value_layer: "torch.tensor(B, H, L, HD)",
119
- attention_mask: "torch.tensor(B, H, L, HD)",
120
- *,
121
- scaling_attention_score: bool = True,
122
- attention_dropout: nn.Module = None
123
- ):
124
- attention_mask_bool = (attention_mask == 0)
125
- is_low_triangle = (attention_mask_bool == torch.ones_like(attention_mask_bool, dtype=torch.float).tril()).all()
126
- is_full = (attention_mask_bool > 0).all()
127
- if not (int(torch.__version__.split('.')[0]) >= 2):
128
- warnings.warn("It's recommended to use torch2.0 or higher.")
129
- if int(torch.__version__.split('.')[0]) >= 2 and scaling_attention_score and (is_full or is_low_triangle):
130
- dropout_p = 0. if attention_dropout is None or not attention_dropout.training else attention_dropout.p
131
- return torch.nn.functional.scaled_dot_product_attention(
132
- query_layer, key_layer, value_layer,
133
- attn_mask=None,
134
- dropout_p=dropout_p,
135
- is_causal=not is_full
136
- )
137
- else:
138
- if scaling_attention_score:
139
- query_layer = query_layer / math.sqrt(query_layer.shape[-1])
140
- attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
141
- attention_scores = attention_scores + attention_mask
142
- attention_scores = nn.functional.softmax(attention_scores, dim=-1, dtype=torch.float32).to(query_layer.dtype)
143
- if attention_dropout is not None:
144
- attention_scores = attention_dropout(attention_scores)
145
- context_layer = torch.matmul(attention_scores, value_layer)
146
- return context_layer
147
-
148
- class RotaryEmbedding(torch.nn.Module):
149
- def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
150
- super().__init__()
151
-
152
- self.dim = dim
153
- self.max_position_embeddings = max_position_embeddings
154
- self.base = base
155
- inv_freq = self._compute_inv_freq(device)
156
- self.register_buffer("inv_freq", inv_freq)
157
- self.max_seq_len_cached = 0
158
-
159
- def _compute_inv_freq(self, device=None):
160
- return 1.0 / (
161
- self.base
162
- ** (torch.arange(0, self.dim, 2, device=device) / self.dim)
163
- )
164
-
165
- def _set_cos_sin_cache(self, seq_len, device, dtype):
166
- self.max_seq_len_cached = seq_len
167
- t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
168
-
169
- freqs = torch.einsum("i,j->ij", t, self.inv_freq)
170
- # Different from paper, but it uses a different permutation in order to obtain the same calculation
171
- emb = torch.cat((freqs, freqs), dim=-1)
172
- self.register_buffer("cos_cached", emb.cos()[:, None, :].to(dtype), persistent=False)
173
- self.register_buffer("sin_cached", emb.sin()[:, None, :].to(dtype), persistent=False)
174
-
175
- def forward(self, x, seq_len):
176
- # x: [bs, num_attention_heads, seq_len, head_size]
177
- if seq_len > self.max_seq_len_cached:
178
- self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
179
-
180
- return (
181
- self.cos_cached[:seq_len, ...].to(dtype=x.dtype),
182
- self.sin_cached[:seq_len, ...].to(dtype=x.dtype),
183
- )
184
-
185
-
186
- def rotate_half(x):
187
- x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
188
- return torch.cat((-x2, x1), dim=x1.ndim - 1)
189
-
190
-
191
- def apply_rotary_pos_emb_index_bhs(q, k, cos, sin, position_id):
192
- # batch_size, num_head, seq_len, hidden_size
193
- cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(1), \
194
- F.embedding(position_id, sin.squeeze(1)).unsqueeze(1)
195
- q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
196
- return q, k
197
-
198
- class VisionExpertAttention(nn.Module):
199
- def __init__(self, config):
200
- super().__init__()
201
- self.config = config
202
- self.hidden_size = config.hidden_size
203
- self.num_heads = config.num_attention_heads
204
- self.head_dim = self.hidden_size // self.num_heads
205
- self.max_position_embeddings = config.max_position_embeddings
206
-
207
- self.rotary_emb = RotaryEmbedding(self.head_dim)
208
- self.vision_expert_query_key_value = nn.Linear(self.hidden_size, self.hidden_size * 3, bias=False)
209
- self.vision_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
210
- self.language_expert_query_key_value = nn.Linear(self.hidden_size, self.hidden_size * 3, bias=False)
211
- self.language_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
212
-
213
- def _transpose_for_scores(self, tensor):
214
- """Transpose a 3D tensor [B, L, H*HD] into a 4D tensor with size [B H L HD]."""
215
- new_tensor_shape = tensor.size()[:-1] + (self.num_heads, self.head_dim)
216
- tensor = tensor.view(*new_tensor_shape)
217
- return tensor.permute(0, 2, 1, 3)
218
-
219
- def forward(
220
- self,
221
- hidden_states: torch.Tensor,
222
- token_type_ids: torch.LongTensor,
223
- position_ids: torch.LongTensor,
224
- attention_mask: Optional[torch.Tensor] = None,
225
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
226
- output_attentions: bool = False,
227
- use_cache: bool = False,
228
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
229
- bsz, q_len, _ = hidden_states.size()
230
- vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
231
-
232
- shape = list(hidden_states.shape)
233
- shape[-1] = shape[-1] * 3
234
- mixed_raw_layer = torch.empty(shape, dtype=hidden_states.dtype, device=hidden_states.device)
235
- mixed_raw_layer[vision_token_mask] = self.vision_expert_query_key_value(hidden_states[vision_token_mask])
236
- mixed_raw_layer[language_token_mask] = self.language_expert_query_key_value(hidden_states[language_token_mask])
237
-
238
- query_states, key_states, value_states = torch.split(mixed_raw_layer, self.hidden_size, dim=-1)
239
- query_states = self._transpose_for_scores(query_states) # B, H, L, HD
240
- key_states = self._transpose_for_scores(key_states) # B, H, L, HD
241
- value_states = self._transpose_for_scores(value_states) # B, H, L, HD
242
-
243
- kv_seq_len = key_states.shape[-2]
244
- if past_key_value is not None:
245
- kv_seq_len += past_key_value[0].shape[-2]
246
-
247
- cos, sin = self.rotary_emb(value_states, seq_len=position_ids.max() + 1)
248
- query_states, key_states = apply_rotary_pos_emb_index_bhs(query_states, key_states, cos, sin, position_ids)
249
-
250
- if past_key_value is not None:
251
- key_states = torch.cat([past_key_value[0], key_states], dim=2)
252
- value_states = torch.cat([past_key_value[1], value_states], dim=2)
253
-
254
- past_key_value = (key_states, value_states) if use_cache else None
255
-
256
- context_layer = attention_fn(
257
- query_layer=query_states, key_layer=key_states, value_layer=value_states, attention_mask=attention_mask,
258
- scaling_attention_score=True, attention_dropout=None)
259
- if context_layer.size() != (bsz, self.num_heads, q_len, self.head_dim):
260
- raise ValueError(
261
- f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
262
- f" {context_layer.size()}"
263
- )
264
- context_layer = context_layer.transpose(1, 2).contiguous().reshape(bsz, q_len, self.hidden_size)
265
-
266
- attn_output = torch.empty(context_layer.shape, dtype=hidden_states.dtype, device=hidden_states.device)
267
- attn_output[vision_token_mask] = self.vision_expert_dense(context_layer[vision_token_mask])
268
- attn_output[language_token_mask] = self.language_expert_dense(context_layer[language_token_mask])
269
-
270
- if output_attentions:
271
- warnings.warn("output_attentions is not implemented.")
272
-
273
- return attn_output, None, past_key_value
274
-
275
- class CrossAttention(nn.Module):
276
- def __init__(self, config):
277
- super().__init__()
278
- self.config = config
279
- self.hidden_size = config.hidden_size
280
- self.cross_hidden_size = config.cross_hidden_size
281
- self.cross_compute_hidden_size = config.cross_compute_hidden_size
282
- self.num_heads = config.num_attention_heads
283
- self.head_dim = self.hidden_size // self.num_heads
284
- self.cross_head_dim = self.cross_compute_hidden_size // self.num_heads
285
- self.max_position_embeddings = config.max_position_embeddings
286
-
287
- self.query = nn.Linear(self.hidden_size, self.cross_compute_hidden_size, bias=False)
288
- self.key_value = nn.Linear(self.cross_hidden_size, self.cross_compute_hidden_size * 2, bias=False)
289
- self.dense = nn.Linear(self.cross_compute_hidden_size, self.hidden_size, bias=False)
290
-
291
- def _transpose_for_scores(self, tensor):
292
- """Transpose a 3D tensor [B, L, H*HD] into a 4D tensor with size [B H L HD]."""
293
- new_tensor_shape = tensor.size()[:-1] + (self.num_heads, self.cross_head_dim)
294
- tensor = tensor.view(*new_tensor_shape)
295
- return tensor.permute(0, 2, 1, 3)
296
-
297
- def forward(
298
- self,
299
- hidden_states: torch.Tensor,
300
- encoder_outputs: torch.LongTensor,
301
- attention_mask: Optional[torch.Tensor] = None,
302
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
303
- output_attentions: bool = False,
304
- use_cache: bool = False,
305
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
306
- bsz, q_len, _ = hidden_states.size()
307
-
308
- shape = list(hidden_states.shape)
309
- shape[-1] = shape[-1] * 3
310
-
311
- mixed_query_layer = self.query(hidden_states)
312
- if past_key_value is None:
313
- mixed_x_layer = self.key_value(encoder_outputs)
314
- mixed_key_layer, mixed_value_layer = torch.split(mixed_x_layer, self.cross_compute_hidden_size, dim=-1)
315
- key_states = self._transpose_for_scores(mixed_key_layer) # B, H, L, HD
316
- value_states = self._transpose_for_scores(mixed_value_layer) # B, H, L, HD
317
- else:
318
- key_states, value_states = past_key_value
319
-
320
- query_states = self._transpose_for_scores(mixed_query_layer) # B, H, L, HD
321
-
322
- past_key_value = (key_states, value_states) if use_cache else None
323
-
324
- context_layer = attention_fn(
325
- query_layer=query_states, key_layer=key_states, value_layer=value_states, attention_mask=attention_mask,
326
- scaling_attention_score=True, attention_dropout=None)
327
- if context_layer.size() != (bsz, self.num_heads, q_len, self.cross_head_dim):
328
- raise ValueError(
329
- f"`cross_attn_output` should be of size {(bsz, self.num_heads, q_len, self.cross_head_dim)}, but is"
330
- f" {context_layer.size()}"
331
- )
332
- context_layer = context_layer.transpose(1, 2).contiguous().reshape(bsz, q_len, self.cross_hidden_size)
333
-
334
- attn_output = self.dense(context_layer)
335
-
336
- if output_attentions:
337
- warnings.warn("output_attentions is not implemented.")
338
-
339
- return attn_output, None, past_key_value
340
-
341
- class CogAgentDecoderLayer(nn.Module):
342
- def __init__(self, config):
343
- super().__init__()
344
- self.hidden_size = config.hidden_size
345
- self.self_attn = VisionExpertAttention(config=config)
346
- self.cross_attn = CrossAttention(config=config)
347
- self.mlp = VisionExpertMLP(config)
348
- self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
349
- self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
350
- self.post_cross_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
351
-
352
- def forward(
353
- self,
354
- hidden_states: torch.Tensor,
355
- encoder_outputs: torch.Tensor,
356
- token_type_ids: torch.LongTensor,
357
- position_ids: torch.LongTensor,
358
- attention_mask: Optional[torch.Tensor] = None,
359
- cross_attention_mask: Optional[torch.Tensor] = None,
360
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
361
- output_attentions: Optional[bool] = False,
362
- use_cache: Optional[bool] = False,
363
- ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
364
- residual = hidden_states
365
-
366
- hidden_states = self.input_layernorm(hidden_states)
367
-
368
- # Self Attention
369
- hidden_states, self_attn_weights, present_key_value = self.self_attn(
370
- hidden_states=hidden_states,
371
- token_type_ids=token_type_ids,
372
- position_ids=position_ids,
373
- attention_mask=attention_mask,
374
- past_key_value=past_key_value[:2] if past_key_value is not None else None,
375
- output_attentions=output_attentions,
376
- use_cache=use_cache,
377
- )
378
- hidden_states = residual + hidden_states
379
-
380
- cross_input = self.post_cross_attention_layernorm(hidden_states)
381
- # Fully Connected
382
- attention_output, self_cross_attn_weights, present_cross_key_value = self.cross_attn(
383
- hidden_states=cross_input,
384
- encoder_outputs=encoder_outputs,
385
- attention_mask=cross_attention_mask,
386
- past_key_value=past_key_value[-2:] if past_key_value is not None else None,
387
- output_attentions=output_attentions,
388
- use_cache=use_cache,
389
- )
390
- hidden_states = hidden_states + attention_output
391
- mlp_input = self.post_attention_layernorm(hidden_states)
392
- mlp_output = self.mlp(mlp_input, token_type_ids=token_type_ids)
393
- hidden_states = mlp_output + hidden_states
394
-
395
- outputs = (hidden_states,)
396
-
397
- if output_attentions:
398
- outputs += (self_attn_weights,)
399
-
400
- if use_cache:
401
- outputs += (present_key_value+present_cross_key_value,)
402
-
403
- return outputs # type: ignore
404
-
405
-
406
- class CogAgentPreTrainedModel(PreTrainedModel):
407
- config_class = CogAgentConfig
408
- base_model_prefix = "model"
409
- supports_gradient_checkpointing = False
410
- _no_split_modules = ["CogAgentDecoderLayer"]
411
- _skip_keys_device_placement = "past_key_values"
412
-
413
- def _init_weights(self, module):
414
- std = self.config.initializer_range
415
- if isinstance(module, nn.Linear):
416
- module.weight.data.normal_(mean=0.0, std=std)
417
- if module.bias is not None:
418
- module.bias.data.zero_()
419
- elif isinstance(module, nn.Embedding):
420
- module.weight.data.normal_(mean=0.0, std=std)
421
- if module.padding_idx is not None:
422
- module.weight.data[module.padding_idx].zero_()
423
-
424
-
425
- def is_empty(images_list: Optional[List[List[torch.Tensor]]]):
426
- if images_list is None or len(images_list) == 0:
427
- return True
428
- for image_list in images_list:
429
- if len(image_list):
430
- return False
431
- return True
432
-
433
-
434
- def build_position_ids(x: "torch.BoolTensor(B, L)", attention_mask: Optional["torch.BoolTensor(B, L)"] = None) -> "torch.LongTensor(B, L)":
435
- if attention_mask is not None:
436
- tmp = x.clone()
437
- tmp[~(attention_mask.bool())] = -1
438
- else:
439
- tmp = x.clone()
440
- # image boi eoi token as LANGUAGE_TOKEN_TYPE
441
- is_boi_eoi = torch.zeros_like(x, dtype=torch.bool)
442
- is_boi_eoi[:, 1:] |= (tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE)
443
- is_boi_eoi[:, 0] |= (tmp[:, 0] == VISION_TOKEN_TYPE)
444
- is_boi_eoi[:, :-1] |= (tmp[:, :-1] == VISION_TOKEN_TYPE) & (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE)
445
- is_boi_eoi[:, -1] |= (tmp[:, -1] == VISION_TOKEN_TYPE)
446
- tmp[is_boi_eoi] = LANGUAGE_TOKEN_TYPE
447
- # final position ids
448
- y = torch.zeros_like(x, dtype=torch.long)
449
- y[:, 1:] = (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE) | ((tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE))
450
- y = y.cumsum(dim=-1)
451
- return y
452
-
453
-
454
- class CogAgentModel(CogAgentPreTrainedModel):
455
- def __init__(self, config):
456
- super().__init__(config)
457
- self.padding_idx = config.pad_token_id
458
- self.vocab_size = config.vocab_size
459
-
460
- self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
461
- self.layers = nn.ModuleList([CogAgentDecoderLayer(config) for _ in range(config.num_hidden_layers)])
462
- self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
463
-
464
- self.vision = EVA2CLIPModel(config)
465
- self.cross_vision = CrossVisionModel(config)
466
-
467
- self.gradient_checkpointing = False
468
- # Initialize weights and apply final processing
469
- self.post_init()
470
-
471
- def encode_images(self, images: List[List[torch.Tensor]]) -> torch.Tensor:
472
- images_list, images = images, []
473
-
474
- images = []
475
- for image_list in images_list:
476
- for image in image_list:
477
- images.append(image)
478
-
479
- images = torch.stack(images)
480
- images_features = self.vision(images)
481
- return images_features
482
-
483
- def encode_cross_images(self, images: List[List[torch.Tensor]]) -> torch.Tensor:
484
- images_list, images = images, []
485
-
486
- images = []
487
- for image_list in images_list:
488
- for image in image_list:
489
- images.append(image)
490
-
491
- images = torch.stack(images)
492
- encoder_outputs = self.cross_vision(images)
493
- return encoder_outputs
494
-
495
- def forward(
496
- self,
497
- input_ids: torch.LongTensor = None,
498
- images: List[List[torch.Tensor]] = None,
499
- cross_images: List[List[torch.Tensor]] = None,
500
- token_type_ids: Optional[torch.LongTensor] = None,
501
- attention_mask: Optional[torch.Tensor] = None,
502
- cross_attention_mask: Optional[torch.Tensor] = None,
503
- position_ids: Optional[torch.LongTensor] = None,
504
- past_key_values: Optional[List[torch.FloatTensor]] = None,
505
- inputs_embeds: Optional[torch.FloatTensor] = None,
506
- use_cache: Optional[bool] = None,
507
- output_attentions: Optional[bool] = None,
508
- output_hidden_states: Optional[bool] = None,
509
- return_dict: Optional[bool] = None,
510
- ) -> Union[Tuple, BaseModelOutputWithPast]:
511
- """take care of image_encode, token_type_ids, position_ids and (attention_mask = None is fine)"""
512
-
513
- if past_key_values is not None:
514
- encoder_outputs = None
515
- # generate mode with past_key_values. the image features are already mapped
516
- else:
517
- # not allow for inputs_embeds, because we want to process image feature
518
- assert input_ids is not None and inputs_embeds is None, f"{input_ids} {inputs_embeds}"
519
- if not is_empty(images): # multi-modality
520
- assert token_type_ids is not None, f"multi-modality requires `token_type_ids`!"
521
- assert len(input_ids) == len(images), f"{len(input_ids)} {len(images)}"
522
- inputs_embeds = self.embed_tokens(input_ids)
523
- images_features = self.encode_images(images)
524
- encoder_outputs = self.encode_cross_images(cross_images)
525
- images_features = rearrange(images_features, 'b n d -> (b n) d')
526
- images_features = images_features.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device)
527
- inputs_embeds = inputs_embeds.index_put([token_type_ids == VISION_TOKEN_TYPE], images_features)
528
- else: # single-modality
529
- if token_type_ids is None:
530
- token_type_ids = torch.ones_like(input_ids, dtype=torch.long, device=input_ids.device) * LANGUAGE_TOKEN_TYPE
531
- assert not (token_type_ids == VISION_TOKEN_TYPE).any(), f"{(token_type_ids == VISION_TOKEN_TYPE).sum()}"
532
- inputs_embeds = self.embed_tokens(input_ids)
533
- encoder_outputs = None
534
-
535
- if position_ids is None:
536
- position_ids = build_position_ids(token_type_ids, attention_mask)
537
- input_ids = None
538
-
539
- return self.llm_forward(
540
- input_ids=input_ids,
541
- encoder_outputs=encoder_outputs,
542
- token_type_ids=token_type_ids,
543
- attention_mask=attention_mask,
544
- cross_attention_mask=cross_attention_mask,
545
- position_ids=position_ids,
546
- past_key_values=past_key_values,
547
- inputs_embeds=inputs_embeds,
548
- use_cache=use_cache,
549
- output_attentions=output_attentions,
550
- output_hidden_states=output_hidden_states,
551
- return_dict=return_dict,
552
- )
553
-
554
- def llm_forward(
555
- self,
556
- input_ids: torch.LongTensor = None,
557
- encoder_outputs: torch.LongTensor = None,
558
- token_type_ids: torch.LongTensor = None,
559
- attention_mask: Optional[torch.Tensor] = None,
560
- cross_attention_mask: Optional[torch.Tensor] = None,
561
- position_ids: Optional[torch.LongTensor] = None,
562
- past_key_values: Optional[List[torch.FloatTensor]] = None,
563
- inputs_embeds: Optional[torch.FloatTensor] = None,
564
- use_cache: Optional[bool] = None,
565
- output_attentions: Optional[bool] = None,
566
- output_hidden_states: Optional[bool] = None,
567
- return_dict: Optional[bool] = None,
568
- ) -> Union[Tuple, BaseModelOutputWithPast]:
569
- """largely copy from llama forward and adapt for CogAgent with `token_type_ids`"""
570
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
571
- output_hidden_states = (
572
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
573
- )
574
- use_cache = use_cache if use_cache is not None else self.config.use_cache
575
-
576
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
577
-
578
- # retrieve input_ids and inputs_embeds
579
- if input_ids is not None and inputs_embeds is not None:
580
- raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
581
- elif input_ids is not None:
582
- batch_size, seq_length = input_ids.shape
583
- elif inputs_embeds is not None:
584
- batch_size, seq_length, _ = inputs_embeds.shape
585
- else:
586
- raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
587
-
588
- seq_length_with_past = seq_length
589
- past_key_values_length = 0
590
-
591
- if past_key_values is not None:
592
- past_key_values_length = past_key_values[0][0].shape[2]
593
- seq_length_with_past = seq_length_with_past + past_key_values_length
594
-
595
- if position_ids is None:
596
- device = input_ids.device if input_ids is not None else inputs_embeds.device
597
- position_ids = torch.arange(
598
- past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
599
- )
600
- position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
601
- else:
602
- position_ids = position_ids.view(-1, seq_length).long()
603
-
604
- if inputs_embeds is None:
605
- inputs_embeds = self.embed_tokens(input_ids)
606
- # embed positions
607
- if attention_mask is None:
608
- attention_mask = torch.ones(
609
- (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
610
- )
611
- if cross_attention_mask is None:
612
- cross_attention_mask = torch.ones(
613
- (batch_size, 1), dtype=torch.bool, device=inputs_embeds.device
614
- )
615
- attention_mask = self._prepare_decoder_attention_mask(
616
- attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
617
- )
618
-
619
- hidden_states = inputs_embeds
620
-
621
- # decoder layers
622
- all_hidden_states = () if output_hidden_states else None
623
- all_self_attns = () if output_attentions else None
624
- next_decoder_cache = () if use_cache else None
625
-
626
- for idx, decoder_layer in enumerate(self.layers):
627
- if output_hidden_states:
628
- all_hidden_states += (hidden_states,)
629
-
630
- past_key_value = past_key_values[idx] if past_key_values is not None else None
631
- layer_outputs = decoder_layer(
632
- hidden_states,
633
- encoder_outputs=encoder_outputs,
634
- token_type_ids=token_type_ids,
635
- attention_mask=attention_mask,
636
- cross_attention_mask=cross_attention_mask,
637
- position_ids=position_ids,
638
- past_key_value=past_key_value,
639
- output_attentions=output_attentions,
640
- use_cache=use_cache,
641
- )
642
- hidden_states = layer_outputs[0]
643
-
644
- if use_cache:
645
- next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
646
-
647
- if output_attentions:
648
- all_self_attns += (layer_outputs[1],)
649
-
650
- hidden_states = self.norm(hidden_states)
651
-
652
- # add hidden states from the last decoder layer
653
- if output_hidden_states:
654
- all_hidden_states += (hidden_states,)
655
-
656
- next_cache = next_decoder_cache if use_cache else None
657
- if not return_dict:
658
- return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
659
- return BaseModelOutputWithPast(
660
- last_hidden_state=hidden_states,
661
- past_key_values=next_cache,
662
- hidden_states=all_hidden_states,
663
- attentions=all_self_attns,
664
- )
665
-
666
- def get_input_embeddings(self):
667
- return self.embed_tokens
668
-
669
- def set_input_embeddings(self, value):
670
- self.embed_tokens = value
671
-
672
- # noinspection PyMethodMayBeStatic
673
- # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
674
- def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
675
- # create causal mask
676
- # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
677
- combined_attention_mask = None
678
- if input_shape[-1] > 1:
679
- combined_attention_mask = _make_causal_mask(
680
- input_shape,
681
- inputs_embeds.dtype,
682
- device=inputs_embeds.device,
683
- past_key_values_length=past_key_values_length,
684
- )
685
-
686
- if attention_mask is not None:
687
- # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
688
- expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
689
- inputs_embeds.device
690
- )
691
- combined_attention_mask = (
692
- expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
693
- )
694
-
695
- return combined_attention_mask
696
-
697
-
698
- def chat_history_to_prompt(history, query):
699
- prompt = " [INST] "
700
- for i, (old_query, response) in enumerate(history):
701
- prompt += old_query + " [/INST] " + response + " [INST] "
702
- prompt += query + " [/INST] "
703
- return prompt
704
-
705
-
706
- def base_history_to_prompt(history, query):
707
- prompt = query
708
- return prompt
709
-
710
-
711
- _history_to_prompt = {
712
- "base": base_history_to_prompt,
713
- "chat": chat_history_to_prompt
714
- }
715
-
716
-
717
- class CogAgentForCausalLM(CogAgentPreTrainedModel):
718
- _auto_class = "AutoModelForCausalLM"
719
-
720
- def __init__(self, config):
721
- super().__init__(config)
722
- self.model = CogAgentModel(config)
723
- self.vocab_size = config.vocab_size
724
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
725
-
726
- # Initialize weights and apply final processing
727
- self.post_init()
728
-
729
- def get_input_embeddings(self):
730
- return self.model.embed_tokens
731
-
732
- def set_input_embeddings(self, value):
733
- self.model.embed_tokens = value
734
-
735
- def get_output_embeddings(self):
736
- return self.lm_head
737
-
738
- def set_output_embeddings(self, new_embeddings):
739
- self.lm_head = new_embeddings
740
-
741
- def set_decoder(self, decoder):
742
- self.model = decoder
743
-
744
- def get_decoder(self):
745
- return self.model
746
-
747
- def forward(
748
- self,
749
- input_ids: torch.LongTensor = None,
750
- images: List[List[torch.Tensor]] = None,
751
- cross_images: List[List[torch.Tensor]] = None,
752
- token_type_ids: Optional[torch.LongTensor] = None,
753
- attention_mask: Optional[torch.Tensor] = None,
754
- position_ids: Optional[torch.LongTensor] = None,
755
- past_key_values: Optional[List[torch.FloatTensor]] = None,
756
- inputs_embeds: Optional[torch.FloatTensor] = None,
757
- use_cache: Optional[bool] = None,
758
- output_attentions: Optional[bool] = None,
759
- output_hidden_states: Optional[bool] = None,
760
- return_dict: Optional[bool] = None,
761
- labels: Optional[torch.LongTensor] = None,
762
- ) -> Union[Tuple, CausalLMOutputWithPast]:
763
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
764
- output_hidden_states = (
765
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
766
- )
767
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
768
-
769
- # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
770
- outputs = self.model(
771
- input_ids=input_ids,
772
- images=images,
773
- cross_images=cross_images,
774
- token_type_ids=token_type_ids,
775
- attention_mask=attention_mask,
776
- position_ids=position_ids,
777
- past_key_values=past_key_values,
778
- inputs_embeds=inputs_embeds,
779
- use_cache=use_cache,
780
- output_attentions=output_attentions,
781
- output_hidden_states=output_hidden_states,
782
- return_dict=return_dict,
783
- )
784
-
785
- hidden_states = outputs[0]
786
- logits = self.lm_head(hidden_states)
787
- logits = logits.float()
788
-
789
- loss = None
790
- if labels is not None:
791
- # Shift so that tokens < n predict n
792
- shift_logits = logits[..., :-1, :].contiguous()
793
- shift_labels = labels[..., 1:].contiguous()
794
- # Flatten the tokens
795
- loss_fct = CrossEntropyLoss()
796
- shift_logits = shift_logits.view(-1, self.config.vocab_size)
797
- shift_labels = shift_labels.view(-1)
798
- # Enable model parallelism
799
- shift_labels = shift_labels.to(shift_logits.device)
800
- loss = loss_fct(shift_logits, shift_labels)
801
-
802
- if not return_dict:
803
- output = (logits,) + outputs[1:]
804
- return (loss,) + output if loss is not None else output
805
-
806
- return CausalLMOutputWithPast(
807
- loss=loss,
808
- logits=logits,
809
- past_key_values=outputs.past_key_values,
810
- hidden_states=outputs.hidden_states,
811
- attentions=outputs.attentions,
812
- )
813
-
814
- def _prepare_attention_mask_for_generation(
815
- self,
816
- inputs: torch.Tensor,
817
- pad_token_id: Optional[int],
818
- eos_token_id: Optional[Union[int, List[int]]],
819
- ) -> torch.LongTensor:
820
- return torch.ones(inputs.shape[:2], dtype=torch.long, device=inputs.device) # type: ignore
821
-
822
- def prepare_inputs_for_generation(
823
- self, input_ids, token_type_ids, images=None, cross_images=None, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
824
- ):
825
- # build position_ids if needed
826
- position_ids = kwargs.get("position_ids", None)
827
- if position_ids is None:
828
- position_ids = build_position_ids(token_type_ids, attention_mask)
829
-
830
- if past_key_values:
831
- input_ids = input_ids[:, -1:]
832
- token_type_ids = token_type_ids[:, -1:]
833
- position_ids = position_ids[:, -1:]
834
-
835
- # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
836
- if inputs_embeds is not None and past_key_values is None:
837
- model_inputs = {"inputs_embeds": inputs_embeds}
838
- else:
839
- model_inputs = {"input_ids": input_ids}
840
-
841
- model_inputs.update(
842
- {
843
- "token_type_ids": token_type_ids,
844
- "images": images,
845
- "cross_images": cross_images,
846
- "position_ids": position_ids,
847
- "past_key_values": past_key_values,
848
- "use_cache": kwargs.get("use_cache"),
849
- "attention_mask": attention_mask,
850
- }
851
- )
852
- return model_inputs
853
-
854
- def _update_model_kwargs_for_generation(
855
- self,
856
- outputs: "ModelOutput",
857
- model_kwargs: Dict[str, Any],
858
- is_encoder_decoder: bool = False,
859
- standardize_cache_format: bool = False,
860
- ) -> Dict[str, Any]:
861
- # update past_key_values
862
- model_kwargs["past_key_values"] = self._extract_past_from_model_output(
863
- outputs, standardize_cache_format=standardize_cache_format
864
- )
865
- if getattr(outputs, "state", None) is not None:
866
- model_kwargs["state"] = outputs.state
867
-
868
- # update token_type_ids with last value
869
- if "token_type_ids" in model_kwargs:
870
- token_type_ids = model_kwargs["token_type_ids"]
871
- new_token_type_ids = torch.ones(size=(token_type_ids.shape[0], 1), dtype=token_type_ids.dtype, device=token_type_ids.device) * LANGUAGE_TOKEN_TYPE
872
- model_kwargs["token_type_ids"] = torch.cat([token_type_ids, new_token_type_ids], dim=-1)
873
-
874
- if not is_encoder_decoder:
875
- # update attention mask
876
- if "attention_mask" in model_kwargs:
877
- attention_mask = model_kwargs["attention_mask"]
878
- model_kwargs["attention_mask"] = torch.cat(
879
- [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
880
- )
881
- else:
882
- # update decoder attention mask
883
- if "decoder_attention_mask" in model_kwargs:
884
- decoder_attention_mask = model_kwargs["decoder_attention_mask"]
885
- model_kwargs["decoder_attention_mask"] = torch.cat(
886
- [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
887
- dim=-1,
888
- )
889
-
890
- return model_kwargs
891
-
892
- def _reorder_cache(self, past_key_values, beam_idx):
893
- reordered_past = ()
894
- for layer_past in past_key_values:
895
- reordered_past += (
896
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
897
- )
898
- return reordered_past
899
-
900
- def build_conversation_input_ids(
901
- self,
902
- tokenizer: "PreTrainedTokenizer",
903
- *,
904
- query: str,
905
- history: Optional[List[Tuple[str, str]]] = None,
906
- images: Optional[List["PIL.Image"]] = None,
907
- template_version: Optional[Literal["base", "chat", "vqa"]] = None,
908
- ):
909
- image_size: int = self.config.vision_config['image_size']
910
- cross_image_size: int = self.config.cross_image_size
911
- patch_size: int = self.config.vision_config['patch_size']
912
- template_version = template_version or self.config.template_version
913
- assert images is None or len(images) <= 1, f"not support multi images by now."
914
- history = history or []
915
- text = _history_to_prompt[template_version](history, query)
916
-
917
- input_ids = [tokenizer.bos_token_id]
918
- token_type_ids = [LANGUAGE_TOKEN_TYPE]
919
- if images is not None and len(images) == 1:
920
- ori = images
921
- # vision
922
- transform = transforms.Compose(
923
- [
924
- transforms.Resize(
925
- (image_size, image_size), interpolation=transforms.InterpolationMode.BICUBIC
926
- ),
927
- transforms.ToTensor(),
928
- transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
929
- ]
930
- )
931
- images = [transform(ori[0])]
932
- cross_transform = transforms.Compose(
933
- [
934
- transforms.Resize(
935
- (cross_image_size, cross_image_size), interpolation=transforms.InterpolationMode.BICUBIC
936
- ),
937
- transforms.ToTensor(),
938
- transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
939
- ]
940
- )
941
- cross_images = [cross_transform(ori[0])]
942
- # language
943
- vision_token_num = (image_size // patch_size) * (image_size // patch_size) + 2
944
- input_ids += [tokenizer.pad_token_id] * vision_token_num
945
- token_type_ids += [VISION_TOKEN_TYPE] * vision_token_num
946
- text_ids = tokenizer.encode(text, add_special_tokens=False)
947
-
948
- input_ids += text_ids
949
- token_type_ids += [LANGUAGE_TOKEN_TYPE] * len(text_ids)
950
- attention_mask = [1] * len(input_ids)
951
-
952
- return {
953
- 'input_ids': torch.tensor(input_ids, dtype=torch.long),
954
- 'token_type_ids': torch.tensor(token_type_ids, dtype=torch.long),
955
- 'attention_mask': torch.tensor(attention_mask, dtype=torch.long),
956
- 'images': images,
957
- 'cross_images': cross_images
958
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """largely copy from llama and adapt for CogAgent"""
2
+ import warnings
3
+ from typing import TYPE_CHECKING, Optional, Tuple, List, Union, Literal, Dict, Any
4
+
5
+ import math
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn import CrossEntropyLoss
9
+ from torchvision import transforms
10
+ from einops import rearrange
11
+
12
+ from transformers import PreTrainedModel, PreTrainedTokenizer
13
+ from transformers.utils.logging import get_logger
14
+ from transformers.activations import ACT2FN
15
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
16
+
17
+ from .configuration_cogagent import CogAgentConfig
18
+ # from .util import FastRotaryEmbedding
19
+ from torch.nn import functional as F
20
+ from .visual import EVA2CLIPModel
21
+ from .cross_visual import CrossVisionModel
22
+
23
+ if TYPE_CHECKING:
24
+ from transformers.utils import ModelOutput
25
+
26
+ logger = get_logger(__name__)
27
+
28
+ LANGUAGE_TOKEN_TYPE = 0
29
+ VISION_TOKEN_TYPE = 1
30
+
31
+
32
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
33
+ def _make_causal_mask(
34
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
35
+ ):
36
+ """
37
+ Make causal mask used for bi-directional self-attention.
38
+ """
39
+ bsz, tgt_len = input_ids_shape
40
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
41
+ mask_cond = torch.arange(mask.size(-1), device=device)
42
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
43
+ mask = mask.to(dtype)
44
+
45
+ if past_key_values_length > 0:
46
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
47
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
48
+
49
+
50
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
51
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
52
+ """
53
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
54
+ """
55
+ bsz, src_len = mask.size()
56
+ tgt_len = tgt_len if tgt_len is not None else src_len
57
+
58
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
59
+
60
+ inverted_mask = 1.0 - expanded_mask
61
+
62
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
63
+
64
+
65
+ class RMSNorm(nn.Module):
66
+ def __init__(self, hidden_size, eps=1e-6):
67
+ super().__init__()
68
+ self.weight = nn.Parameter(torch.ones(hidden_size))
69
+ self.variance_epsilon = eps
70
+
71
+ def forward(self, hidden_states):
72
+ input_dtype = hidden_states.dtype
73
+ hidden_states = hidden_states.to(torch.float32)
74
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
75
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
76
+ return (self.weight * hidden_states).to(input_dtype)
77
+
78
+
79
+ class MLP(nn.Module):
80
+ def __init__(self, config):
81
+ super().__init__()
82
+ self.hidden_size = config.hidden_size
83
+ self.intermediate_size = config.intermediate_size
84
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
85
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
86
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
87
+ self.act_fn = ACT2FN[config.hidden_act]
88
+
89
+ def forward(self, x):
90
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
91
+ return down_proj
92
+
93
+
94
+ def get_expert_mask(token_type_ids: "torch.LongTensor(B, L)") -> "[torch.BoolTensor(B, L), torch.BoolTensor(B, L)]":
95
+ vision_token_mask = torch.zeros_like(token_type_ids, dtype=torch.bool)
96
+ vision_token_mask[:, :-1] = (token_type_ids[:, :-1] == VISION_TOKEN_TYPE) & (token_type_ids[:, 1:] == VISION_TOKEN_TYPE)
97
+ language_token_mask = ~vision_token_mask
98
+ return vision_token_mask, language_token_mask
99
+
100
+
101
+ class VisionExpertMLP(nn.Module):
102
+ def __init__(self, config):
103
+ super().__init__()
104
+ self.language_mlp = MLP(config)
105
+ self.vision_mlp = MLP(config)
106
+
107
+ def forward(self, hidden_states: "torch.Tensor(B, L, D)", token_type_ids: "torch.LongTensor(B, L)"):
108
+ output = torch.empty(hidden_states.shape, dtype=hidden_states.dtype, device=hidden_states.device)
109
+ vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
110
+ output[vision_token_mask] = self.vision_mlp(hidden_states[vision_token_mask])
111
+ output[language_token_mask] = self.language_mlp(hidden_states[language_token_mask])
112
+ return output
113
+
114
+
115
+ def attention_fn(
116
+ query_layer: "torch.tensor(B, H, L, HD)",
117
+ key_layer: "torch.tensor(B, H, L, HD)",
118
+ value_layer: "torch.tensor(B, H, L, HD)",
119
+ attention_mask: "torch.tensor(B, H, L, HD)",
120
+ *,
121
+ scaling_attention_score: bool = True,
122
+ attention_dropout: nn.Module = None
123
+ ):
124
+ attention_mask_bool = (attention_mask == 0)
125
+ is_low_triangle = (attention_mask_bool == torch.ones_like(attention_mask_bool, dtype=torch.float).tril()).all()
126
+ is_full = (attention_mask_bool > 0).all()
127
+ if not (int(torch.__version__.split('.')[0]) >= 2):
128
+ warnings.warn("It's recommended to use torch2.0 or higher.")
129
+ if int(torch.__version__.split('.')[0]) >= 2 and scaling_attention_score and (is_full or is_low_triangle):
130
+ dropout_p = 0. if attention_dropout is None or not attention_dropout.training else attention_dropout.p
131
+ return torch.nn.functional.scaled_dot_product_attention(
132
+ query_layer, key_layer, value_layer,
133
+ attn_mask=None,
134
+ dropout_p=dropout_p,
135
+ is_causal=not is_full
136
+ )
137
+ else:
138
+ if scaling_attention_score:
139
+ query_layer = query_layer / math.sqrt(query_layer.shape[-1])
140
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
141
+ attention_scores = attention_scores + attention_mask
142
+ attention_scores = nn.functional.softmax(attention_scores, dim=-1, dtype=torch.float32).to(query_layer.dtype)
143
+ if attention_dropout is not None:
144
+ attention_scores = attention_dropout(attention_scores)
145
+ context_layer = torch.matmul(attention_scores, value_layer)
146
+ return context_layer
147
+
148
+ class RotaryEmbedding(torch.nn.Module):
149
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
150
+ super().__init__()
151
+
152
+ self.dim = dim
153
+ self.max_position_embeddings = max_position_embeddings
154
+ self.base = base
155
+ inv_freq = self._compute_inv_freq(device)
156
+ self.register_buffer("inv_freq", inv_freq)
157
+ self.max_seq_len_cached = 0
158
+
159
+ def _compute_inv_freq(self, device=None):
160
+ return 1.0 / (
161
+ self.base
162
+ ** (torch.arange(0, self.dim, 2, device=device) / self.dim)
163
+ )
164
+
165
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
166
+ self.max_seq_len_cached = seq_len
167
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
168
+
169
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
170
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
171
+ emb = torch.cat((freqs, freqs), dim=-1)
172
+ self.register_buffer("cos_cached", emb.cos()[:, None, :].to(dtype), persistent=False)
173
+ self.register_buffer("sin_cached", emb.sin()[:, None, :].to(dtype), persistent=False)
174
+
175
+ def forward(self, x, seq_len):
176
+ # x: [bs, num_attention_heads, seq_len, head_size]
177
+ if seq_len > self.max_seq_len_cached:
178
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
179
+
180
+ return (
181
+ self.cos_cached[:seq_len, ...].to(dtype=x.dtype),
182
+ self.sin_cached[:seq_len, ...].to(dtype=x.dtype),
183
+ )
184
+
185
+
186
+ def rotate_half(x):
187
+ x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
188
+ return torch.cat((-x2, x1), dim=x1.ndim - 1)
189
+
190
+
191
+ def apply_rotary_pos_emb_index_bhs(q, k, cos, sin, position_id):
192
+ # batch_size, num_head, seq_len, hidden_size
193
+ cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(1), \
194
+ F.embedding(position_id, sin.squeeze(1)).unsqueeze(1)
195
+ q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
196
+ return q, k
197
+
198
+ class VisionExpertAttention(nn.Module):
199
+ def __init__(self, config):
200
+ super().__init__()
201
+ self.config = config
202
+ self.hidden_size = config.hidden_size
203
+ self.num_heads = config.num_attention_heads
204
+ self.head_dim = self.hidden_size // self.num_heads
205
+ self.max_position_embeddings = config.max_position_embeddings
206
+
207
+ self.rotary_emb = RotaryEmbedding(self.head_dim)
208
+ self.vision_expert_query_key_value = nn.Linear(self.hidden_size, self.hidden_size * 3, bias=False)
209
+ self.vision_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
210
+ self.language_expert_query_key_value = nn.Linear(self.hidden_size, self.hidden_size * 3, bias=False)
211
+ self.language_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
212
+
213
+ def _transpose_for_scores(self, tensor):
214
+ """Transpose a 3D tensor [B, L, H*HD] into a 4D tensor with size [B H L HD]."""
215
+ new_tensor_shape = tensor.size()[:-1] + (self.num_heads, self.head_dim)
216
+ tensor = tensor.view(*new_tensor_shape)
217
+ return tensor.permute(0, 2, 1, 3)
218
+
219
+ def forward(
220
+ self,
221
+ hidden_states: torch.Tensor,
222
+ token_type_ids: torch.LongTensor,
223
+ position_ids: torch.LongTensor,
224
+ attention_mask: Optional[torch.Tensor] = None,
225
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
226
+ output_attentions: bool = False,
227
+ use_cache: bool = False,
228
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
229
+ bsz, q_len, _ = hidden_states.size()
230
+ vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
231
+
232
+ shape = list(hidden_states.shape)
233
+ shape[-1] = shape[-1] * 3
234
+ mixed_raw_layer = torch.empty(shape, dtype=hidden_states.dtype, device=hidden_states.device)
235
+ mixed_raw_layer[vision_token_mask] = self.vision_expert_query_key_value(hidden_states[vision_token_mask])
236
+ mixed_raw_layer[language_token_mask] = self.language_expert_query_key_value(hidden_states[language_token_mask])
237
+
238
+ query_states, key_states, value_states = torch.split(mixed_raw_layer, self.hidden_size, dim=-1)
239
+ query_states = self._transpose_for_scores(query_states) # B, H, L, HD
240
+ key_states = self._transpose_for_scores(key_states) # B, H, L, HD
241
+ value_states = self._transpose_for_scores(value_states) # B, H, L, HD
242
+
243
+ kv_seq_len = key_states.shape[-2]
244
+ if past_key_value is not None:
245
+ kv_seq_len += past_key_value[0].shape[-2]
246
+
247
+ cos, sin = self.rotary_emb(value_states, seq_len=position_ids.max() + 1)
248
+ query_states, key_states = apply_rotary_pos_emb_index_bhs(query_states, key_states, cos, sin, position_ids)
249
+
250
+ if past_key_value is not None:
251
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
252
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
253
+
254
+ past_key_value = (key_states, value_states) if use_cache else None
255
+
256
+ context_layer = attention_fn(
257
+ query_layer=query_states, key_layer=key_states, value_layer=value_states, attention_mask=attention_mask,
258
+ scaling_attention_score=True, attention_dropout=None)
259
+ if context_layer.size() != (bsz, self.num_heads, q_len, self.head_dim):
260
+ raise ValueError(
261
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
262
+ f" {context_layer.size()}"
263
+ )
264
+ context_layer = context_layer.transpose(1, 2).contiguous().reshape(bsz, q_len, self.hidden_size)
265
+
266
+ attn_output = torch.empty(context_layer.shape, dtype=hidden_states.dtype, device=hidden_states.device)
267
+ attn_output[vision_token_mask] = self.vision_expert_dense(context_layer[vision_token_mask])
268
+ attn_output[language_token_mask] = self.language_expert_dense(context_layer[language_token_mask])
269
+
270
+ if output_attentions:
271
+ warnings.warn("output_attentions is not implemented.")
272
+
273
+ return attn_output, None, past_key_value
274
+
275
+ class CrossAttention(nn.Module):
276
+ def __init__(self, config):
277
+ super().__init__()
278
+ self.config = config
279
+ self.hidden_size = config.hidden_size
280
+ self.cross_hidden_size = config.cross_hidden_size
281
+ self.cross_compute_hidden_size = config.cross_compute_hidden_size
282
+ self.num_heads = config.num_attention_heads
283
+ self.head_dim = self.hidden_size // self.num_heads
284
+ self.cross_head_dim = self.cross_compute_hidden_size // self.num_heads
285
+ self.max_position_embeddings = config.max_position_embeddings
286
+
287
+ self.query = nn.Linear(self.hidden_size, self.cross_compute_hidden_size, bias=False)
288
+ self.key_value = nn.Linear(self.cross_hidden_size, self.cross_compute_hidden_size * 2, bias=False)
289
+ self.dense = nn.Linear(self.cross_compute_hidden_size, self.hidden_size, bias=False)
290
+
291
+ def _transpose_for_scores(self, tensor):
292
+ """Transpose a 3D tensor [B, L, H*HD] into a 4D tensor with size [B H L HD]."""
293
+ new_tensor_shape = tensor.size()[:-1] + (self.num_heads, self.cross_head_dim)
294
+ tensor = tensor.view(*new_tensor_shape)
295
+ return tensor.permute(0, 2, 1, 3)
296
+
297
+ def forward(
298
+ self,
299
+ hidden_states: torch.Tensor,
300
+ encoder_outputs: torch.LongTensor,
301
+ attention_mask: Optional[torch.Tensor] = None,
302
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
303
+ output_attentions: bool = False,
304
+ use_cache: bool = False,
305
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
306
+ bsz, q_len, _ = hidden_states.size()
307
+
308
+ shape = list(hidden_states.shape)
309
+ shape[-1] = shape[-1] * 3
310
+
311
+ mixed_query_layer = self.query(hidden_states)
312
+ if past_key_value is None:
313
+ mixed_x_layer = self.key_value(encoder_outputs)
314
+ mixed_key_layer, mixed_value_layer = torch.split(mixed_x_layer, self.cross_compute_hidden_size, dim=-1)
315
+ key_states = self._transpose_for_scores(mixed_key_layer) # B, H, L, HD
316
+ value_states = self._transpose_for_scores(mixed_value_layer) # B, H, L, HD
317
+ else:
318
+ key_states, value_states = past_key_value
319
+
320
+ query_states = self._transpose_for_scores(mixed_query_layer) # B, H, L, HD
321
+
322
+ past_key_value = (key_states, value_states) if use_cache else None
323
+
324
+ context_layer = attention_fn(
325
+ query_layer=query_states, key_layer=key_states, value_layer=value_states, attention_mask=attention_mask,
326
+ scaling_attention_score=True, attention_dropout=None)
327
+ if context_layer.size() != (bsz, self.num_heads, q_len, self.cross_head_dim):
328
+ raise ValueError(
329
+ f"`cross_attn_output` should be of size {(bsz, self.num_heads, q_len, self.cross_head_dim)}, but is"
330
+ f" {context_layer.size()}"
331
+ )
332
+ context_layer = context_layer.transpose(1, 2).contiguous().reshape(bsz, q_len, self.cross_hidden_size)
333
+
334
+ attn_output = self.dense(context_layer)
335
+
336
+ if output_attentions:
337
+ warnings.warn("output_attentions is not implemented.")
338
+
339
+ return attn_output, None, past_key_value
340
+
341
+ class CogAgentDecoderLayer(nn.Module):
342
+ def __init__(self, config):
343
+ super().__init__()
344
+ self.hidden_size = config.hidden_size
345
+ self.self_attn = VisionExpertAttention(config=config)
346
+ self.cross_attn = CrossAttention(config=config)
347
+ self.mlp = VisionExpertMLP(config)
348
+ self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
349
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
350
+ self.post_cross_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
351
+
352
+ def forward(
353
+ self,
354
+ hidden_states: torch.Tensor,
355
+ encoder_outputs: torch.Tensor,
356
+ token_type_ids: torch.LongTensor,
357
+ position_ids: torch.LongTensor,
358
+ attention_mask: Optional[torch.Tensor] = None,
359
+ cross_attention_mask: Optional[torch.Tensor] = None,
360
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
361
+ output_attentions: Optional[bool] = False,
362
+ use_cache: Optional[bool] = False,
363
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
364
+ residual = hidden_states
365
+
366
+ hidden_states = self.input_layernorm(hidden_states)
367
+
368
+ # Self Attention
369
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
370
+ hidden_states=hidden_states,
371
+ token_type_ids=token_type_ids,
372
+ position_ids=position_ids,
373
+ attention_mask=attention_mask,
374
+ past_key_value=past_key_value[:2] if past_key_value is not None else None,
375
+ output_attentions=output_attentions,
376
+ use_cache=use_cache,
377
+ )
378
+ hidden_states = residual + hidden_states
379
+
380
+ cross_input = self.post_cross_attention_layernorm(hidden_states)
381
+ # Fully Connected
382
+ attention_output, self_cross_attn_weights, present_cross_key_value = self.cross_attn(
383
+ hidden_states=cross_input,
384
+ encoder_outputs=encoder_outputs,
385
+ attention_mask=cross_attention_mask,
386
+ past_key_value=past_key_value[-2:] if past_key_value is not None else None,
387
+ output_attentions=output_attentions,
388
+ use_cache=use_cache,
389
+ )
390
+ hidden_states = hidden_states + attention_output
391
+ mlp_input = self.post_attention_layernorm(hidden_states)
392
+ mlp_output = self.mlp(mlp_input, token_type_ids=token_type_ids)
393
+ hidden_states = mlp_output + hidden_states
394
+
395
+ outputs = (hidden_states,)
396
+
397
+ if output_attentions:
398
+ outputs += (self_attn_weights,)
399
+
400
+ if use_cache:
401
+ outputs += (present_key_value+present_cross_key_value,)
402
+
403
+ return outputs # type: ignore
404
+
405
+
406
+ class CogAgentPreTrainedModel(PreTrainedModel):
407
+ config_class = CogAgentConfig
408
+ base_model_prefix = "model"
409
+ supports_gradient_checkpointing = False
410
+ _no_split_modules = ["CogAgentDecoderLayer"]
411
+ _skip_keys_device_placement = "past_key_values"
412
+
413
+ def _init_weights(self, module):
414
+ std = self.config.initializer_range
415
+ if isinstance(module, nn.Linear):
416
+ module.weight.data.normal_(mean=0.0, std=std)
417
+ if module.bias is not None:
418
+ module.bias.data.zero_()
419
+ elif isinstance(module, nn.Embedding):
420
+ module.weight.data.normal_(mean=0.0, std=std)
421
+ if module.padding_idx is not None:
422
+ module.weight.data[module.padding_idx].zero_()
423
+
424
+
425
+ def is_empty(images_list: Optional[List[List[torch.Tensor]]]):
426
+ if images_list is None or len(images_list) == 0:
427
+ return True
428
+ for image_list in images_list:
429
+ if len(image_list):
430
+ return False
431
+ return True
432
+
433
+
434
+ def build_position_ids(x: "torch.BoolTensor(B, L)", attention_mask: Optional["torch.BoolTensor(B, L)"] = None) -> "torch.LongTensor(B, L)":
435
+ if attention_mask is not None:
436
+ tmp = x.clone()
437
+ tmp[~(attention_mask.bool())] = -1
438
+ else:
439
+ tmp = x.clone()
440
+ # image boi eoi token as LANGUAGE_TOKEN_TYPE
441
+ is_boi_eoi = torch.zeros_like(x, dtype=torch.bool)
442
+ is_boi_eoi[:, 1:] |= (tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE)
443
+ is_boi_eoi[:, 0] |= (tmp[:, 0] == VISION_TOKEN_TYPE)
444
+ is_boi_eoi[:, :-1] |= (tmp[:, :-1] == VISION_TOKEN_TYPE) & (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE)
445
+ is_boi_eoi[:, -1] |= (tmp[:, -1] == VISION_TOKEN_TYPE)
446
+ tmp[is_boi_eoi] = LANGUAGE_TOKEN_TYPE
447
+ # final position ids
448
+ y = torch.zeros_like(x, dtype=torch.long)
449
+ y[:, 1:] = (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE) | ((tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE))
450
+ y = y.cumsum(dim=-1)
451
+ return y
452
+
453
+
454
+ class CogAgentModel(CogAgentPreTrainedModel):
455
+ def __init__(self, config):
456
+ super().__init__(config)
457
+ self.padding_idx = config.pad_token_id
458
+ self.vocab_size = config.vocab_size
459
+
460
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
461
+ self.layers = nn.ModuleList([CogAgentDecoderLayer(config) for _ in range(config.num_hidden_layers)])
462
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
463
+
464
+ self.vision = EVA2CLIPModel(config)
465
+ self.cross_vision = CrossVisionModel(config)
466
+
467
+ self.gradient_checkpointing = False
468
+ # Initialize weights and apply final processing
469
+ self.post_init()
470
+
471
+ def encode_images(self, images: List[List[torch.Tensor]]) -> torch.Tensor:
472
+ images_list, images = images, []
473
+
474
+ images = []
475
+ for image_list in images_list:
476
+ for image in image_list:
477
+ images.append(image)
478
+
479
+ images = torch.stack(images)
480
+ images_features = self.vision(images)
481
+ return images_features
482
+
483
+ def encode_cross_images(self, images: List[List[torch.Tensor]]) -> torch.Tensor:
484
+ images_list, images = images, []
485
+
486
+ images = []
487
+ for image_list in images_list:
488
+ for image in image_list:
489
+ images.append(image)
490
+
491
+ images = torch.stack(images)
492
+ encoder_outputs = self.cross_vision(images)
493
+ return encoder_outputs
494
+
495
+ def forward(
496
+ self,
497
+ input_ids: torch.LongTensor = None,
498
+ images: List[List[torch.Tensor]] = None,
499
+ cross_images: List[List[torch.Tensor]] = None,
500
+ token_type_ids: Optional[torch.LongTensor] = None,
501
+ attention_mask: Optional[torch.Tensor] = None,
502
+ cross_attention_mask: Optional[torch.Tensor] = None,
503
+ position_ids: Optional[torch.LongTensor] = None,
504
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
505
+ inputs_embeds: Optional[torch.FloatTensor] = None,
506
+ use_cache: Optional[bool] = None,
507
+ output_attentions: Optional[bool] = None,
508
+ output_hidden_states: Optional[bool] = None,
509
+ return_dict: Optional[bool] = None,
510
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
511
+ """take care of image_encode, token_type_ids, position_ids and (attention_mask = None is fine)"""
512
+
513
+ if past_key_values is not None:
514
+ encoder_outputs = None
515
+ # generate mode with past_key_values. the image features are already mapped
516
+ else:
517
+ # not allow for inputs_embeds, because we want to process image feature
518
+ assert input_ids is not None and inputs_embeds is None, f"{input_ids} {inputs_embeds}"
519
+ if not is_empty(images): # multi-modality
520
+ assert token_type_ids is not None, f"multi-modality requires `token_type_ids`!"
521
+ assert len(input_ids) == len(images), f"{len(input_ids)} {len(images)}"
522
+ inputs_embeds = self.embed_tokens(input_ids)
523
+ images_features = self.encode_images(images)
524
+ encoder_outputs = self.encode_cross_images(cross_images)
525
+ images_features = rearrange(images_features, 'b n d -> (b n) d')
526
+ images_features = images_features.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device)
527
+ inputs_embeds = inputs_embeds.index_put([token_type_ids == VISION_TOKEN_TYPE], images_features)
528
+ else: # single-modality
529
+ if token_type_ids is None:
530
+ token_type_ids = torch.ones_like(input_ids, dtype=torch.long, device=input_ids.device) * LANGUAGE_TOKEN_TYPE
531
+ assert not (token_type_ids == VISION_TOKEN_TYPE).any(), f"{(token_type_ids == VISION_TOKEN_TYPE).sum()}"
532
+ inputs_embeds = self.embed_tokens(input_ids)
533
+ encoder_outputs = None
534
+
535
+ if position_ids is None:
536
+ position_ids = build_position_ids(token_type_ids, attention_mask)
537
+ input_ids = None
538
+
539
+ return self.llm_forward(
540
+ input_ids=input_ids,
541
+ encoder_outputs=encoder_outputs,
542
+ token_type_ids=token_type_ids,
543
+ attention_mask=attention_mask,
544
+ cross_attention_mask=cross_attention_mask,
545
+ position_ids=position_ids,
546
+ past_key_values=past_key_values,
547
+ inputs_embeds=inputs_embeds,
548
+ use_cache=use_cache,
549
+ output_attentions=output_attentions,
550
+ output_hidden_states=output_hidden_states,
551
+ return_dict=return_dict,
552
+ )
553
+
554
+ def llm_forward(
555
+ self,
556
+ input_ids: torch.LongTensor = None,
557
+ encoder_outputs: torch.LongTensor = None,
558
+ token_type_ids: torch.LongTensor = None,
559
+ attention_mask: Optional[torch.Tensor] = None,
560
+ cross_attention_mask: Optional[torch.Tensor] = None,
561
+ position_ids: Optional[torch.LongTensor] = None,
562
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
563
+ inputs_embeds: Optional[torch.FloatTensor] = None,
564
+ use_cache: Optional[bool] = None,
565
+ output_attentions: Optional[bool] = None,
566
+ output_hidden_states: Optional[bool] = None,
567
+ return_dict: Optional[bool] = None,
568
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
569
+ """largely copy from llama forward and adapt for CogAgent with `token_type_ids`"""
570
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
571
+ output_hidden_states = (
572
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
573
+ )
574
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
575
+
576
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
577
+
578
+ # retrieve input_ids and inputs_embeds
579
+ if input_ids is not None and inputs_embeds is not None:
580
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
581
+ elif input_ids is not None:
582
+ batch_size, seq_length = input_ids.shape
583
+ elif inputs_embeds is not None:
584
+ batch_size, seq_length, _ = inputs_embeds.shape
585
+ else:
586
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
587
+
588
+ seq_length_with_past = seq_length
589
+ past_key_values_length = 0
590
+
591
+ if past_key_values is not None:
592
+ past_key_values_length = past_key_values[0][0].shape[2]
593
+ seq_length_with_past = seq_length_with_past + past_key_values_length
594
+
595
+ if position_ids is None:
596
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
597
+ position_ids = torch.arange(
598
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
599
+ )
600
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
601
+ else:
602
+ position_ids = position_ids.view(-1, seq_length).long()
603
+
604
+ if inputs_embeds is None:
605
+ inputs_embeds = self.embed_tokens(input_ids)
606
+ # embed positions
607
+ if attention_mask is None:
608
+ attention_mask = torch.ones(
609
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
610
+ )
611
+ if cross_attention_mask is None:
612
+ cross_attention_mask = torch.ones(
613
+ (batch_size, 1), dtype=torch.bool, device=inputs_embeds.device
614
+ )
615
+ attention_mask = self._prepare_decoder_attention_mask(
616
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
617
+ )
618
+
619
+ hidden_states = inputs_embeds
620
+
621
+ # decoder layers
622
+ all_hidden_states = () if output_hidden_states else None
623
+ all_self_attns = () if output_attentions else None
624
+ next_decoder_cache = () if use_cache else None
625
+
626
+ for idx, decoder_layer in enumerate(self.layers):
627
+ if output_hidden_states:
628
+ all_hidden_states += (hidden_states,)
629
+
630
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
631
+ layer_outputs = decoder_layer(
632
+ hidden_states,
633
+ encoder_outputs=encoder_outputs,
634
+ token_type_ids=token_type_ids,
635
+ attention_mask=attention_mask,
636
+ cross_attention_mask=cross_attention_mask,
637
+ position_ids=position_ids,
638
+ past_key_value=past_key_value,
639
+ output_attentions=output_attentions,
640
+ use_cache=use_cache,
641
+ )
642
+ hidden_states = layer_outputs[0]
643
+
644
+ if use_cache:
645
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
646
+
647
+ if output_attentions:
648
+ all_self_attns += (layer_outputs[1],)
649
+
650
+ hidden_states = self.norm(hidden_states)
651
+
652
+ # add hidden states from the last decoder layer
653
+ if output_hidden_states:
654
+ all_hidden_states += (hidden_states,)
655
+
656
+ next_cache = next_decoder_cache if use_cache else None
657
+ if not return_dict:
658
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
659
+ return BaseModelOutputWithPast(
660
+ last_hidden_state=hidden_states,
661
+ past_key_values=next_cache,
662
+ hidden_states=all_hidden_states,
663
+ attentions=all_self_attns,
664
+ )
665
+
666
+ def get_input_embeddings(self):
667
+ return self.embed_tokens
668
+
669
+ def set_input_embeddings(self, value):
670
+ self.embed_tokens = value
671
+
672
+ # noinspection PyMethodMayBeStatic
673
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
674
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
675
+ # create causal mask
676
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
677
+ combined_attention_mask = None
678
+ if input_shape[-1] > 1:
679
+ combined_attention_mask = _make_causal_mask(
680
+ input_shape,
681
+ inputs_embeds.dtype,
682
+ device=inputs_embeds.device,
683
+ past_key_values_length=past_key_values_length,
684
+ )
685
+
686
+ if attention_mask is not None:
687
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
688
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
689
+ inputs_embeds.device
690
+ )
691
+ combined_attention_mask = (
692
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
693
+ )
694
+
695
+ return combined_attention_mask
696
+
697
+ def vqa_history_to_prompt(history, query):
698
+ # Only support single round chat in vqa mode
699
+ prompt = "<EOI>Question: "
700
+ # for i, (old_query, response) in enumerate(history):
701
+ # prompt += old_query + " Short answer: " + response + " Question: "
702
+ prompt += query + " Short answer:"
703
+ return prompt
704
+
705
+ def chat_old_history_to_prompt(history, query):
706
+ prompt = "<EOI>Question: "
707
+ for i, (old_query, response) in enumerate(history):
708
+ prompt += old_query + " Answer: " + response + "\nQuestion: "
709
+ prompt += query + " Answer:"
710
+ return prompt
711
+
712
+ def chat_history_to_prompt(history, query):
713
+ prompt = " [INST] "
714
+ for i, (old_query, response) in enumerate(history):
715
+ prompt += old_query + " [/INST] " + response + " [INST] "
716
+ prompt += query + " [/INST] "
717
+ return prompt
718
+
719
+
720
+ def base_history_to_prompt(history, query):
721
+ prompt = query
722
+ return prompt
723
+
724
+
725
+ _history_to_prompt = {
726
+ "base": base_history_to_prompt,
727
+ "chat": chat_history_to_prompt,
728
+ "chat_old": chat_old_history_to_prompt,
729
+ "vqa": vqa_history_to_prompt
730
+ }
731
+
732
+
733
+ class CogAgentForCausalLM(CogAgentPreTrainedModel):
734
+ _auto_class = "AutoModelForCausalLM"
735
+
736
+ def __init__(self, config):
737
+ super().__init__(config)
738
+ self.model = CogAgentModel(config)
739
+ self.vocab_size = config.vocab_size
740
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
741
+
742
+ # Initialize weights and apply final processing
743
+ self.post_init()
744
+
745
+ def get_input_embeddings(self):
746
+ return self.model.embed_tokens
747
+
748
+ def set_input_embeddings(self, value):
749
+ self.model.embed_tokens = value
750
+
751
+ def get_output_embeddings(self):
752
+ return self.lm_head
753
+
754
+ def set_output_embeddings(self, new_embeddings):
755
+ self.lm_head = new_embeddings
756
+
757
+ def set_decoder(self, decoder):
758
+ self.model = decoder
759
+
760
+ def get_decoder(self):
761
+ return self.model
762
+
763
+ def forward(
764
+ self,
765
+ input_ids: torch.LongTensor = None,
766
+ images: List[List[torch.Tensor]] = None,
767
+ cross_images: List[List[torch.Tensor]] = None,
768
+ token_type_ids: Optional[torch.LongTensor] = None,
769
+ attention_mask: Optional[torch.Tensor] = None,
770
+ position_ids: Optional[torch.LongTensor] = None,
771
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
772
+ inputs_embeds: Optional[torch.FloatTensor] = None,
773
+ use_cache: Optional[bool] = None,
774
+ output_attentions: Optional[bool] = None,
775
+ output_hidden_states: Optional[bool] = None,
776
+ return_dict: Optional[bool] = None,
777
+ labels: Optional[torch.LongTensor] = None,
778
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
779
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
780
+ output_hidden_states = (
781
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
782
+ )
783
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
784
+
785
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
786
+ outputs = self.model(
787
+ input_ids=input_ids,
788
+ images=images,
789
+ cross_images=cross_images,
790
+ token_type_ids=token_type_ids,
791
+ attention_mask=attention_mask,
792
+ position_ids=position_ids,
793
+ past_key_values=past_key_values,
794
+ inputs_embeds=inputs_embeds,
795
+ use_cache=use_cache,
796
+ output_attentions=output_attentions,
797
+ output_hidden_states=output_hidden_states,
798
+ return_dict=return_dict,
799
+ )
800
+
801
+ hidden_states = outputs[0]
802
+ logits = self.lm_head(hidden_states)
803
+ logits = logits.float()
804
+
805
+ loss = None
806
+ if labels is not None:
807
+ # Shift so that tokens < n predict n
808
+ shift_logits = logits[..., :-1, :].contiguous()
809
+ shift_labels = labels[..., 1:].contiguous()
810
+ # Flatten the tokens
811
+ loss_fct = CrossEntropyLoss()
812
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
813
+ shift_labels = shift_labels.view(-1)
814
+ # Enable model parallelism
815
+ shift_labels = shift_labels.to(shift_logits.device)
816
+ loss = loss_fct(shift_logits, shift_labels)
817
+
818
+ if not return_dict:
819
+ output = (logits,) + outputs[1:]
820
+ return (loss,) + output if loss is not None else output
821
+
822
+ return CausalLMOutputWithPast(
823
+ loss=loss,
824
+ logits=logits,
825
+ past_key_values=outputs.past_key_values,
826
+ hidden_states=outputs.hidden_states,
827
+ attentions=outputs.attentions,
828
+ )
829
+
830
+ def _prepare_attention_mask_for_generation(
831
+ self,
832
+ inputs: torch.Tensor,
833
+ pad_token_id: Optional[int],
834
+ eos_token_id: Optional[Union[int, List[int]]],
835
+ ) -> torch.LongTensor:
836
+ return torch.ones(inputs.shape[:2], dtype=torch.long, device=inputs.device) # type: ignore
837
+
838
+ def prepare_inputs_for_generation(
839
+ self, input_ids, token_type_ids, images=None, cross_images=None, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
840
+ ):
841
+ # build position_ids if needed
842
+ position_ids = kwargs.get("position_ids", None)
843
+ if position_ids is None:
844
+ position_ids = build_position_ids(token_type_ids, attention_mask)
845
+
846
+ if past_key_values:
847
+ input_ids = input_ids[:, -1:]
848
+ token_type_ids = token_type_ids[:, -1:]
849
+ position_ids = position_ids[:, -1:]
850
+
851
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
852
+ if inputs_embeds is not None and past_key_values is None:
853
+ model_inputs = {"inputs_embeds": inputs_embeds}
854
+ else:
855
+ model_inputs = {"input_ids": input_ids}
856
+
857
+ model_inputs.update(
858
+ {
859
+ "token_type_ids": token_type_ids,
860
+ "images": images,
861
+ "cross_images": cross_images,
862
+ "position_ids": position_ids,
863
+ "past_key_values": past_key_values,
864
+ "use_cache": kwargs.get("use_cache"),
865
+ "attention_mask": attention_mask,
866
+ }
867
+ )
868
+ return model_inputs
869
+
870
+ def _update_model_kwargs_for_generation(
871
+ self,
872
+ outputs: "ModelOutput",
873
+ model_kwargs: Dict[str, Any],
874
+ is_encoder_decoder: bool = False,
875
+ standardize_cache_format: bool = False,
876
+ ) -> Dict[str, Any]:
877
+ # update past_key_values
878
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
879
+ outputs, standardize_cache_format=standardize_cache_format
880
+ )
881
+ if getattr(outputs, "state", None) is not None:
882
+ model_kwargs["state"] = outputs.state
883
+
884
+ # update token_type_ids with last value
885
+ if "token_type_ids" in model_kwargs:
886
+ token_type_ids = model_kwargs["token_type_ids"]
887
+ new_token_type_ids = torch.ones(size=(token_type_ids.shape[0], 1), dtype=token_type_ids.dtype, device=token_type_ids.device) * LANGUAGE_TOKEN_TYPE
888
+ model_kwargs["token_type_ids"] = torch.cat([token_type_ids, new_token_type_ids], dim=-1)
889
+
890
+ if not is_encoder_decoder:
891
+ # update attention mask
892
+ if "attention_mask" in model_kwargs:
893
+ attention_mask = model_kwargs["attention_mask"]
894
+ model_kwargs["attention_mask"] = torch.cat(
895
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
896
+ )
897
+ else:
898
+ # update decoder attention mask
899
+ if "decoder_attention_mask" in model_kwargs:
900
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
901
+ model_kwargs["decoder_attention_mask"] = torch.cat(
902
+ [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
903
+ dim=-1,
904
+ )
905
+
906
+ return model_kwargs
907
+
908
+ def _reorder_cache(self, past_key_values, beam_idx):
909
+ reordered_past = ()
910
+ for layer_past in past_key_values:
911
+ reordered_past += (
912
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
913
+ )
914
+ return reordered_past
915
+
916
+ def build_conversation_input_ids(
917
+ self,
918
+ tokenizer: "PreTrainedTokenizer",
919
+ *,
920
+ query: str,
921
+ history: Optional[List[Tuple[str, str]]] = None,
922
+ images: Optional[List["PIL.Image"]] = None,
923
+ template_version: Optional[Literal["base", "chat", "vqa"]] = None,
924
+ ):
925
+ image_size: int = self.config.vision_config['image_size']
926
+ cross_image_size: int = self.config.cross_image_size
927
+ patch_size: int = self.config.vision_config['patch_size']
928
+ template_version = template_version or self.config.template_version
929
+ assert images is None or len(images) <= 1, f"not support multi images by now."
930
+ history = history or []
931
+ text = _history_to_prompt[template_version](history, query)
932
+
933
+ input_ids = [tokenizer.bos_token_id]
934
+ token_type_ids = [LANGUAGE_TOKEN_TYPE]
935
+ if images is not None and len(images) == 1:
936
+ ori = images
937
+ # vision
938
+ transform = transforms.Compose(
939
+ [
940
+ transforms.Resize(
941
+ (image_size, image_size), interpolation=transforms.InterpolationMode.BICUBIC
942
+ ),
943
+ transforms.ToTensor(),
944
+ transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
945
+ ]
946
+ )
947
+ images = [transform(ori[0])]
948
+ cross_transform = transforms.Compose(
949
+ [
950
+ transforms.Resize(
951
+ (cross_image_size, cross_image_size), interpolation=transforms.InterpolationMode.BICUBIC
952
+ ),
953
+ transforms.ToTensor(),
954
+ transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
955
+ ]
956
+ )
957
+ cross_images = [cross_transform(ori[0])]
958
+ # language
959
+ vision_token_num = (image_size // patch_size) * (image_size // patch_size) + 2
960
+ input_ids += [tokenizer.pad_token_id] * vision_token_num
961
+ token_type_ids += [VISION_TOKEN_TYPE] * vision_token_num
962
+ text_ids = tokenizer.encode(text, add_special_tokens=False)
963
+
964
+ input_ids += text_ids
965
+ token_type_ids += [LANGUAGE_TOKEN_TYPE] * len(text_ids)
966
+ attention_mask = [1] * len(input_ids)
967
+
968
+ return {
969
+ 'input_ids': torch.tensor(input_ids, dtype=torch.long),
970
+ 'token_type_ids': torch.tensor(token_type_ids, dtype=torch.long),
971
+ 'attention_mask': torch.tensor(attention_mask, dtype=torch.long),
972
+ 'images': images,
973
+ 'cross_images': cross_images
974
+ }