liyucheng commited on
Commit
14936a3
·
verified ·
1 Parent(s): 272ad65

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ library_name: transformers
5
+ license: apache-2.0
6
+ metrics:
7
+ - accuracy
8
+ tags:
9
+ - multimodal
10
+ pipeline_tag: video-text-to-text
11
+ model-index:
12
+ - name: VideoChat-Flash-Qwen2_5-1_5B_res448
13
+ results:
14
+ - task:
15
+ type: multimodal
16
+ dataset:
17
+ name: MLVU
18
+ type: mlvu
19
+ metrics:
20
+ - type: accuracy
21
+ value: 65.7
22
+ name: accuracy
23
+ verified: true
24
+ - task:
25
+ type: multimodal
26
+ dataset:
27
+ name: MVBench
28
+ type: mvbench
29
+ metrics:
30
+ - type: accuracy
31
+ value: 70.0
32
+ name: accuracy
33
+ verified: true
34
+ - task:
35
+ type: multimodal
36
+ dataset:
37
+ name: Perception Test
38
+ type: percepTest
39
+ metrics:
40
+ - type: accuracy
41
+ value: 70.5
42
+ name: accuracy
43
+ verified: true
44
+ - task:
45
+ type: multimodal
46
+ dataset:
47
+ name: LongVideoBench
48
+ type: longvideobench
49
+ metrics:
50
+ - type: accuracy
51
+ value: 58.3
52
+ name: accuracy
53
+ verified: true
54
+ - task:
55
+ type: multimodal
56
+ dataset:
57
+ name: VideoMME (wo sub)
58
+ type: videomme
59
+ metrics:
60
+ - type: accuracy
61
+ value: 57.0
62
+ name: accuracy
63
+ verified: true
64
+ - task:
65
+ type: multimodal
66
+ dataset:
67
+ name: LVBench
68
+ type: lvbench
69
+ metrics:
70
+ - type: accuracy
71
+ value: 42.9
72
+ name: accuracy
73
+ verified: true
74
+
75
+
76
+ ---
77
+
78
+ # 🦜VideoChat-Flash-Qwen2_5-2B_res448⚡
79
+ [\[📰 Blog\]](https://internvideo.github.io/blog/2024-12-31-VideoChat-Flash) [\[📂 GitHub\]](https://github.com/OpenGVLab/VideoChat-Flash) [\[📜 Tech Report\]](https://www.arxiv.org/abs/2501.00574) [\[🗨️ Chat Demo\]](https://huggingface.co/spaces/OpenGVLab/VideoChat-Flash)
80
+
81
+ VideoChat-Flash-2B is constructed upon UMT-L (300M) and Qwen2.5-1.5B, employing only **16 tokens per frame**. By leveraging Yarn to extend the context window to 128k (Qwen2's native context window is 32k), our model supports input sequences of up to approximately **10,000 frames**.
82
+
83
+ > Note: Due to a predominantly English training corpus, the model only exhibits basic Chinese comprehension, to ensure optimal performance, using English for interaction is recommended.
84
+
85
+
86
+
87
+ ## 📈 Performance
88
+ | Model | MVBench | LongVideoBench | VideoMME(w/o sub)| Max Input Frames|
89
+ | --- | --- | --- | --- | --- |
90
+ |[VideoChat-Flash-Qwen2_5-2B@448](https://huggingface.co/OpenGVLab/VideoChat-Flash-Qwen2_5-2B_res448)| 70.0 | 58.3 | 57.0| 10000 |
91
+ |[VideoChat-Flash-Qwen2-7B@224](https://huggingface.co/OpenGVLab/VideoChat-Flash-Qwen2-7B_res224) | 73.2 | 64.2 | 64.0 | 10000 |
92
+ |[VideoChat-Flash-Qwen2_5-7B-1M@224](https://huggingface.co/OpenGVLab/VideoChat-Flash-Qwen2_5-7B-1M_res224) | 73.4 | **66.5** | 63.5 | 50000 |
93
+ |[VideoChat-Flash-Qwen2_5-7B_InternVideo2-1B@224](https://huggingface.co/OpenGVLab/VideoChat-Flash-Qwen2_5-7B_InternVideo2-1B) | **74.3** | 64.5 | 65.1 | 10000 |
94
+ |[VideoChat-Flash-Qwen2-7B@448](https://huggingface.co/OpenGVLab/VideoChat-Flash-Qwen2-7B_res448)| 74.0| 64.7 | **65.3**| 10000 |
95
+
96
+
97
+ ## 🚀 How to use the model
98
+
99
+ First, you need to install [flash attention2](https://github.com/Dao-AILab/flash-attention) and some other modules. We provide a simple installation example below:
100
+ ```
101
+ pip install transformers==4.40.1
102
+ pip install timm
103
+ pip install av
104
+ pip install imageio
105
+ pip install decord
106
+ pip install opencv-python
107
+ pip install flash-attn --no-build-isolation
108
+ ```
109
+ Then you could use our model:
110
+ ```python
111
+ from transformers import AutoModel, AutoTokenizer
112
+ import torch
113
+
114
+ # model setting
115
+ model_path = 'OpenGVLab/VideoChat-Flash-Qwen2_5-2B_res448'
116
+
117
+ tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
118
+ model = AutoModel.from_pretrained(model_path, trust_remote_code=True).to(torch.bfloat16).cuda()
119
+ image_processor = model.get_vision_tower().image_processor
120
+
121
+ mm_llm_compress = False # use the global compress or not
122
+ if mm_llm_compress:
123
+ model.config.mm_llm_compress = True
124
+ model.config.llm_compress_type = "uniform0_attention"
125
+ model.config.llm_compress_layer_list = [4, 18]
126
+ model.config.llm_image_token_ratio_list = [1, 0.75, 0.25]
127
+ else:
128
+ model.config.mm_llm_compress = False
129
+
130
+ # evaluation setting
131
+ max_num_frames = 512
132
+ generation_config = dict(
133
+ do_sample=False,
134
+ temperature=0.0,
135
+ max_new_tokens=1024,
136
+ top_p=0.1,
137
+ num_beams=1
138
+ )
139
+
140
+ video_path = "your_video.mp4"
141
+
142
+ # single-turn conversation
143
+ question1 = "Describe this video in detail."
144
+ output1, chat_history = model.chat(video_path=video_path, tokenizer=tokenizer, user_prompt=question1, return_history=True, max_num_frames=max_num_frames, generation_config=generation_config)
145
+
146
+ print(output1)
147
+
148
+ # multi-turn conversation
149
+ question2 = "How many people appear in the video?"
150
+ output2, chat_history = model.chat(video_path=video_path, tokenizer=tokenizer, user_prompt=question2, chat_history=chat_history, return_history=True, max_num_frames=max_num_frames, generation_config=generation_config)
151
+
152
+ print(output2)
153
+ ```
154
+
155
+ ## ✏️ Citation
156
+
157
+ ```bibtex
158
+
159
+ @article{li2024videochatflash,
160
+ title={VideoChat-Flash: Hierarchical Compression for Long-Context Video Modeling},
161
+ author={Li, Xinhao and Wang, Yi and Yu, Jiashuo and Zeng, Xiangyu and Zhu, Yuhan and Huang, Haian and Gao, Jianfei and Li, Kunchang and He, Yinan and Wang, Chenting and others},
162
+ journal={arXiv preprint arXiv:2501.00574},
163
+ year={2024}
164
+ }
165
+
166
+ ```
__init__.py ADDED
File without changes
added_tokens.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</tool_call>": 151658,
3
+ "<tool_call>": 151657,
4
+ "<|box_end|>": 151649,
5
+ "<|box_start|>": 151648,
6
+ "<|endoftext|>": 151643,
7
+ "<|file_sep|>": 151664,
8
+ "<|fim_middle|>": 151660,
9
+ "<|fim_pad|>": 151662,
10
+ "<|fim_prefix|>": 151659,
11
+ "<|fim_suffix|>": 151661,
12
+ "<|im_end|>": 151645,
13
+ "<|im_start|>": 151644,
14
+ "<|image_pad|>": 151655,
15
+ "<|object_ref_end|>": 151647,
16
+ "<|object_ref_start|>": 151646,
17
+ "<|quad_end|>": 151651,
18
+ "<|quad_start|>": 151650,
19
+ "<|repo_name|>": 151663,
20
+ "<|video_pad|>": 151656,
21
+ "<|vision_end|>": 151653,
22
+ "<|vision_pad|>": 151654,
23
+ "<|vision_start|>": 151652
24
+ }
config.json ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "VideoChatFlashQwenForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "modeling_videochat_flash.VideoChatFlashQwenConfig",
7
+ "AutoModel": "modeling_videochat_flash.VideoChatFlashQwenForCausalLM"
8
+ },
9
+ "attention_dropout": 0.0,
10
+ "bos_token_id": 151643,
11
+ "eos_token_id": 151645,
12
+ "frame_aspect_ratio": "square",
13
+ "frame_grid_pinpoints": null,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 1536,
16
+ "image_aspect_ratio": "anyres_nopad",
17
+ "image_crop_resolution": null,
18
+ "image_grid_pinpoints": [
19
+ [
20
+ 448,
21
+ 448
22
+ ],
23
+ [
24
+ 448,
25
+ 896
26
+ ],
27
+ [
28
+ 448,
29
+ 1344
30
+ ],
31
+ [
32
+ 448,
33
+ 1792
34
+ ],
35
+ [
36
+ 448,
37
+ 2240
38
+ ],
39
+ [
40
+ 448,
41
+ 2688
42
+ ],
43
+ [
44
+ 896,
45
+ 448
46
+ ],
47
+ [
48
+ 896,
49
+ 896
50
+ ],
51
+ [
52
+ 896,
53
+ 1344
54
+ ],
55
+ [
56
+ 896,
57
+ 1792
58
+ ],
59
+ [
60
+ 896,
61
+ 2240
62
+ ],
63
+ [
64
+ 896,
65
+ 2688
66
+ ],
67
+ [
68
+ 1344,
69
+ 448
70
+ ],
71
+ [
72
+ 1344,
73
+ 896
74
+ ],
75
+ [
76
+ 1344,
77
+ 1344
78
+ ],
79
+ [
80
+ 1344,
81
+ 1792
82
+ ],
83
+ [
84
+ 1344,
85
+ 2240
86
+ ],
87
+ [
88
+ 1344,
89
+ 2688
90
+ ],
91
+ [
92
+ 1792,
93
+ 448
94
+ ],
95
+ [
96
+ 1792,
97
+ 896
98
+ ],
99
+ [
100
+ 1792,
101
+ 1344
102
+ ],
103
+ [
104
+ 1792,
105
+ 1792
106
+ ],
107
+ [
108
+ 1792,
109
+ 2240
110
+ ],
111
+ [
112
+ 1792,
113
+ 2688
114
+ ],
115
+ [
116
+ 2240,
117
+ 448
118
+ ],
119
+ [
120
+ 2240,
121
+ 896
122
+ ],
123
+ [
124
+ 2240,
125
+ 1344
126
+ ],
127
+ [
128
+ 2240,
129
+ 1792
130
+ ],
131
+ [
132
+ 2240,
133
+ 2240
134
+ ],
135
+ [
136
+ 2240,
137
+ 2688
138
+ ],
139
+ [
140
+ 2688,
141
+ 448
142
+ ],
143
+ [
144
+ 2688,
145
+ 896
146
+ ],
147
+ [
148
+ 2688,
149
+ 1344
150
+ ],
151
+ [
152
+ 2688,
153
+ 1792
154
+ ],
155
+ [
156
+ 2688,
157
+ 2240
158
+ ],
159
+ [
160
+ 2688,
161
+ 2688
162
+ ]
163
+ ],
164
+ "image_split_resolution": null,
165
+ "initializer_range": 0.02,
166
+ "intermediate_size": 8960,
167
+ "llm_compress_layer_list": [
168
+ 24
169
+ ],
170
+ "llm_compress_type": "attention",
171
+ "llm_image_token_ratio_list": [
172
+ 1.0,
173
+ 0.5
174
+ ],
175
+ "max_num_pixels": 14745600000,
176
+ "max_position_embeddings": 32768,
177
+ "max_window_layers": 21,
178
+ "min_slow_num_frames": 4,
179
+ "mm_close_init": false,
180
+ "mm_hidden_size": 1024,
181
+ "mm_llm_compress": false,
182
+ "mm_local_num_frames": 4,
183
+ "mm_newline_position": "nothing",
184
+ "mm_num_compress_latents": 128,
185
+ "mm_num_compress_query_type": "learnable",
186
+ "mm_patch_merge_type": "spatial_nopad",
187
+ "mm_pos_num_frames": 8,
188
+ "mm_projector_lr": null,
189
+ "mm_projector_type": "tome16_mlp_hd64",
190
+ "mm_resampler_type": null,
191
+ "mm_spatial_pool_mode": "bilinear",
192
+ "mm_tunable_parts": "mm_vision_tower,mm_mlp_adapter,mm_language_model",
193
+ "mm_use_im_patch_token": false,
194
+ "mm_use_im_start_end": false,
195
+ "mm_vision_select_feature": "patch",
196
+ "mm_vision_select_layer": -2,
197
+ "mm_vision_tower": "umt-hd-large",
198
+ "mm_vision_tower_lr": 2e-06,
199
+ "model_type": "videochat_flash_qwen",
200
+ "num_attention_heads": 12,
201
+ "num_hidden_layers": 28,
202
+ "num_key_value_heads": 2,
203
+ "pos_skipping_range": 4096,
204
+ "rms_norm_eps": 1e-06,
205
+ "rope_scaling": null,
206
+ "rope_theta": 1000000.0,
207
+ "sliding_window": 32768,
208
+ "tie_word_embeddings": true,
209
+ "tokenizer_model_max_length": 32768,
210
+ "tokenizer_padding_side": "right",
211
+ "torch_dtype": "bfloat16",
212
+ "transformers_version": "4.40.1",
213
+ "use_cache": true,
214
+ "use_mm_proj": true,
215
+ "use_pos_skipping": false,
216
+ "use_sliding_window": false,
217
+ "vision_encode_type": "video_image",
218
+ "vision_tower_pretrained": null,
219
+ "vocab_size": 151936
220
+ }
constants.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
2
+ WORKER_HEART_BEAT_INTERVAL = 15
3
+
4
+ LOGDIR = "."
5
+
6
+ # Model Constants
7
+ IGNORE_INDEX = -100
8
+ IMAGE_TOKEN_INDEX = -200
9
+ DEFAULT_IMAGE_TOKEN = "<image>"
10
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
11
+ DEFAULT_IM_START_TOKEN = "<im_start>"
12
+ DEFAULT_IM_END_TOKEN = "<im_end>"
conversation.py ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from enum import auto, Enum
3
+ from typing import List, Any, Dict, Union, Tuple
4
+ import re
5
+ import base64
6
+ from io import BytesIO
7
+ from PIL import Image
8
+ from transformers import AutoTokenizer
9
+
10
+
11
+ class SeparatorStyle(Enum):
12
+ """Different separator style."""
13
+
14
+ SINGLE = auto()
15
+ TWO = auto()
16
+ MPT = auto()
17
+ PLAIN = auto()
18
+ CHATML = auto()
19
+ LLAMA_2 = auto()
20
+ LLAMA_3 = auto()
21
+ QWEN = auto()
22
+ GEMMA = auto()
23
+
24
+
25
+ @dataclasses.dataclass
26
+ class Conversation:
27
+ """A class that keeps all conversation history."""
28
+
29
+ system: str
30
+ roles: List[str]
31
+ messages: List[List[str]]
32
+ offset: int
33
+ sep_style: SeparatorStyle = SeparatorStyle.SINGLE
34
+ sep: str = "###"
35
+ sep2: str = None
36
+ version: str = "Unknown"
37
+
38
+ tokenizer_id: str = ""
39
+ tokenizer: Any = None
40
+ # Stop criteria (the default one is EOS token)
41
+ stop_str: Union[str, List[str]] = None
42
+ # Stops generation if meeting any token in this list
43
+ stop_token_ids: List[int] = None
44
+
45
+ skip_next: bool = False
46
+
47
+ def get_prompt(self):
48
+ messages = self.messages
49
+ if len(messages) > 0 and type(messages[0][1]) is tuple:
50
+ messages = self.messages.copy()
51
+ init_role, init_msg = messages[0].copy()
52
+ init_msg = init_msg[0]
53
+ if "mmtag" in self.version:
54
+ init_msg = init_msg.replace("<image>", "").strip()
55
+ messages[0] = (init_role, init_msg)
56
+ messages.insert(0, (self.roles[0], "<Image><image></Image>"))
57
+ messages.insert(1, (self.roles[1], "Received."))
58
+ elif not init_msg.startswith("<image>"):
59
+ init_msg = init_msg.replace("<image>", "").strip()
60
+ messages[0] = (init_role, "<image>\n" + init_msg)
61
+ else:
62
+ messages[0] = (init_role, init_msg)
63
+
64
+ if self.sep_style == SeparatorStyle.SINGLE:
65
+ ret = self.system + self.sep
66
+ for role, message in messages:
67
+ if message:
68
+ if type(message) is tuple:
69
+ message, _, _ = message
70
+ ret += role + ": " + message + self.sep
71
+ else:
72
+ ret += role + ":"
73
+
74
+ elif self.sep_style == SeparatorStyle.TWO:
75
+ seps = [self.sep, self.sep2]
76
+ ret = self.system + seps[0]
77
+ for i, (role, message) in enumerate(messages):
78
+ if message:
79
+ if type(message) is tuple:
80
+ message, _, _ = message
81
+ ret += role + ": " + message + seps[i % 2]
82
+ else:
83
+ ret += role + ":"
84
+
85
+ elif self.sep_style == SeparatorStyle.CHATML:
86
+ ret = "" if self.system == "" else self.system + self.sep + "\n"
87
+ for role, message in messages:
88
+ if message:
89
+ if type(message) is tuple:
90
+ message, images, _ = message
91
+ message = "<image>" * len(images) + message
92
+ ret += role + "\n" + message + self.sep + "\n"
93
+ else:
94
+ ret += role + "\n"
95
+ return ret
96
+
97
+ elif self.sep_style == SeparatorStyle.LLAMA_3:
98
+ chat_template_messages = [{"role": "system", "content": self.system}]
99
+ for role, message in messages:
100
+ if message:
101
+ if type(message) is tuple:
102
+ message, images = message
103
+ message = "<image>" * len(images) + message
104
+ chat_template_messages.append({"role": role, "content": message})
105
+
106
+ # print(chat_template_messages)
107
+ return self.tokenizer.apply_chat_template(chat_template_messages, tokenize=False, add_generation_prompt=True)
108
+ # ret = "" if self.system == "" else self.system + self.sep + "\n"
109
+ # for role, message in messages:
110
+ # if message:
111
+ # if type(message) is tuple:
112
+ # message, images = message
113
+ # message = "<image>" * len(images) + message
114
+ # ret += role + "\n" + message + self.sep + "\n"
115
+ # else:
116
+ # ret += role + "\n"
117
+ # return ret
118
+
119
+ elif self.sep_style == SeparatorStyle.MPT:
120
+ ret = self.system + self.sep
121
+ for role, message in messages:
122
+ if message:
123
+ if type(message) is tuple:
124
+ message, _, _ = message
125
+ ret += role + message + self.sep
126
+ else:
127
+ ret += role
128
+
129
+ elif self.sep_style == SeparatorStyle.GEMMA:
130
+ ret = ""
131
+ for i, (role, message) in enumerate(messages):
132
+ assert role == self.roles[i % 2], "Conversation should alternate user/assistant/user/assistant/..."
133
+ if message:
134
+ if type(message) is tuple:
135
+ message, _, _ = message
136
+ ret += role + message + self.sep
137
+ else:
138
+ ret += role
139
+
140
+ elif self.sep_style == SeparatorStyle.LLAMA_2:
141
+ wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n" if len(msg) > 0 else msg
142
+ wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
143
+ ret = ""
144
+
145
+ for i, (role, message) in enumerate(messages):
146
+ if i == 0:
147
+ assert message, "first message should not be none"
148
+ assert role == self.roles[0], "first message should come from user"
149
+ if message:
150
+ if type(message) is tuple:
151
+ message, _, _ = message
152
+ if i == 0:
153
+ message = wrap_sys(self.system) + message
154
+ if i % 2 == 0:
155
+ message = wrap_inst(message)
156
+ ret += self.sep + message
157
+ else:
158
+ ret += " " + message + " " + self.sep2
159
+ else:
160
+ ret += ""
161
+ ret = ret.lstrip(self.sep)
162
+
163
+ elif self.sep_style == SeparatorStyle.PLAIN:
164
+ seps = [self.sep, self.sep2]
165
+ ret = self.system
166
+ for i, (role, message) in enumerate(messages):
167
+ if message:
168
+ if type(message) is tuple:
169
+ message, _, _ = message
170
+ ret += message + seps[i % 2]
171
+ else:
172
+ ret += ""
173
+ else:
174
+ raise ValueError(f"Invalid style: {self.sep_style}")
175
+
176
+ return ret
177
+
178
+ def append_message(self, role, message):
179
+ self.messages.append([role, message])
180
+
181
+ def process_image(self, image, image_process_mode, return_pil=False, image_format="PNG"):
182
+ if image_process_mode == "Pad":
183
+
184
+ def expand2square(pil_img, background_color=(122, 116, 104)):
185
+ width, height = pil_img.size
186
+ if width == height:
187
+ return pil_img
188
+ elif width > height:
189
+ result = Image.new(pil_img.mode, (width, width), background_color)
190
+ result.paste(pil_img, (0, (width - height) // 2))
191
+ return result
192
+ else:
193
+ result = Image.new(pil_img.mode, (height, height), background_color)
194
+ result.paste(pil_img, ((height - width) // 2, 0))
195
+ return result
196
+
197
+ image = expand2square(image)
198
+ elif image_process_mode in ["Default", "Crop"]:
199
+ pass
200
+ elif image_process_mode == "Resize":
201
+ image = image.resize((336, 336))
202
+ else:
203
+ raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
204
+
205
+ if type(image) is not Image.Image:
206
+ image = Image.open(image).convert("RGB")
207
+
208
+ max_hw, min_hw = max(image.size), min(image.size)
209
+ aspect_ratio = max_hw / min_hw
210
+ max_len, min_len = 672, 448
211
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
212
+ longest_edge = int(shortest_edge * aspect_ratio)
213
+ W, H = image.size
214
+ if H > W:
215
+ H, W = longest_edge, shortest_edge
216
+ else:
217
+ H, W = shortest_edge, longest_edge
218
+ image = image.resize((W, H))
219
+ if return_pil:
220
+ return image
221
+ else:
222
+ buffered = BytesIO()
223
+ image.save(buffered, format=image_format)
224
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
225
+ return img_b64_str
226
+
227
+ def get_images(self, return_pil=False, return_path=False):
228
+ images = []
229
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
230
+ if i % 2 == 0:
231
+ if type(msg) is tuple:
232
+ msg, image, image_process_mode = msg
233
+ if type(image) != list:
234
+ image = [image]
235
+ for img in image:
236
+ if not return_path and self.is_image_file(img):
237
+ img = self.process_image(img, image_process_mode, return_pil=return_pil)
238
+ else:
239
+ images.append(img)
240
+ return images
241
+
242
+ def is_image_file(self, filename):
243
+ image_extensions = [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".webp"]
244
+ return any(filename.lower().endswith(ext) for ext in image_extensions)
245
+
246
+ def is_video_file(self, filename):
247
+ video_extensions = [".mp4", ".mov", ".avi", ".mkv", ".wmv", ".flv", ".mpeg", ".mpg"]
248
+ return any(filename.lower().endswith(ext) for ext in video_extensions)
249
+
250
+ def to_gradio_chatbot(self):
251
+ ret = []
252
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
253
+ if i % 2 == 0:
254
+ if type(msg) is tuple:
255
+ msg, image, image_process_mode = msg
256
+ if type(image) != list:
257
+ image = [image]
258
+ if len(image) == 1:
259
+ msg = "<image>\n" + msg.replace("<image>", "").strip()
260
+ else:
261
+ msg = re.sub(r"(<image>)\n(?=<image>)", r"\1 ", msg)
262
+
263
+ img_str_list = []
264
+ for img in image:
265
+ if self.is_image_file(img):
266
+ img_b64_str = self.process_image(img, "Default", return_pil=False, image_format="JPEG")
267
+ img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}" style="max-width: 256px; max-height: 256px; width: auto; height: auto; object-fit: contain;"/>'
268
+ img_str_list.append(img_str)
269
+ elif self.is_video_file(img):
270
+ ret.append(((img,), None))
271
+
272
+ msg = msg.strip()
273
+ img_place_holder = ""
274
+ for img_str in img_str_list:
275
+ img_place_holder += f"{img_str}\n\n"
276
+
277
+ if len(img_str_list) > 0:
278
+ msg = f"{img_place_holder}\n\n{msg}"
279
+
280
+ if len(msg) > 0:
281
+ ret.append([msg, None])
282
+ else:
283
+ ret.append([msg, None])
284
+ else:
285
+ ret[-1][-1] = msg
286
+ return ret
287
+
288
+ def copy(self):
289
+ return Conversation(system=self.system, roles=self.roles, messages=[[x, y] for x, y in self.messages], offset=self.offset, sep_style=self.sep_style, sep=self.sep, sep2=self.sep2, version=self.version)
290
+
291
+ def dict(self):
292
+ if len(self.get_images()) > 0:
293
+ return {
294
+ "system": self.system,
295
+ "roles": self.roles,
296
+ "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
297
+ "offset": self.offset,
298
+ "sep": self.sep,
299
+ "sep2": self.sep2,
300
+ }
301
+ return {
302
+ "system": self.system,
303
+ "roles": self.roles,
304
+ "messages": self.messages,
305
+ "offset": self.offset,
306
+ "sep": self.sep,
307
+ "sep2": self.sep2,
308
+ }
309
+
310
+
311
+ conv_vicuna_v0 = Conversation(
312
+ system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
313
+ roles=("Human", "Assistant"),
314
+ messages=[
315
+ ["Human", "What are the key differences between renewable and non-renewable energy sources?"],
316
+ [
317
+ "Assistant",
318
+ "Renewable energy sources are those that can be replenished naturally in a relatively "
319
+ "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
320
+ "Non-renewable energy sources, on the other hand, are finite and will eventually be "
321
+ "depleted, such as coal, oil, and natural gas. Here are some key differences between "
322
+ "renewable and non-renewable energy sources:\n"
323
+ "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
324
+ "energy sources are finite and will eventually run out.\n"
325
+ "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
326
+ "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
327
+ "and other negative effects.\n"
328
+ "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
329
+ "have lower operational costs than non-renewable sources.\n"
330
+ "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
331
+ "locations than non-renewable sources.\n"
332
+ "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
333
+ "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
334
+ "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
335
+ "non-renewable sources are not, and their depletion can lead to economic and social instability.\n",
336
+ ],
337
+ ],
338
+ offset=2,
339
+ sep_style=SeparatorStyle.SINGLE,
340
+ sep="###",
341
+ )
342
+
343
+ conv_vicuna_v1 = Conversation(
344
+ system="A chat between a curious user and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the user's questions.",
345
+ roles=("USER", "ASSISTANT"),
346
+ version="v1",
347
+ messages=[],
348
+ offset=0,
349
+ sep_style=SeparatorStyle.TWO,
350
+ sep=" ",
351
+ sep2="</s>",
352
+ )
353
+
354
+ conv_llama_2 = Conversation(
355
+ system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
356
+
357
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
358
+ roles=("USER", "ASSISTANT"),
359
+ version="llama_v2",
360
+ messages=[],
361
+ offset=0,
362
+ sep_style=SeparatorStyle.LLAMA_2,
363
+ sep="<s>",
364
+ sep2="</s>",
365
+ )
366
+
367
+ conv_llava_llama_2 = Conversation(
368
+ system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
369
+ roles=("USER", "ASSISTANT"),
370
+ version="llama_v2",
371
+ messages=[],
372
+ offset=0,
373
+ sep_style=SeparatorStyle.LLAMA_2,
374
+ sep="<s>",
375
+ sep2="</s>",
376
+ )
377
+
378
+ # conv_llava_llama_3 = Conversation(
379
+ # system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
380
+ # roles=("user", "assistant"),
381
+ # version="llama_v3",
382
+ # messages=[],
383
+ # offset=0,
384
+ # sep="<|eot_id|>",
385
+ # sep_style=SeparatorStyle.LLAMA_3,
386
+ # tokenizer_id="meta-llama/Meta-Llama-3-8B-Instruct",
387
+ # tokenizer=AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct"),
388
+ # stop_token_ids=[128009],
389
+ # )
390
+
391
+ conv_mistral_instruct = Conversation(
392
+ system="",
393
+ roles=("USER", "ASSISTANT"),
394
+ version="llama_v2",
395
+ messages=[],
396
+ offset=0,
397
+ sep_style=SeparatorStyle.LLAMA_2,
398
+ sep="",
399
+ sep2="</s>",
400
+ )
401
+
402
+ conv_llava_llama_2_simple = Conversation(
403
+ system="Answer the questions about the visual content that the user provides.",
404
+ roles=("USER", "ASSISTANT"),
405
+ version="llama_v2",
406
+ messages=[],
407
+ offset=0,
408
+ sep_style=SeparatorStyle.LLAMA_2,
409
+ sep="<s>",
410
+ sep2="</s>",
411
+ )
412
+
413
+ conv_llava_llama_2_mmtag = Conversation(
414
+ system="Answer the questions about the visual content that the user provides." "The visual content will be provided with the following format: <Image>visual content</Image>.",
415
+ roles=("USER", "ASSISTANT"),
416
+ version="llama_v2_mmtag",
417
+ messages=[],
418
+ offset=0,
419
+ sep_style=SeparatorStyle.LLAMA_2,
420
+ sep="<s>",
421
+ sep2="</s>",
422
+ )
423
+
424
+ conv_mpt = Conversation(
425
+ system="""<|im_start|>system
426
+ A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
427
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
428
+ version="mpt",
429
+ messages=[],
430
+ offset=0,
431
+ sep_style=SeparatorStyle.MPT,
432
+ sep="<|im_end|>",
433
+ )
434
+
435
+ conv_qwen = Conversation(
436
+ system="""<|im_start|>system
437
+ You are a helpful assistant.""",
438
+ roles=("<|im_start|>user", "<|im_start|>assistant"),
439
+ version="qwen",
440
+ messages=[],
441
+ offset=0,
442
+ sep_style=SeparatorStyle.CHATML,
443
+ sep="<|im_end|>",
444
+ )
445
+
446
+
447
+
448
+ conv_internlm_2 = Conversation(
449
+ system="""<|im_start|>system
450
+ You are a helpful assistant.""",
451
+ roles=("<|im_start|>user", "<|im_start|>assistant"),
452
+ version="internlm_2",
453
+ messages=[],
454
+ offset=0,
455
+ sep_style=SeparatorStyle.CHATML,
456
+ sep="<|im_end|>",
457
+ )
458
+
459
+ conv_gemma_instruct = Conversation(system="", roles=("<start_of_turn>user\n", "<start_of_turn>model\n"), version="gemma", messages=[], offset=0, sep_style=SeparatorStyle.GEMMA, sep="<end_of_turn>\n")
460
+
461
+ conv_llava_plain = Conversation(
462
+ system="",
463
+ roles=("", ""),
464
+ messages=[],
465
+ offset=0,
466
+ sep_style=SeparatorStyle.PLAIN,
467
+ sep="\n",
468
+ )
469
+
470
+ conv_llava_v0 = Conversation(
471
+ system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
472
+ roles=("Human", "Assistant"),
473
+ messages=[],
474
+ offset=0,
475
+ sep_style=SeparatorStyle.SINGLE,
476
+ sep="###",
477
+ )
478
+
479
+ conv_llava_v0_mmtag = Conversation(
480
+ system="A chat between a curious user and an artificial intelligence assistant. "
481
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
482
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
483
+ roles=("Human", "Assistant"),
484
+ messages=[],
485
+ offset=0,
486
+ sep_style=SeparatorStyle.SINGLE,
487
+ sep="###",
488
+ version="v0_mmtag",
489
+ )
490
+
491
+ conv_llava_v1 = Conversation(
492
+ system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
493
+ roles=("USER", "ASSISTANT"),
494
+ version="v1",
495
+ messages=[],
496
+ offset=0,
497
+ sep_style=SeparatorStyle.TWO,
498
+ sep=" ",
499
+ sep2="</s>",
500
+ )
501
+
502
+ conv_llava_v1_mmtag = Conversation(
503
+ system="A chat between a curious user and an artificial intelligence assistant. "
504
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
505
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
506
+ roles=("USER", "ASSISTANT"),
507
+ messages=[],
508
+ offset=0,
509
+ sep_style=SeparatorStyle.TWO,
510
+ sep=" ",
511
+ sep2="</s>",
512
+ version="v1_mmtag",
513
+ )
514
+
515
+ conv_mistral_orca = Conversation(
516
+ system="""<|im_start|>system
517
+ You are MistralOrca, a large language model trained by Alignment Lab AI. Write out your reasoning step-by-step to be sure you get the right answers!""",
518
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
519
+ version="mpt",
520
+ messages=[],
521
+ offset=0,
522
+ sep_style=SeparatorStyle.MPT,
523
+ sep="<|im_end|>",
524
+ )
525
+
526
+ conv_mistral_zephyr = Conversation(
527
+ system="""<|system|>
528
+ You are a helpful AI assistant.""",
529
+ roles=("<|user|>\n", "<|assistant|>\n"),
530
+ version="mpt",
531
+ messages=[],
532
+ offset=0,
533
+ sep_style=SeparatorStyle.MPT,
534
+ sep="</s>",
535
+ )
536
+
537
+ conv_mistral_direct = Conversation(
538
+ system="""<|im_start|>system
539
+ Answer the questions.""",
540
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
541
+ version="mpt",
542
+ messages=[],
543
+ offset=0,
544
+ sep_style=SeparatorStyle.MPT,
545
+ sep="<|im_end|>",
546
+ )
547
+
548
+ conv_chatml_direct = Conversation(
549
+ system="""<|im_start|>system
550
+ Answer the questions.""",
551
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
552
+ version="mpt",
553
+ messages=[],
554
+ offset=0,
555
+ sep_style=SeparatorStyle.MPT,
556
+ sep="<|im_end|>",
557
+ )
558
+
559
+ default_conversation = conv_vicuna_v0
560
+ conv_templates = {
561
+ "default": conv_vicuna_v0,
562
+ "v0": conv_vicuna_v0,
563
+ "v1": conv_vicuna_v1,
564
+ "vicuna_v1": conv_vicuna_v1,
565
+ "llama_2": conv_llama_2,
566
+ "mistral_instruct": conv_mistral_instruct,
567
+ "mistral_orca": conv_mistral_orca,
568
+ "mistral_zephyr": conv_mistral_zephyr,
569
+ "mistral_direct": conv_mistral_direct,
570
+ "plain": conv_llava_plain,
571
+ "v0_plain": conv_llava_plain,
572
+ "chatml_direct": conv_chatml_direct,
573
+ "llava_v0": conv_llava_v0,
574
+ "llava_v0_mmtag": conv_llava_v0_mmtag,
575
+ "llava_v1": conv_llava_v1,
576
+ "llava_v1_mmtag": conv_llava_v1_mmtag,
577
+ "llava_llama_2": conv_llava_llama_2,
578
+ # "llava_llama_3": conv_llava_llama_3,
579
+ "llava_llama_2_simple": conv_llava_llama_2_simple,
580
+ "llava_llama_2_mmtag": conv_llava_llama_2_mmtag,
581
+ "llava_mistral_instruct": conv_mistral_instruct,
582
+ "mpt": conv_mpt,
583
+ "qwen_1_5": conv_qwen,
584
+ "qwen_2": conv_qwen,
585
+ "internlm_2": conv_internlm_2,
586
+ "gemma_instruct": conv_gemma_instruct,
587
+ }
588
+
589
+
590
+ if __name__ == "__main__":
591
+ print(default_conversation.get_prompt())
592
+ print(default_conversation)
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "repetition_penalty": 1.1,
10
+ "temperature": 0.7,
11
+ "top_k": 20,
12
+ "top_p": 0.8,
13
+ "transformers_version": "4.39.2"
14
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
mm_projector_builder.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from typing import Callable, Tuple
4
+
5
+
6
+ def bipartite_soft_matching(
7
+ metric: torch.Tensor,
8
+ r: int,
9
+ ) -> Tuple[Callable, Callable]:
10
+ """
11
+ Applies ToMe with a balanced matching set (50%, 50%).
12
+
13
+ Input size is [batch, tokens, channels].
14
+ r indicates the number of tokens to remove (max 50% of tokens).
15
+ """
16
+ protected = 0
17
+
18
+ t = metric.shape[1]
19
+ r = min(r, (t - protected) // 2)
20
+
21
+ assert r > 0, r
22
+
23
+ with torch.no_grad():
24
+ metric = metric / metric.norm(dim=-1, keepdim=True)
25
+ a, b = metric[..., ::2, :], metric[..., 1::2, :]
26
+ scores = a @ b.transpose(-1, -2)
27
+
28
+ node_max, node_idx = scores.max(dim=-1)
29
+ edge_idx = node_max.argsort(dim=-1, descending=True)[..., None]
30
+
31
+ unm_idx = edge_idx[..., r:, :] # Unmerged Tokens
32
+ src_idx = edge_idx[..., :r, :] # Merged Tokens
33
+ dst_idx = node_idx[..., None].gather(dim=-2, index=src_idx)
34
+
35
+ def merge(x: torch.Tensor, mode="mean") -> torch.Tensor:
36
+ src, dst = x[..., ::2, :], x[..., 1::2, :]
37
+ n, t1, c = src.shape
38
+ unm = src.gather(dim=-2, index=unm_idx.expand(n, t1 - r, c))
39
+ src = src.gather(dim=-2, index=src_idx.expand(n, r, c))
40
+ dst = dst.scatter_add(-2, dst_idx.expand(n, r, c), src) # , reduce=mode)
41
+
42
+ return torch.cat([unm, dst], dim=1)
43
+
44
+ def unmerge(x: torch.Tensor) -> torch.Tensor:
45
+ unm_len = unm_idx.shape[1]
46
+ unm, dst = x[..., :unm_len, :], x[..., unm_len:, :]
47
+ n, _, c = unm.shape
48
+
49
+ src = dst.gather(dim=-2, index=dst_idx.expand(n, r, c))
50
+
51
+ out = torch.zeros(n, metric.shape[1], c, device=x.device, dtype=x.dtype)
52
+
53
+ out[..., 1::2, :] = dst
54
+ out.scatter_(dim=-2, index=(2 * unm_idx).expand(n, unm_len, c), src=unm)
55
+ out.scatter_(dim=-2, index=(2 * src_idx).expand(n, r, c), src=src)
56
+
57
+ return out
58
+
59
+ return merge, unmerge
60
+
61
+
62
+ def merge_wavg(
63
+ merge: Callable, x: torch.Tensor, size: torch.Tensor = None
64
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
65
+ """
66
+ Applies the merge function by taking a weighted average based on token size.
67
+ Returns the merged tensor and the new token sizes.
68
+ """
69
+ if size is None:
70
+ size = torch.ones_like(x[..., 0, None])
71
+
72
+ x = merge(x * size, mode="sum")
73
+ size = merge(size, mode="sum")
74
+
75
+ x = x / size
76
+ return x, size
77
+
78
+
79
+
80
+
81
+ class ToMe16_mlp_hd64(nn.Module):
82
+ def __init__(self, config, vision_cfg):
83
+ super().__init__()
84
+ self._config = config
85
+ self.mm_hidden_size = config.mm_hidden_size
86
+ self.hw = vision_cfg.image_size // vision_cfg.patch_size
87
+ self.num_attention_heads = vision_cfg.num_attention_heads
88
+ self.mlp = nn.Sequential(nn.Linear(config.mm_hidden_size, config.hidden_size),
89
+ nn.GELU(),
90
+ nn.Linear(config.hidden_size, config.hidden_size))
91
+ self.max_pos_hw = self.hw
92
+ self.max_pos_num_frames = config.mm_pos_num_frames
93
+ self.num_image_patches_per_side = 8
94
+ self.num_frame_patches_per_side = 4
95
+
96
+ def merge_tokens(self, x, target_num_token):
97
+ r"""
98
+ x = torch.randn(10, 2560, c)
99
+ x = merge_tokens(x, r_merge_list=[1280])
100
+ """
101
+ size = None
102
+ b, p, c = x.shape
103
+ tmp_p = p
104
+ r_merge_list = []
105
+ assert tmp_p > target_num_token, f"{tmp_p} should greater than {target_num_token}"
106
+ while tmp_p != target_num_token:
107
+ if tmp_p - target_num_token <= (tmp_p // 2):
108
+ r_merge_list.append(tmp_p - target_num_token)
109
+ break
110
+ else:
111
+ r_merge_list.append(tmp_p // 2)
112
+ tmp_p = tmp_p - (tmp_p // 2)
113
+
114
+
115
+ head = self.num_attention_heads
116
+
117
+ dim = c // head
118
+ for r in r_merge_list:
119
+ metric = x.reshape(b, p, head, dim).mean(2) # [b, p, c//head]
120
+ merge, _ = bipartite_soft_matching(
121
+ metric,
122
+ r
123
+ )
124
+ x, size = merge_wavg(merge, x, size)
125
+ _, p, _ = x.shape
126
+
127
+ return x
128
+
129
+
130
+
131
+ def forward(self, x, compress=False, local_num_frames=-1): # 单帧64
132
+ height = width = self.hw
133
+ assert height * width == x.shape[1]
134
+
135
+ if local_num_frames != -1 and local_num_frames != 1:
136
+ assert compress is True
137
+ if compress:
138
+ if local_num_frames != -1:
139
+ num_frames = local_num_frames
140
+ x = x.reshape(x.shape[0] // local_num_frames, -1, x.shape[-1])
141
+ else:
142
+ num_frames = x.shape[0]
143
+ x = x.reshape(1, -1, x.shape[-1])
144
+ num_tome_tokens = 16 * num_frames
145
+ else:
146
+ num_tome_tokens = 64
147
+
148
+ x = self.merge_tokens(x, target_num_token=num_tome_tokens)
149
+ x = self.mlp(x)
150
+ return x
151
+
152
+ @property
153
+ def config(self):
154
+ return {"mm_projector_type": "tome16_mlp_hd64"}
155
+
156
+
157
+
158
+
159
+ def build_vision_projector(config, delay_load=False, **kwargs):
160
+ projector_type = getattr(config, "mm_projector_type", "linear")
161
+
162
+ if projector_type == 'tome16_mlp_hd64':
163
+ return ToMe16_mlp_hd64(config, kwargs["vision_cfg"])
164
+
165
+ raise ValueError(f"Unknown projector type: {projector_type}")
mm_utils.py ADDED
@@ -0,0 +1,851 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from io import BytesIO
3
+ import base64
4
+ import math
5
+ import ast
6
+ import re
7
+ import torch
8
+ from transformers import StoppingCriteria
9
+ from .constants import IMAGE_TOKEN_INDEX
10
+ import random
11
+ import os
12
+ import io
13
+ import av
14
+ import cv2
15
+ import imageio
16
+ from decord import VideoReader
17
+ import numpy as np
18
+
19
+
20
+
21
+ ######################## load video ########################
22
+
23
+ def get_index(num_frames, num_segments):
24
+ seg_size = float(num_frames - 1) / num_segments
25
+ start = int(seg_size / 2)
26
+ offsets = np.array([
27
+ start + int(np.round(seg_size * idx)) for idx in range(num_segments)
28
+ ])
29
+ return offsets
30
+
31
+
32
+ def pts_to_secs(pts: int, time_base: float, start_pts: int) -> float:
33
+ """
34
+ Converts a present time with the given time base and start_pts offset to seconds.
35
+
36
+ Returns:
37
+ time_in_seconds (float): The corresponding time in seconds.
38
+
39
+ https://github.com/facebookresearch/pytorchvideo/blob/main/pytorchvideo/data/utils.py#L54-L64
40
+ """
41
+ if pts == math.inf:
42
+ return math.inf
43
+
44
+ return int(pts - start_pts) * time_base
45
+
46
+
47
+ def get_pyav_video_duration(video_reader):
48
+ video_stream = video_reader.streams.video[0]
49
+ video_duration = pts_to_secs(
50
+ video_stream.duration,
51
+ video_stream.time_base,
52
+ video_stream.start_time
53
+ )
54
+ return float(video_duration)
55
+
56
+
57
+
58
+ def get_frame_indices(num_frames, vlen, sample='middle', fix_start=None, input_fps=1, min_num_frames=1, max_num_frames=-1, local_num_frames=8):
59
+
60
+ if min_num_frames > vlen:
61
+ if sample == 'dynamic_fps1':
62
+ min_num_frames = (vlen // local_num_frames) * local_num_frames
63
+ else:
64
+ min_num_frames = vlen
65
+
66
+
67
+ if sample == 'dynamic_fps1':
68
+
69
+ duration = float(vlen) / input_fps
70
+ num_segments = int(duration // local_num_frames)
71
+ if num_segments == 0:
72
+ num_frames = local_num_frames
73
+ else:
74
+ num_frames = local_num_frames * num_segments
75
+
76
+ if max_num_frames > 0:
77
+ num_frames = min(num_frames, max_num_frames)
78
+ sample = "middle" # NOTE
79
+
80
+ # logger.info(f"? is OK (img), duation={duration} frames={num_frames}!!!!")
81
+
82
+ num_frames = max(min_num_frames, num_frames)
83
+
84
+ # print(f"\033[0;31m vlen={vlen}, input_fps={input_fps} num_frames={num_frames} \033[0m")
85
+
86
+ if sample in ["rand", "middle"]: # uniform sampling
87
+ acc_samples = min(num_frames, vlen)
88
+ # split the video into `acc_samples` intervals, and sample from each interval.
89
+ intervals = np.linspace(start=0, stop=vlen, num=acc_samples + 1).astype(int)
90
+ ranges = []
91
+ for idx, interv in enumerate(intervals[:-1]):
92
+ ranges.append((interv, intervals[idx + 1] - 1))
93
+ if sample == 'rand':
94
+ try:
95
+ frame_indices = [random.choice(range(x[0], x[1])) for x in ranges]
96
+ except:
97
+ frame_indices = np.random.permutation(vlen)[:acc_samples]
98
+ frame_indices.sort()
99
+ frame_indices = list(frame_indices)
100
+ elif fix_start is not None:
101
+ frame_indices = [x[0] + fix_start for x in ranges]
102
+ elif sample == 'middle':
103
+ frame_indices = [(x[0] + x[1]) // 2 for x in ranges]
104
+ else:
105
+ raise NotImplementedError
106
+
107
+ if len(frame_indices) < num_frames: # padded with last frame
108
+ padded_frame_indices = [frame_indices[-1]] * num_frames
109
+ padded_frame_indices[:len(frame_indices)] = frame_indices
110
+ frame_indices = padded_frame_indices
111
+ elif "fps" in sample: # fps0.5, sequentially sample frames at 0.5 fps
112
+ output_fps = float(sample[3:])
113
+ duration = float(vlen) / input_fps
114
+ delta = 1 / output_fps # gap between frames, this is also the clip length each frame represents
115
+ frame_seconds = np.arange(0 + delta / 2, duration + delta / 2, delta)
116
+ frame_indices = np.around(frame_seconds * input_fps).astype(int)
117
+ frame_indices = [e for e in frame_indices if e < vlen]
118
+ if max_num_frames > 0 and len(frame_indices) > max_num_frames:
119
+ frame_indices = frame_indices[:max_num_frames]
120
+ # frame_indices = np.linspace(0 + delta / 2, duration + delta / 2, endpoint=False, num=max_num_frames)
121
+ else:
122
+ raise ValueError(f"Not support sample type: {sample}")
123
+
124
+
125
+ return frame_indices
126
+
127
+
128
+ def read_frames_av(video_path, num_frames, sample='rand', client=None, fix_start=None, min_num_frames=1, max_num_frames=-1, clip=None, local_num_frames=8):
129
+ if clip is not None:
130
+ raise NotImplementedError("av don't support clip!!!")
131
+ if 's3://' in video_path:
132
+ video_bytes = client.get(video_path)
133
+ byteio = io.BytesIO(video_bytes)
134
+ byteio.seek(0)
135
+ reader = av.open(byteio)
136
+ else:
137
+ byteio = None
138
+ reader = av.open(video_path)
139
+ frames = [f.to_rgb().to_ndarray() for f in reader.decode(video=0)]
140
+ vlen = len(frames)
141
+ duration = get_pyav_video_duration(reader)
142
+ fps = vlen / float(duration)
143
+ frame_indices = get_frame_indices(
144
+ num_frames, vlen, sample=sample, fix_start=fix_start,
145
+ input_fps=fps, min_num_frames=min_num_frames, max_num_frames=max_num_frames, local_num_frames=local_num_frames
146
+ )
147
+ frames = np.stack([frames[idx] for idx in frame_indices]) # (T, H, W, C), torch.uint8
148
+ # frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8
149
+ if byteio != None:
150
+ byteio.close()
151
+
152
+ reader.close()
153
+
154
+ return frames, frame_indices, float(fps), duration
155
+
156
+
157
+ def read_frames_gif(
158
+ video_path, num_frames, sample='rand', fix_start=None,
159
+ min_num_frames=1, max_num_frames=-1, client=None, clip=None, local_num_frames=8
160
+ ):
161
+ if clip is not None:
162
+ raise NotImplementedError("Gif don't support clip!!!")
163
+ if 's3://' in video_path:
164
+ video_bytes = client.get(video_path)
165
+ byteio = io.BytesIO(video_bytes)
166
+ gif = imageio.get_reader(byteio)
167
+ else:
168
+ byteio = None
169
+ gif = imageio.get_reader(video_path)
170
+ vlen = len(gif)
171
+ fps = 1.
172
+ duration = vlen / fps
173
+ frame_indices = get_frame_indices(
174
+ num_frames, vlen, sample=sample, fix_start=fix_start,
175
+ min_num_frames=min_num_frames,
176
+ max_num_frames=max_num_frames, local_num_frames=local_num_frames,
177
+ input_fps=fps
178
+ )
179
+ frames = []
180
+
181
+ min_h = min_w = 100000
182
+ hw_set = set()
183
+ for index, frame in enumerate(gif):
184
+ # for index in frame_idxs:
185
+ if index in frame_indices:
186
+ frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2RGB)
187
+ frame = frame.astype(np.uint8)
188
+ # # (H x W x C) to (C x H x W)
189
+ # frame = frame.permute(2, 0, 1)
190
+ frames.append(frame)
191
+ hw_set.add(frame.shape)
192
+ if frame.shape[0] < min_h:
193
+ min_h = frame.shape[0]
194
+ if frame.shape[1] < min_w:
195
+ min_w = frame.shape[1]
196
+ # print(hw_set, min_h, min_w)
197
+ if len(hw_set) > 1:
198
+ frames = [i[:min_h, :min_w] for i in frames]
199
+
200
+ frames = np.stack(frames) # .float() / 255
201
+
202
+ if byteio != None:
203
+ byteio.close()
204
+
205
+ return frames, frame_indices, float(fps), duration # for tgif
206
+
207
+
208
+
209
+ def read_frames_decord(
210
+ video_path, num_frames, sample='rand', fix_start=None, min_num_frames=1,
211
+ max_num_frames=-1, client=None, clip=None, local_num_frames=8
212
+ ):
213
+
214
+ if video_path.endswith('.avi'):
215
+ return read_frames_av(video_path=video_path, num_frames=num_frames, sample=sample,
216
+ fix_start=fix_start, min_num_frames=min_num_frames, max_num_frames=max_num_frames,
217
+ client=client, clip=clip, local_num_frames=local_num_frames)
218
+ if 's3://' in video_path:
219
+ video_bytes = client.get(video_path)
220
+ if video_bytes is None or len(video_bytes) == 0:
221
+ raise ValueError(f"Can't read byte from {video_path}!")
222
+ byteio = io.BytesIO(video_bytes)
223
+ video_reader = VideoReader(byteio, num_threads=1)
224
+ else:
225
+ byteio = None
226
+ video_reader = VideoReader(video_path, num_threads=1)
227
+ vlen = len(video_reader)
228
+ fps = video_reader.get_avg_fps()
229
+ duration = vlen / float(fps)
230
+
231
+
232
+ if clip:
233
+ start, end = clip
234
+ start = max(0, start)
235
+ end = min(duration - 0.1, end)
236
+ duration = end - start
237
+ vlen = int(duration * fps)
238
+ start_index = int(start * fps)
239
+
240
+ frame_indices = get_frame_indices(
241
+ num_frames, vlen, sample=sample, fix_start=fix_start,
242
+ input_fps=fps, min_num_frames=min_num_frames, max_num_frames=max_num_frames, local_num_frames=local_num_frames
243
+ )
244
+ if clip:
245
+ frame_indices = [f + start_index for f in frame_indices]
246
+
247
+ # print(fps, frame_indices)
248
+ frames = video_reader.get_batch(frame_indices).asnumpy() # (T, H, W, C), torch.uint8
249
+ # https://github.com/dmlc/decord/issues/208
250
+ video_reader.seek(0)
251
+
252
+ if byteio != None:
253
+ byteio.close()
254
+ # frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8
255
+ return frames, frame_indices, float(fps), duration
256
+
257
+
258
+
259
+ def read_frames_img(
260
+ video_path, num_frames, sample='rand', fix_start=None, min_num_frames=1,
261
+ max_num_frames=-1, client=None, clip=None, local_num_frames=8
262
+ ):
263
+ def extract_frame_number(filename):
264
+ # Extract the numeric part from the filename using regular expressions
265
+ if filename.endswith('.jpg'):
266
+ match = re.search(r'_(\d+).jpg$', filename)
267
+ elif filename.endswith('.jpeg'):
268
+ match = re.search(r'_(\d+).jpeg$', filename)
269
+ elif filename.endswith('.png'):
270
+ match = re.search(r'_(\d+).png$', filename)
271
+ else:
272
+ raise NotImplementedError(f"Wrong filename: {filename}")
273
+
274
+ return int(match.group(1)) if match else -1
275
+
276
+
277
+ def sort_frames(frame_paths):
278
+ # Extract filenames from each path and sort by their numeric part
279
+ return sorted(frame_paths, key=lambda x: extract_frame_number(os.path.basename(x)))
280
+
281
+ # img_list=[]
282
+
283
+ if "s3://" in video_path:
284
+ img_list = sort_frames(client.list(video_path))
285
+ else:
286
+ img_list = sort_frames(list(os.listdir(video_path)))
287
+
288
+
289
+ if 'tvqa' in video_path.lower():
290
+ fps = 3.0
291
+ else:
292
+ fps = 1.0
293
+
294
+ if clip is not None:
295
+ start = float(clip[0])
296
+ end = float(clip[1])
297
+ start = max(0, start)
298
+ end = min(len(img_list) / fps, end)
299
+ vlen = (end - start) * fps
300
+ else:
301
+ vlen = len(img_list)
302
+
303
+ duration = vlen / fps
304
+
305
+ if min_num_frames > vlen:
306
+ if sample == 'dynamic_fps1':
307
+ min_num_frames = (vlen // local_num_frames) * local_num_frames
308
+ else:
309
+ min_num_frames = vlen
310
+
311
+ if sample == 'dynamic_fps1':
312
+ num_segments = int(duration // local_num_frames)
313
+ if num_segments == 0:
314
+ num_frames = local_num_frames
315
+ else:
316
+ num_frames = local_num_frames * num_segments
317
+ num_frames = min(num_frames, max_num_frames)
318
+ num_frames = max(min_num_frames, num_frames)
319
+
320
+ num_frames = int(num_frames)
321
+ if clip is not None:
322
+ def _get_index_by_time(start_sec, end_sec, num_segments=8, fps=1., max_frame=9999):
323
+ start_idx = max(1, round(start_sec * fps))
324
+ end_idx = min(round(end_sec * fps), max_frame)
325
+ seg_size = float(end_idx - start_idx) / (num_segments - 1)
326
+ offsets = np.array([start_idx + int(np.round(seg_size * idx)) for idx in range(num_segments)])
327
+ return offsets
328
+
329
+ frame_indices = _get_index_by_time(float(clip[0]), float(clip[1]), num_segments=num_frames, fps=fps, max_frame=len(img_list)-1)
330
+ else:
331
+ frame_indices = get_frame_indices(
332
+ num_frames, vlen, sample=sample, fix_start=fix_start,
333
+ min_num_frames=min_num_frames,
334
+ max_num_frames=max_num_frames, local_num_frames=local_num_frames
335
+ )
336
+
337
+ imgs = []
338
+ for idx in frame_indices:
339
+ frame_fname = os.path.join(video_path, img_list[idx])
340
+ if "s3://" in video_path:
341
+ img_bytes = client.get(frame_fname)
342
+ else:
343
+ with open(frame_fname, 'rb') as f:
344
+ img_bytes = f.read()
345
+ img_np = np.frombuffer(img_bytes, np.uint8)
346
+ img = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
347
+ cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
348
+ imgs.append(img)
349
+
350
+ frames = np.array(imgs, dtype=np.uint8)
351
+
352
+
353
+ return frames, frame_indices, fps, duration
354
+
355
+
356
+
357
+ VIDEO_READER_FUNCS = {
358
+ 'av': read_frames_av,
359
+ 'decord': read_frames_decord,
360
+ 'gif': read_frames_gif,
361
+ 'img': read_frames_img,
362
+ 'frame': read_frames_img
363
+ }
364
+
365
+
366
+
367
+ def load_video(video_path, max_num_frames=512, media_dict=None): #, media_dict):
368
+
369
+ if media_dict is None:
370
+ media_dict = {'video_read_type': 'decord'}
371
+
372
+ if type(video_path) != str:
373
+ assert len(video_path) == 1, video_path
374
+ video_path = video_path[0]
375
+
376
+ if 'start' in media_dict:
377
+ clip = [media_dict['start'], media_dict['end']]
378
+ else:
379
+ clip = None
380
+
381
+ client = None
382
+
383
+ frames, frame_indices, fps, duration = VIDEO_READER_FUNCS[media_dict['video_read_type']](video_path=video_path, num_frames=max_num_frames, sample='dynamic_fps1', fix_start=None, min_num_frames=64, max_num_frames=max_num_frames, client=client, clip=clip, local_num_frames=8)
384
+
385
+ sec = [str(round(f / fps, 1)) for f in frame_indices]
386
+
387
+ msg = f"\nThe video lasts for {duration:.2f} seconds, and {len(sec)} frames are uniformly sampled from it. "
388
+
389
+ return frames, msg
390
+
391
+
392
+ ######################## load video ########################
393
+
394
+
395
+ def resize_and_center_crop(image, shortest_edge_length):
396
+ # Calculate new dimensions and resize
397
+ aspect_ratio = float(image.width) / float(image.height)
398
+ if aspect_ratio > 1:
399
+ new_width = int(shortest_edge_length * aspect_ratio)
400
+ new_height = shortest_edge_length
401
+ else:
402
+ new_width = shortest_edge_length
403
+ new_height = int(shortest_edge_length / aspect_ratio)
404
+ resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
405
+
406
+ # Calculate the position and perform the center crop
407
+ left = (new_width - shortest_edge_length) / 2
408
+ top = (new_height - shortest_edge_length) / 2
409
+ right = (new_width + shortest_edge_length) / 2
410
+ bottom = (new_height + shortest_edge_length) / 2
411
+ cropped_image = resized_image.crop((left, top, right, bottom))
412
+
413
+ return cropped_image
414
+
415
+
416
+ def auto_pad_images(image, grid_params):
417
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
418
+ assert len(grid_params) > 0, "Grid parameters should not be empty"
419
+
420
+ # Step 1: Calculate and find the closest aspect ratio
421
+ input_width, input_height = image.size
422
+ input_aspect_ratio = input_width / input_height
423
+ candidate_resolutions = [(w / h, w, h) for w in grid_params for h in grid_params]
424
+ closest_aspect_ratio = min(candidate_resolutions, key=lambda x: abs(input_aspect_ratio - x[0]))
425
+
426
+ candidate_resolutions = [(x[1], x[2]) for x in candidate_resolutions if abs(x[0] - closest_aspect_ratio[0]) < 1e-3]
427
+
428
+ target_resolution = min(candidate_resolutions, key=lambda res: abs(max(input_width, input_height) / max(res) - 1))
429
+
430
+ resize_width, resize_height = target_resolution
431
+ if input_width > input_height:
432
+ resize_height = int(resize_width / input_aspect_ratio)
433
+ else:
434
+ resize_width = int(resize_height * input_aspect_ratio)
435
+ resized_image = image.resize((resize_width, resize_height), Image.ANTIALIAS)
436
+
437
+ # Step 5: Pad the resized image if necessary to match the target resolution
438
+ pad_width = target_resolution[0] - resize_width
439
+ pad_height = target_resolution[1] - resize_height
440
+ padded_image = Image.new("RGB", target_resolution, color=(0, 0, 0))
441
+ padded_image.paste(resized_image, (pad_width // 2, pad_height // 2))
442
+
443
+ return padded_image
444
+
445
+
446
+ def extract_patches(image, patch_size, overlap_ratio):
447
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
448
+ assert patch_size > 0, "Patch size should be greater than 0"
449
+ assert 0 <= overlap_ratio < 1, "Overlap ratio should be between 0 and 1"
450
+
451
+ W, H = image.size
452
+ patches = []
453
+
454
+ stride = int(patch_size * (1 - overlap_ratio))
455
+
456
+ num_patches_y = (H - patch_size) // stride + 1
457
+ num_patches_x = (W - patch_size) // stride + 1
458
+
459
+ y_start = (H - (num_patches_y - 1) * stride - patch_size) // 2
460
+ x_start = (W - (num_patches_x - 1) * stride - patch_size) // 2
461
+
462
+ for y in range(y_start, y_start + num_patches_y * stride, stride):
463
+ for x in range(x_start, x_start + num_patches_x * stride, stride):
464
+ patch = image.crop((x, y, x + patch_size, y + patch_size))
465
+ patches.append(patch)
466
+
467
+ return patches
468
+
469
+
470
+ def process_highres_image_crop_split(image, data_args, processor=None):
471
+ crop_resolution = data_args.image_crop_resolution
472
+ split_resolution = data_args.image_split_resolution
473
+ if processor is None:
474
+ processor = data_args.image_processor
475
+ image_crop = resize_and_center_crop(image, crop_resolution)
476
+ image_patches = extract_patches(image_crop, patch_size=split_resolution, overlap_ratio=0)
477
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
478
+ return torch.stack(image_patches, dim=0)
479
+
480
+
481
+ def process_highres_image(image, processor, grid_pinpoints):
482
+ grid_params = [int(x) for x in grid_pinpoints.split(",")]
483
+ width_height = max(image.size)
484
+ fit_grid_params = [x for x in grid_params if x >= width_height]
485
+ if len(fit_grid_params) == 0:
486
+ select_size = max(grid_params)
487
+ else:
488
+ select_size = min(fit_grid_params)
489
+ # FIXME: always select the 448
490
+ select_size = max(grid_params)
491
+ image_padded = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
492
+
493
+ # FIXME: this seems to be a bug that it always resizes instead of padding
494
+ image_original_resize = image.resize((processor.size["shortest_edge"], processor.size["shortest_edge"]))
495
+ image_padded = image_padded.resize((select_size, select_size))
496
+ image_patches = extract_patches(image_padded, patch_size=processor.size["shortest_edge"], overlap_ratio=0)
497
+ image_patches = [image_original_resize] + image_patches
498
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
499
+ return torch.stack(image_patches, dim=0)
500
+
501
+
502
+ def select_best_resolution(original_size, possible_resolutions, max_resolutions, patch_size):
503
+ """
504
+ Selects the best resolution from a list of possible resolutions based on the original size.
505
+
506
+ Args:
507
+ original_size (tuple): The original size of the image in the format (width, height).
508
+ possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
509
+
510
+ Returns:
511
+ tuple: The best fit resolution in the format (width, height).
512
+ """
513
+ original_width, original_height = original_size
514
+ best_fit = None
515
+ max_effective_resolution = 0
516
+ min_wasted_resolution = float("inf")
517
+
518
+ for width, height in possible_resolutions:
519
+ if max_resolutions != None and (width * height != patch_size * patch_size):
520
+ if (width * height+patch_size*patch_size) > max_resolutions: # NOTE 要算一个global
521
+ continue
522
+ # Calculate the downscaled size to keep the aspect ratio
523
+ scale = min(width / original_width, height / original_height)
524
+ downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
525
+
526
+ # Calculate effective and wasted resolutions
527
+ effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
528
+ wasted_resolution = (width * height) - effective_resolution
529
+
530
+ if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
531
+ max_effective_resolution = effective_resolution
532
+ min_wasted_resolution = wasted_resolution
533
+ best_fit = (width, height)
534
+
535
+ # print(f"original_size={original_size}, possible_resolutions={possible_resolutions}, max_resolutions={max_resolutions}, best_fit={best_fit}")
536
+ assert best_fit is not None, f"Can't find suitable fit in {possible_resolutions} at max:{max_resolutions}"
537
+ return best_fit
538
+
539
+
540
+ def resize_and_pad_image(image, target_resolution):
541
+ """
542
+ Resize and pad an image to a target resolution while maintaining aspect ratio.
543
+
544
+ Args:
545
+ image (PIL.Image.Image): The input image.
546
+ target_resolution (tuple): The target resolution (width, height) of the image.
547
+
548
+ Returns:
549
+ PIL.Image.Image: The resized and padded image.
550
+ """
551
+ original_width, original_height = image.size
552
+ target_width, target_height = target_resolution
553
+
554
+ # Determine which dimension (width or height) to fill
555
+ scale_w = target_width / original_width
556
+ scale_h = target_height / original_height
557
+
558
+ if scale_w < scale_h:
559
+ # Width will be filled completely
560
+ new_width = target_width
561
+ new_height = min(math.ceil(original_height * scale_w), target_height)
562
+ else:
563
+ # Height will be filled completely
564
+ new_height = target_height
565
+ new_width = min(math.ceil(original_width * scale_h), target_width)
566
+
567
+ # Resize the image
568
+ resized_image = image.resize((new_width, new_height))
569
+
570
+ # Create a new image with the target size and paste the resized image onto it
571
+ new_image = Image.new("RGB", (target_width, target_height), (0, 0, 0))
572
+ paste_x = (target_width - new_width) // 2
573
+ paste_y = (target_height - new_height) // 2
574
+ new_image.paste(resized_image, (paste_x, paste_y))
575
+
576
+ return new_image
577
+
578
+
579
+ def divide_to_patches(image, patch_size):
580
+ """
581
+ Divides an image into patches of a specified size.
582
+
583
+ Args:
584
+ image (PIL.Image.Image): The input image.
585
+ patch_size (int): The size of each patch.
586
+
587
+ Returns:
588
+ list: A list of PIL.Image.Image objects representing the patches.
589
+ """
590
+ patches = []
591
+ width, height = image.size
592
+ for i in range(0, height, patch_size):
593
+ for j in range(0, width, patch_size):
594
+ box = (j, i, j + patch_size, i + patch_size)
595
+ patch = image.crop(box)
596
+ patches.append(patch)
597
+
598
+ return patches
599
+
600
+
601
+ def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size, max_resolutions=None):
602
+ """
603
+ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
604
+
605
+ Args:
606
+ image_size (tuple): The size of the input image in the format (width, height).
607
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
608
+ patch_size (int): The size of each image patch.
609
+
610
+ Returns:
611
+ tuple: The shape of the image patch grid in the format (width, height).
612
+ """
613
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
614
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
615
+ # Use regex to extract the range from the input string
616
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
617
+ range_start = tuple(map(int, matches[0]))
618
+ range_end = tuple(map(int, matches[-1]))
619
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
620
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
621
+ # Multiply all elements by patch_size
622
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
623
+ if type(grid_pinpoints) is list:
624
+ possible_resolutions = grid_pinpoints
625
+ else:
626
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
627
+ width, height = select_best_resolution(image_size, possible_resolutions, max_resolutions=max_resolutions, patch_size=patch_size)
628
+
629
+ # print("get width/patch size", width, patch_size, flush=True)
630
+
631
+ return width // patch_size, height // patch_size
632
+
633
+
634
+ def process_anyres_image(image, processor, grid_pinpoints):
635
+ """
636
+ Process an image with variable resolutions.
637
+
638
+ Args:
639
+ image (PIL.Image.Image): The input image to be processed.
640
+ processor: The image processor object.
641
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
642
+
643
+ Returns:
644
+ torch.Tensor: A tensor containing the processed image patches.
645
+ """
646
+ raise NotImplementedError
647
+ # Convert grid_pinpoints from string to list
648
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
649
+ try:
650
+ patch_size = processor.size[0]
651
+ except Exception as e:
652
+ patch_size = processor.size["shortest_edge"]
653
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
654
+ # Use regex to extract the range from the input string
655
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
656
+ range_start = tuple(map(int, matches[0]))
657
+ range_end = tuple(map(int, matches[-1]))
658
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
659
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
660
+ # Multiply all elements by patch_size
661
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
662
+
663
+ if type(grid_pinpoints) is list:
664
+ possible_resolutions = grid_pinpoints
665
+ else:
666
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
667
+ best_resolution = select_best_resolution(image.size, possible_resolutions)
668
+ image_padded = resize_and_pad_image(image, best_resolution)
669
+
670
+ patches = divide_to_patches(image_padded, processor.crop_size["height"])
671
+
672
+ # FIXME: this seems to be a bug that it resizes instead of pad.
673
+ # but to keep it consistent with previous, i will keep it as it is
674
+ # TODO: uncomment below to ablate with the padding
675
+ if isinstance(processor.size, dict):
676
+ shortest_edge = processor.size["shortest_edge"]
677
+ else:
678
+ shortest_edge = min(processor.size)
679
+ image_original_resize = image.resize((shortest_edge, shortest_edge))
680
+ # image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
681
+ # image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
682
+
683
+ image_patches = [image_original_resize] + patches
684
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
685
+
686
+ # print("image.size", image.size, "len(image_patches):", len(image_patches), "patch_size:", image_patches[0].shape)
687
+ return torch.stack(image_patches, dim=0)
688
+
689
+ def process_anyres_image_nopad(image, processor, grid_pinpoints):
690
+ """
691
+ Process an image with variable resolutions.
692
+
693
+ Args:
694
+ image (PIL.Image.Image): The input image to be processed.
695
+ processor: The image processor object.
696
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
697
+
698
+ Returns:
699
+ torch.Tensor: A tensor containing the processed image patches.
700
+ """
701
+ # Convert grid_pinpoints from string to list
702
+ try:
703
+ patch_size = processor.size[0]
704
+ except Exception as e:
705
+ patch_size = processor.size["shortest_edge"]
706
+
707
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
708
+
709
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
710
+
711
+ # Use regex to extract the range from the input string
712
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
713
+ range_start = tuple(map(int, matches[0]))
714
+ range_end = tuple(map(int, matches[-1]))
715
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
716
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
717
+ # Multiply all elements by patch_size
718
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
719
+
720
+ if type(grid_pinpoints) is list:
721
+ possible_resolutions = grid_pinpoints
722
+ else:
723
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
724
+ best_resolution = select_best_resolution(image.size, possible_resolutions, max_resolutions=None, patch_size=patch_size) # 目前图像无限制
725
+ # image_padded = resize_and_pad_image(image, best_resolution)
726
+
727
+ patches = divide_to_patches(image.resize(best_resolution), patch_size)
728
+
729
+ # FIXME: this seems to be a bug that it resizes instead of pad.
730
+ # but to keep it consistent with previous, i will keep it as it is
731
+ # TODO: uncomment below to ablate with the padding
732
+ if isinstance(processor.size, dict):
733
+ shortest_edge = processor.size["shortest_edge"]
734
+ else:
735
+ shortest_edge = min(processor.size)
736
+ image_original_resize = image.resize((shortest_edge, shortest_edge))
737
+ # image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
738
+ # image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
739
+
740
+ image_patches = [image_original_resize] + patches
741
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
742
+
743
+ # raise ValueError(f"image.size: {image.size} len(image_patches): {len(image_patches)}, patch_size:, {image_patches[0].shape}, possible_resolutions:, {possible_resolutions}, best: {best_resolution}")
744
+ return torch.stack(image_patches, dim=0)
745
+
746
+
747
+ def load_image_from_base64(image):
748
+ return Image.open(BytesIO(base64.b64decode(image)))
749
+
750
+
751
+ def expand2square(pil_img, background_color):
752
+ width, height = pil_img.size
753
+ if width == height:
754
+ return pil_img
755
+ elif width > height:
756
+ result = Image.new(pil_img.mode, (width, width), background_color)
757
+ result.paste(pil_img, (0, (width - height) // 2))
758
+ return result
759
+ else:
760
+ result = Image.new(pil_img.mode, (height, height), background_color)
761
+ result.paste(pil_img, ((height - width) // 2, 0))
762
+ return result
763
+
764
+
765
+ def process_images(images, image_processor, model_cfg):
766
+ image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
767
+ new_images = []
768
+ if image_aspect_ratio == "highres":
769
+ raise NotImplementedError
770
+ for image in images:
771
+ image = process_highres_image(image, image_processor, model_cfg.image_grid_pinpoints)
772
+ new_images.append(image)
773
+ elif "anyres" in image_aspect_ratio:
774
+ for image in images:
775
+ if "nopad" in image_aspect_ratio:
776
+ image = process_anyres_image_nopad(image, image_processor, model_cfg.image_grid_pinpoints)
777
+ else:
778
+ image = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints)
779
+ new_images.append(image)
780
+ elif image_aspect_ratio == "crop_split":
781
+ raise NotImplementedError
782
+ for image in images:
783
+ image = process_highres_image_crop_split(image, model_cfg, image_processor)
784
+ new_images.append(image)
785
+ elif image_aspect_ratio == "pad":
786
+ for image in images:
787
+ image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean))
788
+ image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
789
+ new_images.append(image)
790
+ else:
791
+ return image_processor.preprocess(images, return_tensors="pt")["pixel_values"]
792
+ if all(x.shape == new_images[0].shape for x in new_images):
793
+ new_images = torch.stack(new_images, dim=0)
794
+ return new_images
795
+
796
+
797
+ def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
798
+ prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
799
+
800
+ def insert_separator(X, sep):
801
+ return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
802
+
803
+ input_ids = []
804
+ offset = 0
805
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
806
+ offset = 1
807
+ input_ids.append(prompt_chunks[0][0])
808
+
809
+ for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
810
+ input_ids.extend(x[offset:])
811
+
812
+ if return_tensors is not None:
813
+ if return_tensors == "pt":
814
+ return torch.tensor(input_ids, dtype=torch.long)
815
+ raise ValueError(f"Unsupported tensor type: {return_tensors}")
816
+ return input_ids
817
+
818
+
819
+ def get_model_name_from_path(model_path):
820
+ model_path = model_path.strip("/")
821
+ model_paths = model_path.split("/")
822
+ if model_paths[-1].startswith("checkpoint-"):
823
+ return model_paths[-2] + "_" + model_paths[-1]
824
+ else:
825
+ return model_paths[-1]
826
+
827
+
828
+ class KeywordsStoppingCriteria(StoppingCriteria):
829
+ def __init__(self, keywords, tokenizer, input_ids):
830
+ self.keywords = keywords
831
+ self.keyword_ids = []
832
+ for keyword in keywords:
833
+ cur_keyword_ids = tokenizer(keyword).input_ids
834
+ if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
835
+ cur_keyword_ids = cur_keyword_ids[1:]
836
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
837
+ self.tokenizer = tokenizer
838
+ self.start_len = input_ids.shape[1]
839
+
840
+ def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
841
+ assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
842
+ offset = min(output_ids.shape[1] - self.start_len, 3)
843
+ self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
844
+ for keyword_id in self.keyword_ids:
845
+ if output_ids[0, -keyword_id.shape[0] :] == keyword_id:
846
+ return True
847
+ outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
848
+ for keyword in self.keywords:
849
+ if keyword in outputs:
850
+ return True
851
+ return False
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d7599e40867eaac136fffa154b070c71aa22bc73b3c1ceece1dcb094f70b475
3
+ size 4143085560
modeling_qwen2_flash.py ADDED
@@ -0,0 +1,1596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # transformers==4.39.2 NOTE
3
+ # Borrows some implementations from https://github.com/Cooperx521/PyramidDrop, thanks!
4
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
5
+ #
6
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
7
+ # and OPT implementations in this library. It has been modified from its
8
+ # original forms to accommodate minor architectural differences compared
9
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ """ PyTorch Qwen2 model."""
23
+ import inspect
24
+ import math
25
+ import warnings
26
+ from typing import List, Optional, Tuple, Union
27
+
28
+ import torch
29
+ import torch.nn.functional as F
30
+ import torch.utils.checkpoint
31
+ from torch import nn
32
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.cache_utils import Cache, DynamicCache
36
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
37
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
40
+ from transformers.utils import (
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
49
+ from .constants import IGNORE_INDEX
50
+
51
+
52
+ if is_flash_attn_2_available():
53
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
54
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
55
+
56
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
57
+
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+
62
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
63
+ _CONFIG_FOR_DOC = "Qwen2Config"
64
+
65
+ QWEN2_PRETRAINED_MODEL_ARCHIVE_LIST = [
66
+ "Qwen/Qwen2-7B-beta",
67
+ # See all Qwen2 models at https://huggingface.co/models?filter=qwen2
68
+ ]
69
+
70
+
71
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
72
+ def _get_unpad_data(attention_mask):
73
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
74
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
75
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
76
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
77
+ return (
78
+ indices,
79
+ cu_seqlens,
80
+ max_seqlen_in_batch,
81
+ )
82
+
83
+
84
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
85
+ class Qwen2RMSNorm(nn.Module):
86
+ def __init__(self, hidden_size, eps=1e-6):
87
+ """
88
+ Qwen2RMSNorm is equivalent to T5LayerNorm
89
+ """
90
+ super().__init__()
91
+ self.weight = nn.Parameter(torch.ones(hidden_size))
92
+ self.variance_epsilon = eps
93
+
94
+ def forward(self, hidden_states):
95
+ input_dtype = hidden_states.dtype
96
+ hidden_states = hidden_states.to(torch.float32)
97
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
98
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
99
+ return self.weight * hidden_states.to(input_dtype)
100
+
101
+
102
+ class Qwen2RotaryEmbedding(nn.Module):
103
+ def __init__(
104
+ self,
105
+ dim=None,
106
+ max_position_embeddings=2048,
107
+ base=10000,
108
+ device=None,
109
+ scaling_factor=1.0,
110
+ rope_type="default",
111
+ config: Optional[Qwen2Config] = None,
112
+ ):
113
+ super().__init__()
114
+ # TODO (joao): remove the `if` below, only used for BC
115
+ self.rope_kwargs = {}
116
+ if config is None:
117
+ logger.warning_once(
118
+ "`Qwen2RotaryEmbedding` can now be fully parameterized by passing the model config through the "
119
+ "`config` argument. All other arguments will be removed in v4.46"
120
+ )
121
+ self.rope_kwargs = {
122
+ "rope_type": rope_type,
123
+ "factor": scaling_factor,
124
+ "dim": dim,
125
+ "base": base,
126
+ "max_position_embeddings": max_position_embeddings,
127
+ }
128
+ self.rope_type = rope_type
129
+ self.max_seq_len_cached = max_position_embeddings
130
+ self.original_max_seq_len = max_position_embeddings
131
+ else:
132
+ # BC: "rope_type" was originally "type"
133
+ if config.rope_scaling is not None:
134
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
135
+ else:
136
+ self.rope_type = "default"
137
+ self.max_seq_len_cached = config.max_position_embeddings
138
+ self.original_max_seq_len = config.max_position_embeddings
139
+
140
+ self.config = config
141
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
142
+
143
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
144
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
145
+ self.original_inv_freq = self.inv_freq
146
+
147
+ def _dynamic_frequency_update(self, position_ids, device):
148
+ """
149
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
150
+ 1 - growing beyond the cached sequence length (allow scaling)
151
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
152
+ """
153
+ seq_len = torch.max(position_ids) + 1
154
+ if seq_len > self.max_seq_len_cached: # growth
155
+ inv_freq, self.attention_scaling = self.rope_init_fn(
156
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
157
+ )
158
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
159
+ self.max_seq_len_cached = seq_len
160
+
161
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
162
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
163
+ self.max_seq_len_cached = self.original_max_seq_len
164
+
165
+ @torch.no_grad()
166
+ def forward(self, x, position_ids):
167
+ if "dynamic" in self.rope_type:
168
+ self._dynamic_frequency_update(position_ids, device=x.device)
169
+
170
+ # Core RoPE block
171
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
172
+ position_ids_expanded = position_ids[:, None, :].float()
173
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
174
+ device_type = x.device.type
175
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
176
+ with torch.autocast(device_type=device_type, enabled=False):
177
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
178
+ emb = torch.cat((freqs, freqs), dim=-1)
179
+ cos = emb.cos()
180
+ sin = emb.sin()
181
+
182
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
183
+ cos = cos * self.attention_scaling
184
+ sin = sin * self.attention_scaling
185
+
186
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
187
+
188
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
189
+ def rotate_half(x):
190
+ """Rotates half the hidden dims of the input."""
191
+ x1 = x[..., : x.shape[-1] // 2]
192
+ x2 = x[..., x.shape[-1] // 2 :]
193
+ return torch.cat((-x2, x1), dim=-1)
194
+
195
+
196
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
197
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
198
+ """Applies Rotary Position Embedding to the query and key tensors.
199
+
200
+ Args:
201
+ q (`torch.Tensor`): The query tensor.
202
+ k (`torch.Tensor`): The key tensor.
203
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
204
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
205
+ position_ids (`torch.Tensor`):
206
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
207
+ used to pass offsetted position ids when working with a KV-cache.
208
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
209
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
210
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
211
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
212
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
213
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
214
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
215
+ Returns:
216
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
217
+ """
218
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
219
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
220
+ q_embed = (q * cos) + (rotate_half(q) * sin)
221
+ k_embed = (k * cos) + (rotate_half(k) * sin)
222
+ return q_embed, k_embed
223
+
224
+
225
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
226
+ class Qwen2MLP(nn.Module):
227
+ def __init__(self, config):
228
+ super().__init__()
229
+ self.config = config
230
+ self.hidden_size = config.hidden_size
231
+ self.intermediate_size = config.intermediate_size
232
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
233
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
234
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
235
+ self.act_fn = ACT2FN[config.hidden_act]
236
+
237
+ def forward(self, x):
238
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
239
+
240
+
241
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
242
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
243
+ """
244
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
245
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
246
+ """
247
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
248
+ if n_rep == 1:
249
+ return hidden_states
250
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
251
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
252
+
253
+
254
+ class Qwen2Attention(nn.Module):
255
+ """
256
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
257
+ and "Generating Long Sequences with Sparse Transformers".
258
+ """
259
+
260
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
261
+ super().__init__()
262
+ self.config = config
263
+ self.layer_idx = layer_idx
264
+ if layer_idx is None:
265
+ logger.warning_once(
266
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
267
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
268
+ "when creating this class."
269
+ )
270
+
271
+ self.hidden_size = config.hidden_size
272
+ self.num_heads = config.num_attention_heads
273
+ self.head_dim = self.hidden_size // self.num_heads
274
+ self.num_key_value_heads = config.num_key_value_heads
275
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
276
+ self.max_position_embeddings = config.max_position_embeddings
277
+ self.rope_theta = config.rope_theta
278
+ self.is_causal = True
279
+ self.attention_dropout = config.attention_dropout
280
+
281
+ if (self.head_dim * self.num_heads) != self.hidden_size:
282
+ raise ValueError(
283
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
284
+ f" and `num_heads`: {self.num_heads})."
285
+ )
286
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
287
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
288
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
289
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
290
+
291
+ self.rotary_emb = Qwen2RotaryEmbedding(
292
+ self.head_dim,
293
+ max_position_embeddings=self.max_position_embeddings,
294
+ base=self.rope_theta,
295
+ )
296
+
297
+ def forward(
298
+ self,
299
+ hidden_states: torch.Tensor,
300
+ attention_mask: Optional[torch.Tensor] = None,
301
+ position_ids: Optional[torch.LongTensor] = None,
302
+ past_key_value: Optional[Cache] = None,
303
+ output_attentions: bool = False,
304
+ use_cache: bool = False,
305
+ **kwargs,
306
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
307
+ if "padding_mask" in kwargs:
308
+ warnings.warn(
309
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
310
+ )
311
+ bsz, q_len, _ = hidden_states.size()
312
+
313
+ query_states = self.q_proj(hidden_states)
314
+ key_states = self.k_proj(hidden_states)
315
+ value_states = self.v_proj(hidden_states)
316
+
317
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
318
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
319
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
320
+
321
+ kv_seq_len = key_states.shape[-2]
322
+ if past_key_value is not None:
323
+ if self.layer_idx is None:
324
+ raise ValueError(
325
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
326
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
327
+ "with a layer index."
328
+ )
329
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
330
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
331
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
332
+
333
+ if past_key_value is not None:
334
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
335
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
336
+
337
+ # repeat k/v heads if n_kv_heads < n_heads
338
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
339
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
340
+
341
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
342
+
343
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
344
+ raise ValueError(
345
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
346
+ f" {attn_weights.size()}"
347
+ )
348
+
349
+ if attention_mask is not None:
350
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
351
+ raise ValueError(
352
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
353
+ )
354
+
355
+ attn_weights = attn_weights + attention_mask
356
+
357
+ # upcast attention to fp32
358
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
359
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
360
+ attn_output = torch.matmul(attn_weights, value_states)
361
+
362
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
363
+ raise ValueError(
364
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
365
+ f" {attn_output.size()}"
366
+ )
367
+
368
+ attn_output = attn_output.transpose(1, 2).contiguous()
369
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
370
+
371
+ attn_output = self.o_proj(attn_output)
372
+
373
+ if not output_attentions:
374
+ attn_weights = None
375
+
376
+ return attn_output, attn_weights, past_key_value
377
+
378
+
379
+ class Qwen2FlashAttention2(Qwen2Attention):
380
+ """
381
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
382
+ as the weights of the module stays untouched. The only required change would be on the forward pass
383
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
384
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
385
+ config.max_window_layers layers.
386
+ """
387
+
388
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
389
+ def __init__(self, *args, **kwargs):
390
+ super().__init__(*args, **kwargs)
391
+
392
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
393
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
394
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
395
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
396
+
397
+ def forward(
398
+ self,
399
+ hidden_states: torch.Tensor,
400
+ attention_mask: Optional[torch.Tensor] = None,
401
+ position_ids: Optional[torch.LongTensor] = None,
402
+ past_key_value: Optional[Cache] = None,
403
+ output_attentions: bool = False,
404
+ use_cache: bool = False,
405
+ **kwargs,
406
+ ):
407
+ if "padding_mask" in kwargs:
408
+ warnings.warn(
409
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
410
+ )
411
+
412
+ # overwrite attention_mask with padding_mask
413
+ attention_mask = kwargs.pop("padding_mask")
414
+ bsz, q_len, _ = hidden_states.size()
415
+
416
+ query_states = self.q_proj(hidden_states)
417
+ key_states = self.k_proj(hidden_states)
418
+ value_states = self.v_proj(hidden_states)
419
+
420
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
421
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
422
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
423
+
424
+ kv_seq_len = key_states.shape[-2]
425
+ if past_key_value is not None:
426
+ if self.layer_idx is None:
427
+ raise ValueError(
428
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
429
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
430
+ "with a layer index."
431
+ )
432
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
433
+
434
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
435
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
436
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
437
+
438
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
439
+
440
+ use_sliding_windows = (
441
+ _flash_supports_window_size
442
+ and getattr(self.config, "sliding_window", None) is not None
443
+ and kv_seq_len > self.config.sliding_window
444
+ and self.config.use_sliding_window
445
+ )
446
+
447
+ if not _flash_supports_window_size:
448
+ logger.warning_once(
449
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
450
+ " make sure to upgrade flash-attn library."
451
+ )
452
+
453
+ if past_key_value is not None:
454
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
455
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
456
+ if (
457
+ getattr(self.config, "sliding_window", None) is not None
458
+ and kv_seq_len > self.config.sliding_window
459
+ and cache_has_contents
460
+ ):
461
+ slicing_tokens = 1 - self.config.sliding_window
462
+
463
+ past_key = past_key_value[self.layer_idx][0]
464
+ past_value = past_key_value[self.layer_idx][1]
465
+
466
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
467
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
468
+
469
+ if past_key.shape[-2] != self.config.sliding_window - 1:
470
+ raise ValueError(
471
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
472
+ f" {past_key.shape}"
473
+ )
474
+
475
+ if attention_mask is not None:
476
+ attention_mask = attention_mask[:, slicing_tokens:]
477
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
478
+
479
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
480
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
481
+
482
+ # repeat k/v heads if n_kv_heads < n_heads
483
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
484
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
485
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
486
+
487
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
488
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
489
+ # cast them back in float16 just to be sure everything works as expected.
490
+ input_dtype = query_states.dtype
491
+ if input_dtype == torch.float32:
492
+ if torch.is_autocast_enabled():
493
+ target_dtype = torch.get_autocast_gpu_dtype()
494
+ # Handle the case where the model is quantized
495
+ elif hasattr(self.config, "_pre_quantization_dtype"):
496
+ target_dtype = self.config._pre_quantization_dtype
497
+ else:
498
+ target_dtype = self.q_proj.weight.dtype
499
+
500
+ logger.warning_once(
501
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
502
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
503
+ f" {target_dtype}."
504
+ )
505
+
506
+ query_states = query_states.to(target_dtype)
507
+ key_states = key_states.to(target_dtype)
508
+ value_states = value_states.to(target_dtype)
509
+
510
+ # Reashape to the expected shape for Flash Attention
511
+ query_states = query_states.transpose(1, 2)
512
+ key_states = key_states.transpose(1, 2)
513
+ value_states = value_states.transpose(1, 2)
514
+
515
+ attn_output = self._flash_attention_forward(
516
+ query_states,
517
+ key_states,
518
+ value_states,
519
+ attention_mask,
520
+ q_len,
521
+ dropout=dropout_rate,
522
+ use_sliding_windows=use_sliding_windows,
523
+ )
524
+
525
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
526
+ attn_output = self.o_proj(attn_output)
527
+
528
+ if not output_attentions:
529
+ attn_weights = None
530
+
531
+ return attn_output, attn_weights, past_key_value
532
+
533
+ def _flash_attention_forward(
534
+ self,
535
+ query_states,
536
+ key_states,
537
+ value_states,
538
+ attention_mask,
539
+ query_length,
540
+ dropout=0.0,
541
+ softmax_scale=None,
542
+ use_sliding_windows=False,
543
+ ):
544
+ """
545
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
546
+ first unpad the input, then computes the attention scores and pad the final attention scores.
547
+
548
+ Args:
549
+ query_states (`torch.Tensor`):
550
+ Input query states to be passed to Flash Attention API
551
+ key_states (`torch.Tensor`):
552
+ Input key states to be passed to Flash Attention API
553
+ value_states (`torch.Tensor`):
554
+ Input value states to be passed to Flash Attention API
555
+ attention_mask (`torch.Tensor`):
556
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
557
+ position of padding tokens and 1 for the position of non-padding tokens.
558
+ dropout (`float`):
559
+ Attention dropout
560
+ softmax_scale (`float`, *optional*):
561
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
562
+ use_sliding_windows (`bool`, *optional*):
563
+ Whether to activate sliding window attention.
564
+ """
565
+ if not self._flash_attn_uses_top_left_mask:
566
+ causal = self.is_causal
567
+ else:
568
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
569
+ causal = self.is_causal and query_length != 1
570
+
571
+ # Decide whether to use SWA or not by layer index.
572
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
573
+ use_sliding_windows = False
574
+
575
+ # Contains at least one padding token in the sequence
576
+ if attention_mask is not None:
577
+ batch_size = query_states.shape[0]
578
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
579
+ query_states, key_states, value_states, attention_mask, query_length
580
+ )
581
+
582
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
583
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
584
+
585
+ if not use_sliding_windows:
586
+ attn_output_unpad = flash_attn_varlen_func(
587
+ query_states,
588
+ key_states,
589
+ value_states,
590
+ cu_seqlens_q=cu_seqlens_q,
591
+ cu_seqlens_k=cu_seqlens_k,
592
+ max_seqlen_q=max_seqlen_in_batch_q,
593
+ max_seqlen_k=max_seqlen_in_batch_k,
594
+ dropout_p=dropout,
595
+ softmax_scale=softmax_scale,
596
+ causal=causal,
597
+ )
598
+ else:
599
+ attn_output_unpad = flash_attn_varlen_func(
600
+ query_states,
601
+ key_states,
602
+ value_states,
603
+ cu_seqlens_q=cu_seqlens_q,
604
+ cu_seqlens_k=cu_seqlens_k,
605
+ max_seqlen_q=max_seqlen_in_batch_q,
606
+ max_seqlen_k=max_seqlen_in_batch_k,
607
+ dropout_p=dropout,
608
+ softmax_scale=softmax_scale,
609
+ causal=causal,
610
+ window_size=(self.config.sliding_window, self.config.sliding_window),
611
+ )
612
+
613
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
614
+ else:
615
+ if not use_sliding_windows:
616
+ attn_output = flash_attn_func(
617
+ query_states,
618
+ key_states,
619
+ value_states,
620
+ dropout,
621
+ softmax_scale=softmax_scale,
622
+ causal=causal,
623
+ )
624
+ else:
625
+ attn_output = flash_attn_func(
626
+ query_states,
627
+ key_states,
628
+ value_states,
629
+ dropout,
630
+ softmax_scale=softmax_scale,
631
+ causal=causal,
632
+ window_size=(self.config.sliding_window, self.config.sliding_window),
633
+ )
634
+
635
+ return attn_output
636
+
637
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
638
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
639
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
640
+
641
+ # On the first iteration we need to properly re-create the padding mask
642
+ # by slicing it on the proper place
643
+ if kv_seq_len != attention_mask.shape[-1]:
644
+ attention_mask_num_tokens = attention_mask.shape[-1]
645
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
646
+
647
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
648
+
649
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
650
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
651
+
652
+ if query_length == kv_seq_len:
653
+ query_layer = index_first_axis(
654
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
655
+ )
656
+ cu_seqlens_q = cu_seqlens_k
657
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
658
+ indices_q = indices_k
659
+ elif query_length == 1:
660
+ max_seqlen_in_batch_q = 1
661
+ cu_seqlens_q = torch.arange(
662
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
663
+ ) # There is a memcpy here, that is very bad.
664
+ indices_q = cu_seqlens_q[:-1]
665
+ query_layer = query_layer.squeeze(1)
666
+ else:
667
+ # The -q_len: slice assumes left padding.
668
+ attention_mask = attention_mask[:, -query_length:]
669
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
670
+
671
+ return (
672
+ query_layer,
673
+ key_layer,
674
+ value_layer,
675
+ indices_q,
676
+ (cu_seqlens_q, cu_seqlens_k),
677
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
678
+ )
679
+
680
+
681
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
682
+ class Qwen2SdpaAttention(Qwen2Attention):
683
+ """
684
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
685
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
686
+ SDPA API.
687
+ """
688
+
689
+ # Adapted from Qwen2Attention.forward
690
+ def forward(
691
+ self,
692
+ hidden_states: torch.Tensor,
693
+ attention_mask: Optional[torch.Tensor] = None,
694
+ position_ids: Optional[torch.LongTensor] = None,
695
+ past_key_value: Optional[Cache] = None,
696
+ output_attentions: bool = False,
697
+ use_cache: bool = False,
698
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
699
+ if output_attentions:
700
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
701
+ logger.warning_once(
702
+ "Qwen2Model is using Qwen2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
703
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
704
+ )
705
+ return super().forward(
706
+ hidden_states=hidden_states,
707
+ attention_mask=attention_mask,
708
+ position_ids=position_ids,
709
+ past_key_value=past_key_value,
710
+ output_attentions=output_attentions,
711
+ use_cache=use_cache,
712
+ )
713
+
714
+ bsz, q_len, _ = hidden_states.size()
715
+
716
+ query_states = self.q_proj(hidden_states)
717
+ key_states = self.k_proj(hidden_states)
718
+ value_states = self.v_proj(hidden_states)
719
+
720
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
721
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
722
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
723
+
724
+ kv_seq_len = key_states.shape[-2]
725
+ if past_key_value is not None:
726
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
727
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
728
+
729
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
730
+
731
+ if past_key_value is not None:
732
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
733
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
734
+
735
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
736
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
737
+
738
+ if attention_mask is not None:
739
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
740
+ raise ValueError(
741
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
742
+ )
743
+
744
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
745
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
746
+ if query_states.device.type == "cuda" and attention_mask is not None:
747
+ query_states = query_states.contiguous()
748
+ key_states = key_states.contiguous()
749
+ value_states = value_states.contiguous()
750
+
751
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
752
+ query_states,
753
+ key_states,
754
+ value_states,
755
+ attn_mask=attention_mask,
756
+ dropout_p=self.attention_dropout if self.training else 0.0,
757
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
758
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
759
+ )
760
+
761
+ attn_output = attn_output.transpose(1, 2).contiguous()
762
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
763
+
764
+ attn_output = self.o_proj(attn_output)
765
+
766
+ return attn_output, None, past_key_value
767
+
768
+
769
+ QWEN2_ATTENTION_CLASSES = {
770
+ "eager": Qwen2Attention,
771
+ "flash_attention_2": Qwen2FlashAttention2,
772
+ "sdpa": Qwen2SdpaAttention,
773
+ }
774
+
775
+
776
+ class Qwen2DecoderLayer(nn.Module):
777
+ def __init__(self, config: Qwen2Config, layer_idx: int):
778
+ super().__init__()
779
+ self.hidden_size = config.hidden_size
780
+
781
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
782
+ logger.warning_once(
783
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
784
+ "unexpected results may be encountered."
785
+ )
786
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
787
+
788
+ self.mlp = Qwen2MLP(config)
789
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
790
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
791
+
792
+ def forward(
793
+ self,
794
+ hidden_states: torch.Tensor,
795
+ attention_mask: Optional[torch.Tensor] = None,
796
+ position_ids: Optional[torch.LongTensor] = None,
797
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
798
+ output_attentions: Optional[bool] = False,
799
+ use_cache: Optional[bool] = False,
800
+ **kwargs,
801
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
802
+ if "padding_mask" in kwargs:
803
+ warnings.warn(
804
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
805
+ "Please make sure use `attention_mask` instead.`"
806
+ )
807
+ """
808
+ Args:
809
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
810
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
811
+ `(batch, sequence_length)` where padding elements are indicated by 0.
812
+ output_attentions (`bool`, *optional*):
813
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
814
+ returned tensors for more detail.
815
+ use_cache (`bool`, *optional*):
816
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
817
+ (see `past_key_values`).
818
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
819
+ """
820
+
821
+ residual = hidden_states
822
+
823
+ hidden_states = self.input_layernorm(hidden_states)
824
+
825
+ # Self Attention
826
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
827
+ hidden_states=hidden_states,
828
+ attention_mask=attention_mask,
829
+ position_ids=position_ids,
830
+ past_key_value=past_key_value,
831
+ output_attentions=output_attentions,
832
+ use_cache=use_cache,
833
+ )
834
+ hidden_states = residual + hidden_states
835
+
836
+ # Fully Connected
837
+ residual = hidden_states
838
+ hidden_states = self.post_attention_layernorm(hidden_states)
839
+ hidden_states = self.mlp(hidden_states)
840
+ hidden_states = residual + hidden_states
841
+
842
+ outputs = (hidden_states,)
843
+
844
+ if output_attentions:
845
+ outputs += (self_attn_weights,)
846
+
847
+ if use_cache:
848
+ outputs += (present_key_value,)
849
+
850
+ return outputs
851
+
852
+
853
+ QWEN2_START_DOCSTRING = r"""
854
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
855
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
856
+ etc.)
857
+
858
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
859
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
860
+ and behavior.
861
+
862
+ Parameters:
863
+ config ([`Qwen2Config`]):
864
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
865
+ load the weights associated with the model, only the configuration. Check out the
866
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
867
+ """
868
+
869
+
870
+ @add_start_docstrings(
871
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
872
+ QWEN2_START_DOCSTRING,
873
+ )
874
+ class Qwen2PreTrainedModel(PreTrainedModel):
875
+ config_class = Qwen2Config
876
+ base_model_prefix = "model"
877
+ supports_gradient_checkpointing = True
878
+ _no_split_modules = ["Qwen2DecoderLayer"]
879
+ _skip_keys_device_placement = "past_key_values"
880
+ _supports_flash_attn_2 = True
881
+ _supports_sdpa = True
882
+ _supports_cache_class = True
883
+
884
+ def _init_weights(self, module):
885
+ std = self.config.initializer_range
886
+ if isinstance(module, nn.Linear):
887
+ module.weight.data.normal_(mean=0.0, std=std)
888
+ if module.bias is not None:
889
+ module.bias.data.zero_()
890
+ elif isinstance(module, nn.Embedding):
891
+ module.weight.data.normal_(mean=0.0, std=std)
892
+ if module.padding_idx is not None:
893
+ module.weight.data[module.padding_idx].zero_()
894
+
895
+
896
+ QWEN2_INPUTS_DOCSTRING = r"""
897
+ Args:
898
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
899
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
900
+ it.
901
+
902
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
903
+ [`PreTrainedTokenizer.__call__`] for details.
904
+
905
+ [What are input IDs?](../glossary#input-ids)
906
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
907
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
908
+
909
+ - 1 for tokens that are **not masked**,
910
+ - 0 for tokens that are **masked**.
911
+
912
+ [What are attention masks?](../glossary#attention-mask)
913
+
914
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
915
+ [`PreTrainedTokenizer.__call__`] for details.
916
+
917
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
918
+ `past_key_values`).
919
+
920
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
921
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
922
+ information on the default strategy.
923
+
924
+ - 1 indicates the head is **not masked**,
925
+ - 0 indicates the head is **masked**.
926
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
927
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
928
+ config.n_positions - 1]`.
929
+
930
+ [What are position IDs?](../glossary#position-ids)
931
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
932
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
933
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
934
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
935
+
936
+ Two formats are allowed:
937
+ - a [`~cache_utils.Cache`] instance;
938
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
939
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
940
+ cache format.
941
+
942
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
943
+ legacy cache format will be returned.
944
+
945
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
946
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
947
+ of shape `(batch_size, sequence_length)`.
948
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
949
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
950
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
951
+ model's internal embedding lookup matrix.
952
+ use_cache (`bool`, *optional*):
953
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
954
+ `past_key_values`).
955
+ output_attentions (`bool`, *optional*):
956
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
957
+ tensors for more detail.
958
+ output_hidden_states (`bool`, *optional*):
959
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
960
+ more detail.
961
+ return_dict (`bool`, *optional*):
962
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
963
+ """
964
+
965
+
966
+ @add_start_docstrings(
967
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
968
+ QWEN2_START_DOCSTRING,
969
+ )
970
+ class Qwen2Model_Flash(Qwen2PreTrainedModel):
971
+ """
972
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
973
+
974
+ Args:
975
+ config: Qwen2Config
976
+ """
977
+
978
+ def __init__(self, config: Qwen2Config):
979
+ super().__init__(config)
980
+ self.padding_idx = config.pad_token_id
981
+ self.vocab_size = config.vocab_size
982
+
983
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
984
+ self.layers = nn.ModuleList(
985
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
986
+ )
987
+ self._attn_implementation = config._attn_implementation
988
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
989
+
990
+ self.gradient_checkpointing = False
991
+
992
+ # Initialize weights and apply final processing
993
+ self.post_init()
994
+
995
+ def get_input_embeddings(self):
996
+ return self.embed_tokens
997
+
998
+ def set_input_embeddings(self, value):
999
+ self.embed_tokens = value
1000
+
1001
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1002
+ def forward(
1003
+ self,
1004
+ input_ids: torch.LongTensor = None,
1005
+ attention_mask: Optional[torch.Tensor] = None,
1006
+ position_ids: Optional[torch.LongTensor] = None,
1007
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1008
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1009
+ use_cache: Optional[bool] = None,
1010
+ output_attentions: Optional[bool] = None,
1011
+ output_hidden_states: Optional[bool] = None,
1012
+ return_dict: Optional[bool] = None,
1013
+ labels: Optional[torch.Tensor] = None,
1014
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1015
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1016
+ output_hidden_states = (
1017
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1018
+ )
1019
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1020
+
1021
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1022
+
1023
+ # retrieve input_ids and inputs_embeds
1024
+ if input_ids is not None and inputs_embeds is not None:
1025
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1026
+ elif input_ids is not None and input_ids.numel() != 0:
1027
+ batch_size, seq_length = input_ids.shape
1028
+ elif inputs_embeds is not None:
1029
+ batch_size, seq_length, _ = inputs_embeds.shape
1030
+ else:
1031
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1032
+
1033
+ if self.gradient_checkpointing and self.training:
1034
+ if use_cache:
1035
+ logger.warning_once(
1036
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1037
+ )
1038
+ use_cache = False
1039
+
1040
+ past_key_values_length = 0
1041
+
1042
+ if use_cache:
1043
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1044
+ if use_legacy_cache:
1045
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1046
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1047
+
1048
+ if position_ids is None:
1049
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1050
+ position_ids = torch.arange(
1051
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1052
+ )
1053
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1054
+ else:
1055
+ position_ids = position_ids.view(-1, seq_length).long()
1056
+
1057
+ if inputs_embeds is None:
1058
+ inputs_embeds = self.embed_tokens(input_ids)
1059
+
1060
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1061
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1062
+ if is_padding_right:
1063
+ raise ValueError(
1064
+ "You are attempting to perform batched generation with padding_side='right'"
1065
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
1066
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1067
+ )
1068
+
1069
+ if self._attn_implementation == "flash_attention_2":
1070
+ # 2d mask is passed through the layers
1071
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1072
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1073
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1074
+ # the manual implementation that requires a 4D causal mask in all cases.
1075
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1076
+ attention_mask,
1077
+ (batch_size, seq_length),
1078
+ inputs_embeds,
1079
+ past_key_values_length,
1080
+ sliding_window=self.config.sliding_window,
1081
+ )
1082
+ else:
1083
+ # 4d mask is passed through the layers
1084
+ attention_mask = _prepare_4d_causal_attention_mask(
1085
+ attention_mask,
1086
+ (batch_size, seq_length),
1087
+ inputs_embeds,
1088
+ past_key_values_length,
1089
+ sliding_window=self.config.sliding_window,
1090
+ )
1091
+
1092
+ hidden_states = inputs_embeds
1093
+
1094
+ # decoder layers
1095
+ all_hidden_states = () if output_hidden_states else None
1096
+ all_self_attns = () if output_attentions else None
1097
+ next_decoder_cache = None
1098
+
1099
+ for layer_idx, decoder_layer in enumerate(self.layers):
1100
+ if output_hidden_states:
1101
+ all_hidden_states += (hidden_states,)
1102
+
1103
+ if self.gradient_checkpointing and self.training:
1104
+ layer_outputs = self._gradient_checkpointing_func(
1105
+ decoder_layer.__call__,
1106
+ hidden_states,
1107
+ attention_mask,
1108
+ position_ids,
1109
+ past_key_values,
1110
+ output_attentions,
1111
+ use_cache,
1112
+ )
1113
+ else:
1114
+ layer_outputs = decoder_layer(
1115
+ hidden_states,
1116
+ attention_mask=attention_mask,
1117
+ position_ids=position_ids,
1118
+ past_key_value=past_key_values,
1119
+ output_attentions=output_attentions,
1120
+ use_cache=use_cache,
1121
+ )
1122
+
1123
+ hidden_states = layer_outputs[0]
1124
+
1125
+ if use_cache:
1126
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1127
+
1128
+ if output_attentions:
1129
+ all_self_attns += (layer_outputs[1],)
1130
+
1131
+ ###### copy from pdrop #########
1132
+ # rank & drop after specific layer
1133
+ # only drop in prefill stage when inference
1134
+ rank_layer = layer_idx+1
1135
+ if rank_layer in self.llm_compress_layer_list:
1136
+ if hidden_states.shape[1] != 1: # prefill stage or training
1137
+ stage = self.llm_compress_layer_list.index(rank_layer) # determine current stage
1138
+ (
1139
+ position_ids,
1140
+ attention_mask,
1141
+ hidden_states,
1142
+ labels # update labels and return
1143
+ ) = self.video_level_compress(
1144
+ cur_num = stage,
1145
+ rank_layer = rank_layer,
1146
+ features = hidden_states,
1147
+ position_ids=position_ids,
1148
+ attention_mask=attention_mask,
1149
+ labels = labels
1150
+ )
1151
+
1152
+ # process attention_mask again after updating
1153
+ if self._attn_implementation == "flash_attention_2":
1154
+ # 2d mask is passed through the layers
1155
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1156
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1157
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1158
+ # the manual implementation that requires a 4D causal mask in all cases.
1159
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1160
+ attention_mask,
1161
+ (batch_size, hidden_states.shape[1]),
1162
+ hidden_states,
1163
+ past_key_values_length,
1164
+ )
1165
+ else:
1166
+ # 4d mask is passed through the layers
1167
+ attention_mask = _prepare_4d_causal_attention_mask(
1168
+ attention_mask,
1169
+ (batch_size, hidden_states.shape[1]),
1170
+ hidden_states,
1171
+ past_key_values_length,
1172
+ sliding_window=self.config.sliding_window,
1173
+ )
1174
+
1175
+ else:
1176
+ # update position_ids in decoding stage when inference
1177
+ stage = self.llm_compress_layer_list.index(rank_layer) # determine current stage
1178
+ cur_visual_length = [int(cur_image_token * self.llm_image_token_ratio_list[stage]) for cur_image_token in self.num_image_token_lens]
1179
+ next_visual_length = [int(cur_image_token * self.llm_image_token_ratio_list[stage + 1]) for cur_image_token in self.num_image_token_lens]
1180
+ new_position_ids = []
1181
+ for idx, cur_position_ids in enumerate(position_ids):
1182
+ cur_position_ids = cur_position_ids - (cur_visual_length[idx] - next_visual_length[idx])
1183
+ new_position_ids.append(cur_position_ids)
1184
+ assert idx == 0, idx
1185
+ position_ids = torch.tensor(new_position_ids, dtype=torch.long).unsqueeze(0)
1186
+
1187
+ #################
1188
+
1189
+ hidden_states = self.norm(hidden_states)
1190
+
1191
+ # add hidden states from the last decoder layer
1192
+ if output_hidden_states:
1193
+ all_hidden_states += (hidden_states,)
1194
+
1195
+ next_cache = None
1196
+ if use_cache:
1197
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1198
+
1199
+ if not return_dict:
1200
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None), labels
1201
+ return BaseModelOutputWithPast(
1202
+ last_hidden_state=hidden_states,
1203
+ past_key_values=next_cache,
1204
+ hidden_states=all_hidden_states,
1205
+ attentions=all_self_attns,
1206
+ ), labels
1207
+
1208
+
1209
+ # implementation of pdrop
1210
+ def video_level_compress(
1211
+ self, cur_num, rank_layer, features ,
1212
+ position_ids, attention_mask, labels
1213
+ ):
1214
+
1215
+ if self.llm_compress_type == 'uniform0_attention':
1216
+ if cur_num == 0:
1217
+ llm_compress_type = 'uniform'
1218
+ else:
1219
+ llm_compress_type = 'attention'
1220
+ else:
1221
+ llm_compress_type = self.llm_compress_type
1222
+
1223
+ _labels = labels
1224
+ _position_ids = position_ids
1225
+ _attention_mask = attention_mask
1226
+
1227
+ if position_ids is None:
1228
+ position_ids = torch.arange(0, features.shape[1], dtype=torch.long, device=features.device).unsqueeze(0)
1229
+
1230
+ if getattr(self.config, 'tokenizer_padding_side', 'right') == "right":
1231
+
1232
+ batch_size = features.shape[0]
1233
+ image_tokens = [int(cur_image_token * self.llm_image_token_ratio_list[cur_num]) for cur_image_token in self.num_image_token_lens]
1234
+ keep_length = [int(cur_image_token * self.llm_image_token_ratio_list[cur_num + 1]) for cur_image_token in self.num_image_token_lens]
1235
+
1236
+ features_list = []
1237
+ attention_mask_list = []
1238
+ labels_list = []
1239
+
1240
+ if attention_mask is None:
1241
+ attention_mask = torch.ones((batch_size,features.shape[1]), dtype=torch.bool, device=features.device)
1242
+ else:
1243
+ attention_mask = attention_mask.bool()
1244
+ if labels is None:
1245
+ labels = torch.full((batch_size,features.shape[1]), IGNORE_INDEX, device=features.device)
1246
+
1247
+
1248
+ if 'attention' in llm_compress_type:
1249
+ # obtain query_states and key_states to calculate attention map
1250
+ hidden_states= features.clone().detach()
1251
+
1252
+ self_attn = self.layers[rank_layer].self_attn
1253
+ hidden_states = self.layers[rank_layer].input_layernorm(hidden_states)
1254
+
1255
+ num_heads = self_attn.num_heads
1256
+ num_key_value_heads = self_attn.num_key_value_heads
1257
+ head_dim = self_attn.head_dim
1258
+
1259
+ bsz, q_len, _ = hidden_states.size()
1260
+
1261
+ query_states = self_attn.q_proj(hidden_states)
1262
+ key_states = self_attn.k_proj(hidden_states)
1263
+ value_states = self_attn.v_proj(hidden_states)
1264
+
1265
+ query_states = query_states.view(bsz, q_len, num_heads, head_dim).transpose(1, 2)
1266
+ key_states = key_states.view(bsz, q_len, num_key_value_heads, head_dim).transpose(1, 2)
1267
+ value_states = value_states.view(bsz, q_len, num_key_value_heads, head_dim).transpose(1, 2)
1268
+
1269
+ kv_seq_len = key_states.shape[-2]
1270
+ cos, sin = self_attn.rotary_emb(value_states, seq_len=kv_seq_len)
1271
+
1272
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
1273
+ key_states = repeat_kv(key_states, self_attn.num_key_value_groups)
1274
+
1275
+ # attention_mask
1276
+ eager_attention_mask = _prepare_4d_causal_attention_mask(
1277
+ attention_mask, (batch_size, q_len), hidden_states, past_key_values_length=0
1278
+ ).to(device=query_states.device)
1279
+
1280
+ # take valid features
1281
+ features = [cur_features[cur_attention_mask] for cur_features, cur_attention_mask in zip(features, attention_mask)]
1282
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
1283
+ attention_mask = [cur_attention_mask[cur_attention_mask] for cur_attention_mask, cur_attention_mask in zip(attention_mask, attention_mask)]
1284
+
1285
+ # rank & drop
1286
+ for i in range(batch_size):
1287
+ image_index = self.first_image_token_position[i]
1288
+ if image_index == -1:
1289
+ cur_input_embeds = features[i]
1290
+ features_list.append(cur_input_embeds)
1291
+ attention_mask_list.append(attention_mask[i])
1292
+ labels_list.append(labels[i])
1293
+ continue
1294
+
1295
+ if 'attention' in llm_compress_type:
1296
+
1297
+ # obtain current states
1298
+ cur_key_states = key_states[i]
1299
+ cur_query_states = query_states[i]
1300
+ cur_eager_attention_mask = eager_attention_mask[i]
1301
+
1302
+ # choose last instruction token as query
1303
+ if self.training:
1304
+ answer_index = torch.where(labels[i] != -100)[0].tolist()
1305
+ index_before_answer = []
1306
+ for index in answer_index:
1307
+ if labels[i][index-1] == -100:
1308
+ index_before_answer.append(index-1)
1309
+ if index_before_answer == []:
1310
+ cur_input_embeds = features[i]
1311
+ features_list.append(cur_input_embeds)
1312
+ attention_mask_list.append(attention_mask[i])
1313
+ labels_list.append(labels[i])
1314
+ continue
1315
+
1316
+ index_before_answer=torch.tensor(index_before_answer,device=labels[0].device)
1317
+ text_query_states = cur_query_states[:,index_before_answer,:]
1318
+ text_eager_attention_mask = cur_eager_attention_mask[:,index_before_answer,:]
1319
+
1320
+ else:
1321
+ prompt_total_len = self.text_prompt_lens[i] + image_tokens[i]
1322
+ text_query_states = cur_query_states[:,prompt_total_len-1,:].unsqueeze(1)
1323
+ text_eager_attention_mask = cur_eager_attention_mask[:,prompt_total_len-1,:].unsqueeze(1)
1324
+
1325
+ # calculate attention map
1326
+ attn_weights = torch.matmul(text_query_states, cur_key_states.transpose(1, 2)) / math.sqrt(head_dim) #(num_head, text_token,seq_len)
1327
+ attn_weights = attn_weights + text_eager_attention_mask
1328
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) #(num_head, text_token,seq_len)
1329
+
1330
+ attention_avg_head = torch.mean(attn_weights, dim=0) # ave across heads
1331
+ attention_avg_head = attention_avg_head[:,image_index:image_index+image_tokens[i]] # select image token as keys
1332
+ attention_avg_text = torch.mean(attention_avg_head, dim=0) # (576)
1333
+
1334
+ if llm_compress_type == 'attention':
1335
+ top_rank_index = attention_avg_text.topk(keep_length[i]).indices
1336
+ else:
1337
+ raise NotImplementedError(llm_compress_type)
1338
+
1339
+ elif llm_compress_type == 'uniform':
1340
+ top_rank_index = torch.linspace(0, image_tokens[i]-1, keep_length[i], dtype=torch.long)
1341
+ else:
1342
+ raise NotImplementedError(llm_compress_type)
1343
+
1344
+ top_rank_index = top_rank_index + image_index
1345
+ top_rank_index= top_rank_index.sort().values
1346
+
1347
+ start_index = image_index + image_tokens[i]
1348
+ new_input_embeds = torch.cat([features[i][ :image_index, :] ,features[i][ top_rank_index, :], features[i][start_index:, :]], dim=0)
1349
+
1350
+ new_labels = torch.cat([labels[i][ :image_index],labels[i][ top_rank_index], labels[i][start_index:]], dim=0)
1351
+ new_attention_mask = torch.cat([attention_mask[i][:image_index], attention_mask[i][top_rank_index], attention_mask[i][start_index:]], dim=0)
1352
+
1353
+ features_list.append(new_input_embeds)
1354
+ attention_mask_list.append(new_attention_mask)
1355
+ labels_list.append(new_labels)
1356
+
1357
+ # Truncate sequences to max length as image embeddings can make the sequence longer
1358
+ tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None)
1359
+ if tokenizer_model_max_length is not None:
1360
+ new_input_embeds = [x[:tokenizer_model_max_length] for x in features_list]
1361
+ new_attention_mask = [x[:tokenizer_model_max_length] for x in attention_mask_list]
1362
+ new_labels = [x[:tokenizer_model_max_length] for x in labels_list]
1363
+
1364
+ max_len = max(x.shape[0] for x in new_input_embeds)
1365
+
1366
+ # padding the sequences to form batch
1367
+ embeds_padded=[]
1368
+ labels_paded=[]
1369
+ attention_mask_padded=[]
1370
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
1371
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
1372
+ cur_len_emb=cur_new_embed.shape[0]
1373
+ dif=max_len - cur_len_emb # padding to longest seq
1374
+
1375
+ cur_new_embed = torch.cat([cur_new_embed,torch.zeros((dif, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)],dim=0)
1376
+ cur_new_labels = torch.cat([cur_new_labels,torch.full((dif,),IGNORE_INDEX,dtype=cur_new_labels.dtype, device=cur_new_labels.device)],dim=0)
1377
+ cur_attention_mask = new_attention_mask[i]
1378
+ cur_attention_mask = torch.cat([cur_attention_mask,torch.full((dif,),False, dtype=cur_attention_mask.dtype, device=cur_attention_mask.device)],dim=0)
1379
+
1380
+ embeds_padded.append(cur_new_embed)
1381
+ labels_paded.append(cur_new_labels)
1382
+ attention_mask_padded.append(cur_attention_mask)
1383
+
1384
+ cur_len = new_attention_mask[i].sum().item()
1385
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
1386
+
1387
+
1388
+ new_input_embeds = torch.stack(embeds_padded,dim=0)
1389
+ new_input_embeds = new_input_embeds.to(features[0].dtype)
1390
+
1391
+ new_attention_mask = torch.stack(attention_mask_padded,dim=0)
1392
+ new_labels = torch.stack(labels_paded,dim=0)
1393
+
1394
+ if _position_ids is None:
1395
+ position_ids = None
1396
+ if _labels is None:
1397
+ new_labels = None
1398
+
1399
+ if _attention_mask is None:
1400
+ new_attention_mask = None
1401
+ else:
1402
+ new_attention_mask = new_attention_mask.to(dtype=_attention_mask.dtype)
1403
+
1404
+ return position_ids, new_attention_mask, new_input_embeds, new_labels
1405
+
1406
+ else:
1407
+ raise ValueError(f"Unexpected tokenizer_padding_side: {self.config.tokenizer_padding_side}")
1408
+
1409
+
1410
+ class Qwen2ForCausalLM_Flash(Qwen2PreTrainedModel):
1411
+ _tied_weights_keys = ["lm_head.weight"]
1412
+
1413
+ def __init__(self, config):
1414
+ super().__init__(config)
1415
+ self.model = Qwen2Model_Flash(config)
1416
+ self.vocab_size = config.vocab_size
1417
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1418
+
1419
+ # Initialize weights and apply final processing
1420
+ self.post_init()
1421
+
1422
+ def get_input_embeddings(self):
1423
+ return self.model.embed_tokens
1424
+
1425
+ def set_input_embeddings(self, value):
1426
+ self.model.embed_tokens = value
1427
+
1428
+ def get_output_embeddings(self):
1429
+ return self.lm_head
1430
+
1431
+ def set_output_embeddings(self, new_embeddings):
1432
+ self.lm_head = new_embeddings
1433
+
1434
+ def set_decoder(self, decoder):
1435
+ self.model = decoder
1436
+
1437
+ def get_decoder(self):
1438
+ return self.model
1439
+
1440
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1441
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1442
+ def forward(
1443
+ self,
1444
+ input_ids: torch.LongTensor = None,
1445
+ attention_mask: Optional[torch.Tensor] = None,
1446
+ position_ids: Optional[torch.LongTensor] = None,
1447
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1448
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1449
+ labels: Optional[torch.LongTensor] = None,
1450
+ use_cache: Optional[bool] = None,
1451
+ output_attentions: Optional[bool] = None,
1452
+ output_hidden_states: Optional[bool] = None,
1453
+ return_dict: Optional[bool] = None,
1454
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1455
+ r"""
1456
+ Args:
1457
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1458
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1459
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1460
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1461
+
1462
+ Returns:
1463
+
1464
+ Example:
1465
+
1466
+ ```python
1467
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1468
+
1469
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1470
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1471
+
1472
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1473
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1474
+
1475
+ >>> # Generate
1476
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1477
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1478
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1479
+ ```"""
1480
+
1481
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1482
+ output_hidden_states = (
1483
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1484
+ )
1485
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1486
+
1487
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1488
+ outputs, labels = self.model(
1489
+ input_ids=input_ids,
1490
+ attention_mask=attention_mask,
1491
+ position_ids=position_ids,
1492
+ past_key_values=past_key_values,
1493
+ inputs_embeds=inputs_embeds,
1494
+ use_cache=use_cache,
1495
+ output_attentions=output_attentions,
1496
+ output_hidden_states=output_hidden_states,
1497
+ return_dict=return_dict,
1498
+ labels=labels
1499
+ )
1500
+
1501
+ hidden_states = outputs[0]
1502
+ logits = self.lm_head(hidden_states)
1503
+ logits = logits.float()
1504
+
1505
+ loss = None
1506
+ if labels is not None:
1507
+ # Shift so that tokens < n predict n
1508
+ shift_logits = logits[..., :-1, :].contiguous()
1509
+ shift_labels = labels[..., 1:].contiguous()
1510
+ # Flatten the tokens
1511
+ loss_fct = CrossEntropyLoss()
1512
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1513
+ shift_labels = shift_labels.view(-1)
1514
+ # Enable model parallelism
1515
+ shift_labels = shift_labels.to(shift_logits.device)
1516
+ loss = loss_fct(shift_logits, shift_labels)
1517
+
1518
+ if not return_dict:
1519
+ output = (logits,) + outputs[1:]
1520
+ return (loss,) + output if loss is not None else output
1521
+
1522
+ return CausalLMOutputWithPast(
1523
+ loss=loss,
1524
+ logits=logits,
1525
+ past_key_values=outputs.past_key_values,
1526
+ hidden_states=outputs.hidden_states,
1527
+ attentions=outputs.attentions,
1528
+ )
1529
+
1530
+ def prepare_inputs_for_generation(
1531
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1532
+ ):
1533
+ # Omit tokens covered by past_key_values
1534
+ if past_key_values is not None:
1535
+ if isinstance(past_key_values, Cache):
1536
+ cache_length = past_key_values.get_seq_length()
1537
+ past_length = past_key_values.seen_tokens
1538
+ max_cache_length = past_key_values.get_max_length()
1539
+ else:
1540
+ cache_length = past_length = past_key_values[0][0].shape[2]
1541
+ max_cache_length = None
1542
+
1543
+ # Keep only the unprocessed tokens:
1544
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1545
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1546
+ # input)
1547
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1548
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1549
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1550
+ # input_ids based on the past_length.
1551
+ elif past_length < input_ids.shape[1]:
1552
+ input_ids = input_ids[:, past_length:]
1553
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1554
+
1555
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1556
+ if (
1557
+ max_cache_length is not None
1558
+ and attention_mask is not None
1559
+ and cache_length + input_ids.shape[1] > max_cache_length
1560
+ ):
1561
+ attention_mask = attention_mask[:, -max_cache_length:]
1562
+
1563
+ position_ids = kwargs.get("position_ids", None)
1564
+ if attention_mask is not None and position_ids is None:
1565
+ # create position_ids on the fly for batch generation
1566
+ position_ids = attention_mask.long().cumsum(-1) - 1
1567
+ position_ids.masked_fill_(attention_mask == 0, 1)
1568
+ if past_key_values:
1569
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1570
+
1571
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1572
+ if inputs_embeds is not None and past_key_values.get_seq_length() == 0:
1573
+ model_inputs = {"inputs_embeds": inputs_embeds}
1574
+ else:
1575
+ model_inputs = {"input_ids": input_ids}
1576
+
1577
+ model_inputs.update(
1578
+ {
1579
+ "position_ids": position_ids,
1580
+ "past_key_values": past_key_values,
1581
+ "use_cache": kwargs.get("use_cache"),
1582
+ "attention_mask": attention_mask,
1583
+ }
1584
+ )
1585
+ return model_inputs
1586
+
1587
+ @staticmethod
1588
+ def _reorder_cache(past_key_values, beam_idx):
1589
+ reordered_past = ()
1590
+ for layer_past in past_key_values:
1591
+ reordered_past += (
1592
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1593
+ )
1594
+ return reordered_past
1595
+
1596
+
modeling_videochat_flash.py ADDED
@@ -0,0 +1,727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from abc import ABC, abstractmethod
16
+ import re
17
+ import torch
18
+ import numpy as np
19
+ import torch.nn as nn
20
+ import random
21
+ from typing import List, Optional, Tuple, Union, Dict
22
+
23
+ from transformers import AutoConfig, AutoModelForCausalLM
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+ from transformers.generation.utils import GenerateOutput
26
+ from transformers import Qwen2Config
27
+
28
+ from .vision_tower_builder import build_vision_tower
29
+ from .mm_projector_builder import build_vision_projector
30
+
31
+ from .constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_IMAGE_TOKEN
32
+ from .conversation import conv_templates, SeparatorStyle
33
+ from .mm_utils import tokenizer_image_token, KeywordsStoppingCriteria, get_anyres_image_grid_shape, load_video
34
+ from .modeling_qwen2_flash import Qwen2Model_Flash, Qwen2ForCausalLM_Flash
35
+
36
+
37
+ class LlavaMetaModel:
38
+
39
+ def __init__(self, config):
40
+ super(LlavaMetaModel, self).__init__(config)
41
+
42
+ if hasattr(config, "mm_vision_tower"):
43
+ delay_load = getattr(config, "delay_load", False)
44
+ self.vision_tower = build_vision_tower(config, delay_load=delay_load)
45
+ self.mm_projector = build_vision_projector(config, vision_cfg=self.vision_tower.config)
46
+
47
+ if "unpad" in getattr(config, "mm_patch_merge_type", ""):
48
+ self.image_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
49
+ if "nopad" in getattr(config, "mm_patch_merge_type", "") and getattr(self.config, "mm_newline_position", "nothing") != "nothing":
50
+ self.frame_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
51
+
52
+ def get_vision_tower(self):
53
+ vision_tower = getattr(self, "vision_tower", None)
54
+ if type(vision_tower) is list:
55
+ vision_tower = vision_tower[0]
56
+ return vision_tower
57
+
58
+ def initialize_vision_modules(self, model_args, fsdp=None):
59
+ vision_tower = model_args.vision_tower
60
+ mm_vision_select_layer = model_args.mm_vision_select_layer
61
+ mm_vision_select_feature = model_args.mm_vision_select_feature
62
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
63
+ mm_patch_merge_type = model_args.mm_patch_merge_type
64
+
65
+ self.config.mm_vision_tower = vision_tower
66
+ self.config.vision_tower_pretrained = getattr(model_args, "vision_tower_pretrained", "")
67
+
68
+ if self.get_vision_tower() is None:
69
+ vision_tower = build_vision_tower(model_args)
70
+
71
+ if fsdp is not None and len(fsdp) > 0:
72
+ self.vision_tower = [vision_tower]
73
+ else:
74
+ self.vision_tower = vision_tower
75
+ else:
76
+ if fsdp is not None and len(fsdp) > 0:
77
+ vision_tower = self.vision_tower[0]
78
+ else:
79
+ vision_tower = self.vision_tower
80
+ vision_tower.load_model()
81
+
82
+
83
+
84
+ self.config.use_mm_proj = True
85
+ self.config.mm_projector_type = getattr(model_args, "mm_projector_type", "linear")
86
+ self.config.mm_vision_select_layer = mm_vision_select_layer
87
+ self.config.mm_vision_select_feature = mm_vision_select_feature
88
+ self.config.mm_patch_merge_type = mm_patch_merge_type
89
+
90
+ if getattr(self, "mm_projector", None) is None:
91
+ self.mm_projector = build_vision_projector(self.config, vision_cfg=vision_tower.config)
92
+
93
+ if "unpad" in mm_patch_merge_type:
94
+ embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
95
+ self.image_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
96
+ if "nopad" in getattr(self.config, "mm_patch_merge_type", "") and getattr(self.config, "mm_newline_position", "nothing") != "nothing":
97
+ embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
98
+ self.frame_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
99
+ else:
100
+ # In case it is frozen by LoRA
101
+ for p in self.mm_projector.parameters():
102
+ p.requires_grad = True
103
+
104
+ if pretrain_mm_mlp_adapter is not None:
105
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location="cpu")
106
+
107
+ def get_w(weights, keyword):
108
+ return {k.split(keyword + ".")[1]: v for k, v in weights.items() if keyword in k}
109
+
110
+ if self.config.mm_projector_type =='lxh_qformer':
111
+ incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"), strict=False)
112
+ else:
113
+ incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"))
114
+ print(f"Loaded mm projector weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}")
115
+
116
+
117
+ class LlavaMetaForCausalLM(ABC):
118
+
119
+ @abstractmethod
120
+ def get_model(self):
121
+ pass
122
+
123
+ def get_vision_tower(self):
124
+ return self.get_model().get_vision_tower()
125
+
126
+
127
+ def encode_video_image(self, images_list, video_idx_in_batch):
128
+ # video encoder编码后按图像的connector处理
129
+ bs = len(images_list)
130
+
131
+ concat_images = []
132
+ concat_videos = []
133
+ for idx, image in enumerate(images_list):
134
+ if idx in video_idx_in_batch:
135
+ concat_videos.append(image)
136
+ else:
137
+ concat_images.append(image)
138
+ # print(concat_videos[0].shape)
139
+ has_image = len(concat_images) > 0
140
+ has_video = len(concat_videos) > 0
141
+
142
+ mm_local_num_frames = getattr(self.config, "mm_local_num_frames", -1)
143
+ assert mm_local_num_frames != -1
144
+ if has_image:
145
+ image_split_sizes = [image.shape[0] for image in concat_images]
146
+ concat_images = torch.cat([image.unsqueeze(1) for image in concat_images], dim=0)
147
+ # print("input vit image.shape:", concat_images.shape)
148
+ images_features = self.get_model().get_vision_tower()(concat_images) # B_i, N, D
149
+ images_features = torch.split(images_features, image_split_sizes)
150
+
151
+ if has_video:
152
+ video_split_sizes = [video.shape[0] // mm_local_num_frames for video in concat_videos]
153
+ concat_videos = torch.cat([video.reshape(video.shape[0] // mm_local_num_frames, mm_local_num_frames, video.shape[1], video.shape[2], video.shape[3]) for video in concat_videos], dim=0)
154
+ # print("input vit video.shape:", concat_videos.shape)
155
+ videos_features = self.get_model().get_vision_tower()(concat_videos) # B_v, N, D
156
+ videos_features = [v.reshape(-1, v.shape[-2] // mm_local_num_frames, v.shape[-1]) for v in torch.split(videos_features, video_split_sizes)]
157
+
158
+
159
+ all_videos_or_images_features = []
160
+ img_idx = 0
161
+ vid_idx = 0
162
+
163
+ for idx in range(bs):
164
+
165
+ if idx in video_idx_in_batch:
166
+ feat = self.get_model().mm_projector(videos_features[vid_idx], compress=True, local_num_frames=getattr(self.config, "mm_local_num_frames", -1))
167
+
168
+ vid_idx += 1
169
+ else:
170
+ feat = self.get_model().mm_projector(images_features[img_idx], compress=False)
171
+ img_idx += 1
172
+ # print("video_idx_in_batch:", video_idx_in_batch)
173
+ all_videos_or_images_features.append(feat)
174
+
175
+ if has_video:
176
+ assert vid_idx == len(videos_features), f"vid: {vid_idx} != {len(videos_features)}"
177
+ if has_image:
178
+ assert img_idx == len(images_features), f"img: {img_idx} != {len(images_features)}"
179
+
180
+ return all_videos_or_images_features
181
+
182
+
183
+
184
+ def prepare_inputs_labels_for_multimodal(self, input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities=["image"], image_sizes=None):
185
+ assert type(modalities) is list, modalities
186
+
187
+ vision_tower = self.get_vision_tower()
188
+ # rank_print(modalities)
189
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
190
+ return input_ids, position_ids, attention_mask, past_key_values, None, labels
191
+
192
+ if type(images) is list or images.ndim == 5:
193
+ if type(images) is list:
194
+ images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]
195
+
196
+ video_idx_in_batch = []
197
+ for _ in range(len(modalities)):
198
+ if modalities[_] == "video":
199
+ video_idx_in_batch.append(_)
200
+
201
+ images_list = []
202
+ for image in images:
203
+ if image.ndim == 4:
204
+ images_list.append(image)
205
+ else:
206
+ images_list.append(image.unsqueeze(0))
207
+
208
+
209
+ vision_encode_type = getattr(self.config, "vision_encode_type", "image")
210
+ mm_patch_merge_type = getattr(self.config, "mm_patch_merge_type", "flat")
211
+ image_aspect_ratio = getattr(self.config, "image_aspect_ratio", "square")
212
+ frame_aspect_ratio = getattr(self.config, "frame_aspect_ratio", "square")
213
+ mm_newline_position = getattr(self.config, "mm_newline_position", "nothing")
214
+
215
+
216
+ if vision_encode_type == "video_image": # video backbone, process video with compress
217
+ image_features = self.encode_video_image(images_list, video_idx_in_batch=video_idx_in_batch)
218
+ else:
219
+ raise NotImplementedError(vision_encode_type)
220
+
221
+ frame_start_indices = [i*image_features[0].size(1) for i in range(len(image_features[0]))]
222
+ if mm_patch_merge_type == "flat":
223
+ image_features = [x.flatten(0, 1) for x in image_features]
224
+ elif mm_patch_merge_type.startswith("spatial"):
225
+ new_image_features = []
226
+ for image_idx, image_feature in enumerate(image_features):
227
+
228
+ if image_idx in video_idx_in_batch: # video operations
229
+
230
+ if "anyres" in frame_aspect_ratio:
231
+ raise NotImplementedError
232
+ else:
233
+ frame_feature = image_feature
234
+
235
+ if "pad" in mm_patch_merge_type:
236
+ if mm_newline_position == 'one_token':
237
+ frame_feature = frame_feature.flatten(0, 1)
238
+ if "unpad" in mm_patch_merge_type:
239
+ frame_feature = torch.cat((frame_feature, self.model.image_newline[None].to(frame_feature.device)), dim=0)
240
+ else:
241
+ frame_feature = torch.cat((frame_feature, self.model.frame_newline[None].to(frame_feature.device)), dim=0)
242
+ elif mm_newline_position == 'nothing':
243
+ frame_feature = frame_feature.flatten(0, 1)
244
+ else:
245
+ raise NotImplementedError("add pad please!!")
246
+ else:
247
+ frame_feature = frame_feature.flatten(0, 1)
248
+
249
+ # print(f"final video frame_feature.shape: {frame_feature.shape}")
250
+ image_feature = frame_feature
251
+
252
+ elif image_feature.shape[0] > 1: # multi patches and multi images operations
253
+ base_image_feature = image_feature[0]
254
+ image_feature = image_feature[1:]
255
+ origin_size = image_feature.shape
256
+
257
+ height = width = self.get_model().mm_projector.num_image_patches_per_side
258
+ assert height * width == base_image_feature.shape[0], f"height:{height}, width: {width}, base_image_feature: {base_image_feature.shape}"
259
+
260
+ if "anyres_max" in image_aspect_ratio:
261
+ matched_anyres_max_num_patches = re.match(r"anyres_max_(\d+)", image_aspect_ratio)
262
+ if matched_anyres_max_num_patches:
263
+ max_num_patches = int(matched_anyres_max_num_patches.group(1))
264
+
265
+ if "anyres" in image_aspect_ratio:
266
+ if hasattr(self.get_vision_tower(), "image_size"):
267
+ vision_tower_image_size = self.get_vision_tower().image_size
268
+ else:
269
+ raise ValueError("vision_tower_image_size is not found in the vision tower.")
270
+ try:
271
+ num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, vision_tower_image_size, max_resolutions=None)
272
+ except Exception as e:
273
+ print(f"Error: {e}")
274
+ raise e
275
+ # num_patch_width, num_patch_height = 2, 2
276
+
277
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
278
+ else:
279
+ raise NotImplementedError(image_aspect_ratio)
280
+ image_feature = image_feature.view(2, 2, height, width, -1)
281
+
282
+ if "maxpool2x2" in mm_patch_merge_type:
283
+ raise NotImplementedError
284
+ elif "unpad" in mm_patch_merge_type and "anyres_max" in image_aspect_ratio and matched_anyres_max_num_patches:
285
+ raise NotImplementedError
286
+ elif "unpad" in mm_patch_merge_type:
287
+ raise NotImplementedError
288
+ else:
289
+ image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
290
+ image_feature = image_feature.flatten(0, 3)
291
+ if "nobase" in mm_patch_merge_type:
292
+ pass
293
+ else:
294
+ try:
295
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
296
+ except Exception as e:
297
+ raise ValueError(f"{num_patch_width} {num_patch_height} now: base_image_feature: {base_image_feature.shape}, {image_feature.shape}, image_sizes[image_idx]: {image_sizes[image_idx]}, origin_size: {origin_size}, {image_sizes[image_idx]}, {self.config.image_grid_pinpoints}, {vision_tower_image_size}")
298
+ else: # single image operations
299
+ image_feature = image_feature[0]
300
+ if "unpad" in mm_patch_merge_type:
301
+ image_feature = torch.cat((image_feature, self.model.image_newline[None]), dim=0)
302
+
303
+ # print(f"image/video_feature.shape: {image_feature.shape}")
304
+ new_image_features.append(image_feature)
305
+ image_features = new_image_features
306
+ else:
307
+ raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")
308
+ else:
309
+ # raise NotImplementedError(f"images.shape={images.shape}, modalities={modalities}")
310
+ image_features = self.encode_image(images)
311
+
312
+ # TODO: image start / end is not implemented here to support pretraining.
313
+ if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(self.config, "mm_use_im_start_end", False):
314
+ raise NotImplementedError
315
+ # print(f"Total images len(image_features: {len(image_features)}")
316
+
317
+ # Let's just add dummy tensors if they do not exist,
318
+ # it is a headache to deal with None all the time.
319
+ # But it is not ideal, and if you have a better idea,
320
+ # please open an issue / submit a PR, thanks.
321
+ _labels = labels
322
+ _position_ids = position_ids
323
+ _attention_mask = attention_mask
324
+ if attention_mask is None:
325
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
326
+ else:
327
+ attention_mask = attention_mask.bool()
328
+ if position_ids is None:
329
+ position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
330
+ if labels is None:
331
+ labels = torch.full_like(input_ids, IGNORE_INDEX)
332
+
333
+
334
+ input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
335
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
336
+
337
+ new_input_embeds = []
338
+ new_labels = []
339
+ cur_image_idx = 0
340
+
341
+ mm_llm_compress = getattr(self.config, "mm_llm_compress", False)
342
+
343
+ if mm_llm_compress:
344
+ self.model.llm_compress_type = getattr(self.config, "llm_compress_type", "attention")
345
+ self.model.llm_compress_layer_list = getattr(self.config, "llm_compress_layer_list", [8, 16, 24])
346
+ self.model.llm_image_token_ratio_list = getattr(self.config, "llm_image_token_ratio_list", [1.0, 0.5, 0.25, 0.125])
347
+ first_image_token_position = []
348
+ text_prompt_lens = []
349
+ else:
350
+ self.model.llm_compress_type = "attention"
351
+ self.model.llm_compress_layer_list = []
352
+ self.model.llm_image_token_ratio_list = []
353
+ first_image_token_position = []
354
+ text_prompt_lens = []
355
+
356
+ # rank_print("Inserting Images embedding")
357
+ for batch_idx, cur_input_ids in enumerate(input_ids):
358
+ num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
359
+
360
+ if mm_llm_compress:
361
+ ####### copy from pdrop, only support single image/video NOTE ##################
362
+ # record image position for further dropping
363
+ image_index = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist()
364
+ assert len(image_index) == 1, f"Only support singe/video: {image_index}"
365
+ if image_index == []:
366
+ first_image_token_position.append(-1)
367
+ else:
368
+ first_image_token_position.append(image_index[0])
369
+
370
+
371
+ # record input instruction length in inference mode
372
+ if not self.training:
373
+ if image_index == []:
374
+ assert num_images == 0, num_images
375
+ else:
376
+ assert num_images == 1, f"num_images={num_images}"
377
+ text_prompt_lens.append(cur_input_ids.shape[0] - num_images) # consider image place holder
378
+
379
+ ###############################################
380
+
381
+ # print(f"num_images={num_images}")
382
+ if num_images == 0:
383
+ cur_image_features = image_features[cur_image_idx]
384
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
385
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
386
+ new_input_embeds.append(cur_input_embeds)
387
+ new_labels.append(labels[batch_idx])
388
+ cur_image_idx += 1
389
+ continue
390
+
391
+ image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
392
+ cur_input_ids_noim = []
393
+ cur_labels = labels[batch_idx]
394
+ cur_labels_noim = []
395
+ for i in range(len(image_token_indices) - 1):
396
+ cur_input_ids_noim.append(cur_input_ids[image_token_indices[i] + 1 : image_token_indices[i + 1]])
397
+ cur_labels_noim.append(cur_labels[image_token_indices[i] + 1 : image_token_indices[i + 1]])
398
+ split_sizes = [x.shape[0] for x in cur_labels_noim]
399
+ cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
400
+ cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
401
+ cur_new_input_embeds = []
402
+ cur_new_labels = []
403
+
404
+ for i in range(num_images + 1):
405
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
406
+ cur_new_labels.append(cur_labels_noim[i])
407
+ if i < num_images:
408
+ try:
409
+ cur_image_features = image_features[cur_image_idx]
410
+ except IndexError:
411
+ print(f"cur_image_idx={cur_image_idx} is not ok")
412
+ cur_image_features = image_features[cur_image_idx - 1]
413
+ cur_image_idx += 1
414
+ cur_new_input_embeds.append(cur_image_features)
415
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
416
+
417
+ cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]
418
+ input_boundaries = np.cumsum([x.shape[0] for x in cur_new_input_embeds])
419
+
420
+ # import pdb; pdb.set_trace()
421
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
422
+ cur_new_labels = torch.cat(cur_new_labels)
423
+
424
+ new_input_embeds.append(cur_new_input_embeds)
425
+ new_labels.append(cur_new_labels)
426
+
427
+
428
+ if mm_llm_compress:
429
+ self.model.first_image_token_position = first_image_token_position
430
+ self.model.text_prompt_lens = text_prompt_lens
431
+ self.model.num_image_token_lens = [image_feature.shape[0] for image_feature in image_features]
432
+
433
+ # Truncate sequences to max length as image embeddings can make the sequence longer
434
+ tokenizer_model_max_length = getattr(self.config, "tokenizer_model_max_length", None)
435
+ # rank_print("Finishing Inserting")
436
+
437
+ new_input_embeds = [x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)]
438
+ new_labels = [x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)]
439
+
440
+ # Combine them
441
+ max_len = max(x.shape[0] for x in new_input_embeds)
442
+ batch_size = len(new_input_embeds)
443
+
444
+ new_input_embeds_padded = []
445
+ new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
446
+ attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
447
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
448
+ # print("Prepare pos id")
449
+
450
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
451
+ cur_len = cur_new_embed.shape[0]
452
+ if getattr(self.config, "tokenizer_padding_side", "right") == "left":
453
+ new_input_embeds_padded.append(torch.cat((torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device), cur_new_embed), dim=0))
454
+ if cur_len > 0:
455
+ new_labels_padded[i, -cur_len:] = cur_new_labels
456
+ attention_mask[i, -cur_len:] = True
457
+ position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
458
+ else:
459
+ new_input_embeds_padded.append(torch.cat((cur_new_embed, torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0))
460
+ if cur_len > 0:
461
+ new_labels_padded[i, :cur_len] = cur_new_labels
462
+ attention_mask[i, :cur_len] = True
463
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
464
+
465
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
466
+ # print("tokenizer padding")
467
+
468
+ if _labels is None:
469
+ new_labels = None
470
+ else:
471
+ new_labels = new_labels_padded
472
+
473
+ if _attention_mask is None:
474
+ attention_mask = None
475
+ else:
476
+ attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
477
+
478
+ if _position_ids is None:
479
+ position_ids = None
480
+ if getattr(self.config, "use_pos_skipping", False) and self.training:
481
+ position_ids = torch.arange(new_input_embeds.size(1), device=new_input_embeds.device).unsqueeze(0).to(new_input_embeds.device)
482
+ split_position = random.randint(0, new_input_embeds.size(1))
483
+ left_add = random.randint(0, self.config.pos_skipping_range)
484
+ right_add = random.randint(left_add, self.config.pos_skipping_range)
485
+ position_ids[:, :split_position] += left_add
486
+ position_ids[:, split_position:] += right_add
487
+ # import pdb; pdb.set_trace()
488
+ # print("Finish preparing")
489
+ frame_start_indices = np.array(frame_start_indices) + input_boundaries[0]
490
+ Attention = self.model.layers[0].self_attn.__class__
491
+ def apply_module(module):
492
+ if isinstance(module, Attention):
493
+ module.input_boundaries = input_boundaries
494
+ module.frame_start_indices = frame_start_indices
495
+ stride = self.get_vision_tower().num_patches_per_side//2
496
+ if self.config.mm_newline_position == "grid":
497
+ stride += 1
498
+ module.stride = stride
499
+ module.model_name = "llava_vid"
500
+ self.model.apply(apply_module)
501
+ return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
502
+
503
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
504
+ if model_args.mm_use_im_patch_token:
505
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
506
+ self.resize_token_embeddings(len(tokenizer))
507
+
508
+ if model_args.mm_use_im_start_end:
509
+ num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
510
+ self.resize_token_embeddings(len(tokenizer))
511
+
512
+ if num_new_tokens > 0:
513
+ input_embeddings = self.get_input_embeddings().weight.data
514
+ output_embeddings = self.get_output_embeddings().weight.data
515
+
516
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
517
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
518
+
519
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
520
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
521
+
522
+ if model_args.tune_mm_mlp_adapter:
523
+ for p in self.get_input_embeddings().parameters():
524
+ p.requires_grad = True
525
+ for p in self.get_output_embeddings().parameters():
526
+ p.requires_grad = False
527
+
528
+ if model_args.pretrain_mm_mlp_adapter:
529
+ mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location="cpu")
530
+ embed_tokens_weight = mm_projector_weights["model.embed_tokens.weight"]
531
+ assert num_new_tokens == 2
532
+ if input_embeddings.shape == embed_tokens_weight.shape:
533
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
534
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
535
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
536
+ else:
537
+ raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
538
+ elif model_args.mm_use_im_patch_token:
539
+ if model_args.tune_mm_mlp_adapter:
540
+ for p in self.get_input_embeddings().parameters():
541
+ p.requires_grad = False
542
+ for p in self.get_output_embeddings().parameters():
543
+ p.requires_grad = False
544
+
545
+
546
+
547
+ class VideoChatFlashQwenConfig(Qwen2Config):
548
+ model_type = "videochat_flash_qwen"
549
+
550
+
551
+ class VideoChatFlashQwenModel(LlavaMetaModel, Qwen2Model_Flash):
552
+ config_class = VideoChatFlashQwenConfig
553
+
554
+ def __init__(self, config: VideoChatFlashQwenConfig):
555
+ super(VideoChatFlashQwenModel, self).__init__(config)
556
+
557
+
558
+ class VideoChatFlashQwenForCausalLM(LlavaMetaForCausalLM, Qwen2ForCausalLM_Flash):
559
+ config_class = VideoChatFlashQwenConfig
560
+
561
+ def __init__(self, config):
562
+ # super(Qwen2ForCausalLM, self).__init__(config)
563
+ Qwen2ForCausalLM_Flash.__init__(self, config)
564
+ config.model_type = "videochat_flash_qwen"
565
+ # config.rope_scaling = None
566
+
567
+ self.model = VideoChatFlashQwenModel(config)
568
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
569
+ # Initialize weights and apply final processing
570
+ self.post_init()
571
+
572
+ def get_model(self):
573
+ return self.model
574
+
575
+ def forward(
576
+ self,
577
+ input_ids: torch.LongTensor = None,
578
+ attention_mask: Optional[torch.Tensor] = None,
579
+ position_ids: Optional[torch.LongTensor] = None,
580
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
581
+ inputs_embeds: Optional[torch.FloatTensor] = None,
582
+ labels: Optional[torch.LongTensor] = None,
583
+ use_cache: Optional[bool] = None,
584
+ output_attentions: Optional[bool] = None,
585
+ output_hidden_states: Optional[bool] = None,
586
+ images: Optional[torch.FloatTensor] = None,
587
+ image_sizes: Optional[List[List[int]]] = None,
588
+ return_dict: Optional[bool] = None,
589
+ modalities: Optional[List[str]] = ["image"],
590
+ dpo_forward: Optional[bool] = False,
591
+ cache_position=None,
592
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
593
+
594
+ if inputs_embeds is None:
595
+ (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes)
596
+
597
+ # print("inputs_embeds.shape:", inputs_embeds.shape)
598
+ if dpo_forward:
599
+ raise NotImplementedError
600
+ else:
601
+ return super().forward(
602
+ input_ids=input_ids,
603
+ attention_mask=attention_mask,
604
+ position_ids=position_ids,
605
+ past_key_values=past_key_values,
606
+ inputs_embeds=inputs_embeds,
607
+ labels=labels,
608
+ use_cache=use_cache,
609
+ output_attentions=output_attentions,
610
+ output_hidden_states=output_hidden_states,
611
+ return_dict=return_dict,
612
+ )
613
+
614
+ @torch.no_grad()
615
+ def generate(
616
+ self,
617
+ inputs: Optional[torch.Tensor] = None,
618
+ images: Optional[torch.Tensor] = None,
619
+ image_sizes: Optional[torch.Tensor] = None,
620
+ modalities: Optional[List[str]] = ["image"],
621
+ **kwargs,
622
+ ) -> Union[GenerateOutput, torch.LongTensor]:
623
+ position_ids = kwargs.pop("position_ids", None)
624
+ attention_mask = kwargs.pop("attention_mask", None)
625
+ if "inputs_embeds" in kwargs:
626
+ raise NotImplementedError("`inputs_embeds` is not supported")
627
+
628
+ if images is not None:
629
+ (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes)
630
+ else:
631
+ self.model.image_token_posi = [-1]
632
+ self.model.prompt_len = None
633
+ self.model.image_tokens = [0]
634
+ inputs_embeds = self.get_model().embed_tokens(inputs)
635
+
636
+ return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs)
637
+
638
+ @torch.no_grad()
639
+ def chat(self,
640
+ video_path,
641
+ tokenizer,
642
+ user_prompt,
643
+ chat_history=None,
644
+ return_history=True,
645
+ max_num_frames=512,
646
+ media_dict=None,
647
+ generation_config={}):
648
+
649
+ frames, time_msg = load_video(video_path, max_num_frames=max_num_frames, media_dict=media_dict)
650
+
651
+ image_sizes = [frames[0].shape[:2]]
652
+
653
+ frames = [self.get_vision_tower().image_processor.preprocess(frames, return_tensors="pt")["pixel_values"].to(self.model.dtype).cuda()]
654
+
655
+ conv = conv_templates["qwen_2"].copy()
656
+
657
+ if chat_history is None or len(chat_history) == 0:
658
+ user_prompt = f'{DEFAULT_IMAGE_TOKEN}\n{time_msg.strip()} {user_prompt}'
659
+ else:
660
+ assert DEFAULT_IMAGE_TOKEN in chat_history[0]['content'], chat_history
661
+ for msg in chat_history:
662
+ conv.append_message(msg['role'], msg['content'])
663
+
664
+ conv.append_message(conv.roles[0], user_prompt)
665
+ conv.append_message(conv.roles[1], None)
666
+
667
+ prompt = conv.get_prompt()
668
+
669
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
670
+
671
+ if tokenizer.pad_token_id is None:
672
+ if "qwen" in tokenizer.name_or_path.lower():
673
+ print("Setting pad token to bos token for qwen model.")
674
+ tokenizer.pad_token_id = 151643
675
+
676
+ attention_masks = input_ids.ne(tokenizer.pad_token_id).long().cuda()
677
+
678
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
679
+ keywords = [stop_str]
680
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
681
+
682
+ with torch.inference_mode():
683
+ output_ids = self.generate(
684
+ inputs=input_ids,
685
+ images=frames,
686
+ attention_mask=attention_masks,
687
+ modalities=["video"],
688
+ image_sizes=image_sizes,
689
+ use_cache=True,
690
+ stopping_criteria=[stopping_criteria],
691
+ **generation_config
692
+ )
693
+
694
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
695
+ if outputs.endswith(stop_str):
696
+ outputs = outputs[: -len(stop_str)]
697
+
698
+ outputs = outputs.strip()
699
+
700
+ # print(f"\033[91m== Question: \033[0m\n{prompt}\n")
701
+ # print(f"\033[91m== Response: \033[0m\n{outputs}\n")
702
+
703
+ if chat_history is None:
704
+ chat_history = []
705
+
706
+ chat_history.append({"role":conv.roles[0], "content":user_prompt})
707
+ chat_history.append({"role":conv.roles[1], "content":outputs})
708
+ if return_history:
709
+ return outputs, chat_history
710
+ else:
711
+ return outputs
712
+
713
+
714
+
715
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
716
+ images = kwargs.pop("images", None)
717
+ image_sizes = kwargs.pop("image_sizes", None)
718
+ inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs)
719
+ if images is not None:
720
+ inputs["images"] = images
721
+ if image_sizes is not None:
722
+ inputs["image_sizes"] = image_sizes
723
+ return inputs
724
+
725
+
726
+ AutoConfig.register("videochat_flash_qwen", VideoChatFlashQwenConfig)
727
+ AutoModelForCausalLM.register(VideoChatFlashQwenConfig, VideoChatFlashQwenForCausalLM)
special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ }
181
+ },
182
+ "additional_special_tokens": [
183
+ "<|im_start|>",
184
+ "<|im_end|>",
185
+ "<|object_ref_start|>",
186
+ "<|object_ref_end|>",
187
+ "<|box_start|>",
188
+ "<|box_end|>",
189
+ "<|quad_start|>",
190
+ "<|quad_end|>",
191
+ "<|vision_start|>",
192
+ "<|vision_end|>",
193
+ "<|vision_pad|>",
194
+ "<|image_pad|>",
195
+ "<|video_pad|>"
196
+ ],
197
+ "bos_token": null,
198
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
199
+ "clean_up_tokenization_spaces": false,
200
+ "eos_token": "<|im_end|>",
201
+ "errors": "replace",
202
+ "model_max_length": 32768,
203
+ "pad_token": "<|endoftext|>",
204
+ "padding_side": "right",
205
+ "split_special_tokens": false,
206
+ "tokenizer_class": "Qwen2Tokenizer",
207
+ "unk_token": null
208
+ }
trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b56ec34c18c9bbd191a2faf6892f9eb4c856cdec5d8b0fa05f54ad8da5d942f2
3
+ size 7480
vision_tower_builder.py ADDED
@@ -0,0 +1,632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, Union, Dict
2
+ from dataclasses import dataclass
3
+ from functools import partial, reduce
4
+ from PIL import Image
5
+ import os
6
+ from transformers.image_processing_utils import BatchFeature, get_size_dict
7
+ from transformers.image_transforms import (
8
+ convert_to_rgb,
9
+ normalize,
10
+ rescale,
11
+ resize,
12
+ to_channel_dimension_format,
13
+ )
14
+ from transformers.image_utils import (
15
+ ChannelDimension,
16
+ PILImageResampling,
17
+ to_numpy_array,
18
+ )
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ import torch.utils.checkpoint as checkpoint
24
+ from functools import partial
25
+ try:
26
+ from flash_attn import flash_attn_qkvpacked_func
27
+ use_flash_attn = True
28
+ except:
29
+ use_flash_attn = False
30
+ print("You need to install flash_attn to be faster!")
31
+
32
+ try:
33
+ from timm.layers import drop_path, to_2tuple, trunc_normal_
34
+ except:
35
+ from timm.models.layers import drop_path, trunc_normal_, to_2tuple
36
+
37
+
38
+
39
+ class DropPath(nn.Module):
40
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
41
+ """
42
+ def __init__(self, drop_prob=None):
43
+ super(DropPath, self).__init__()
44
+ self.drop_prob = drop_prob
45
+
46
+ def forward(self, x):
47
+ return drop_path(x, self.drop_prob, self.training)
48
+
49
+ def extra_repr(self) -> str:
50
+ return 'p={}'.format(self.drop_prob)
51
+
52
+
53
+ class Mlp(nn.Module):
54
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
55
+ super().__init__()
56
+ out_features = out_features or in_features
57
+ hidden_features = hidden_features or in_features
58
+ self.fc1 = nn.Linear(in_features, hidden_features)
59
+ self.act = act_layer()
60
+ self.fc2 = nn.Linear(hidden_features, out_features)
61
+ self.drop = nn.Dropout(drop)
62
+
63
+ def forward(self, x):
64
+ x = self.fc1(x)
65
+ x = self.act(x)
66
+ x = self.drop(x)
67
+ x = self.fc2(x)
68
+ x = self.drop(x)
69
+ return x
70
+
71
+ class Attention(nn.Module):
72
+ def __init__(
73
+ self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
74
+ proj_drop=0., attn_head_dim=None,
75
+ attn_type='flash_v2'):
76
+
77
+ if use_flash_attn:
78
+ attn_type = attn_type
79
+ else:
80
+ attn_type = 'origin'
81
+
82
+ print(attn_type)
83
+
84
+ super().__init__()
85
+ self.num_heads = num_heads
86
+ head_dim = dim // num_heads
87
+ if attn_head_dim is not None:
88
+ head_dim = attn_head_dim
89
+ all_head_dim = head_dim * self.num_heads
90
+ self.scale = qk_scale or head_dim ** -0.5
91
+
92
+ self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
93
+ if qkv_bias:
94
+ self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
95
+ self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
96
+ else:
97
+ self.q_bias = None
98
+ self.v_bias = None
99
+
100
+ if attn_type not in ['origin', 'flash_v2']:
101
+ raise NotImplementedError(f"Not support attn_type: {attn_type}")
102
+
103
+ # print('umt:', f'attn_type: {attn_type}')
104
+
105
+ self.attn_type = attn_type
106
+ if attn_type == 'flash_v2':
107
+ self.attn_drop = attn_drop
108
+ else:
109
+ self.attn_drop = nn.Dropout(attn_drop)
110
+ self.proj = nn.Linear(all_head_dim, dim)
111
+ self.proj_drop = nn.Dropout(proj_drop)
112
+
113
+ def forward(self, x):
114
+ B, N, C = x.shape
115
+ qkv_bias = None
116
+ if self.q_bias is not None:
117
+ qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
118
+ # qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
119
+ qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
120
+
121
+ if self.attn_type == 'flash_v2':
122
+ qkv = qkv.reshape(B, N, 3, self.num_heads, -1)
123
+ x = flash_attn_qkvpacked_func(qkv, dropout_p=self.attn_drop, softmax_scale=self.scale, causal=False).reshape(B, N, -1)
124
+ else:
125
+ qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
126
+ q, k, v = qkv[0], qkv[1], qkv[
127
+ 2] # make torchscript happy (cannot use tensor as tuple)
128
+ # B num_heads N head_dim
129
+
130
+ q = q * self.scale
131
+ attn = (q @ k.transpose(-2, -1))
132
+
133
+ attn = attn.softmax(dim=-1)
134
+ attn = self.attn_drop(attn)
135
+
136
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
137
+
138
+ x = self.proj(x)
139
+ x = self.proj_drop(x)
140
+ return x
141
+
142
+
143
+
144
+
145
+ class Block(nn.Module):
146
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
147
+ drop_path=0., init_values=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm,
148
+ attn_head_dim=None):
149
+ super().__init__()
150
+ self.norm1 = norm_layer(dim)
151
+ self.attn = Attention(
152
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
153
+ attn_drop=attn_drop, proj_drop=drop, attn_head_dim=attn_head_dim)
154
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
155
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
156
+ self.norm2 = norm_layer(dim)
157
+ mlp_hidden_dim = int(dim * mlp_ratio)
158
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
159
+
160
+ if init_values > 0:
161
+ self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True)
162
+ self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True)
163
+ else:
164
+ self.gamma_1, self.gamma_2 = None, None
165
+
166
+ def forward(self, x):
167
+ if self.gamma_1 is None:
168
+ x = x + self.drop_path(self.attn(self.norm1(x)))
169
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
170
+ else:
171
+ x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x)))
172
+ x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
173
+ return x
174
+
175
+
176
+ class PatchEmbed(nn.Module):
177
+ """ Image to Patch Embedding
178
+ """
179
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, num_frames=16, tubelet_size=2):
180
+ super().__init__()
181
+ img_size = to_2tuple(img_size)
182
+ patch_size = to_2tuple(patch_size)
183
+ self.tubelet_size = int(tubelet_size)
184
+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) * (num_frames // self.tubelet_size)
185
+ self.img_size = img_size
186
+ self.patch_size = patch_size
187
+ self.num_patches = num_patches
188
+ self.proj = nn.Conv3d(
189
+ in_channels=in_chans, out_channels=embed_dim,
190
+ kernel_size=(self.tubelet_size, patch_size[0], patch_size[1]),
191
+ stride=(self.tubelet_size, patch_size[0], patch_size[1])
192
+ )
193
+ # print('umt:', f'Num of patches: {num_patches}')
194
+
195
+ def forward(self, x, **kwargs):
196
+ B, C, T, H, W = x.shape
197
+ # FIXME look at relaxing size constraints
198
+ # assert H == self.img_size[0] and W == self.img_size[1], \
199
+ # f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
200
+ x = self.proj(x).flatten(2).transpose(1, 2)
201
+ return x
202
+
203
+ # sin-cos position encoding
204
+ # https://github.com/jadore801120/attention-is-all-you-need-pytorch/blob/master/transformer/Models.py#L31
205
+ def get_sinusoid_encoding_table(n_position, d_hid, ckpt_num_frame=-1, cur_frame=12):
206
+ ''' Sinusoid position encoding table '''
207
+ # TODO: make it with torch instead of numpy
208
+ def get_position_angle_vec(position):
209
+ return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]
210
+
211
+ if ckpt_num_frame != -1 and ckpt_num_frame != cur_frame:
212
+ # print('umt:', f"Interpolate position embedding")
213
+ # print('umt:', f"Testing frame: {cur_frame}")
214
+ # print('umt:', f"Checkpoint frame: {ckpt_num_frame}")
215
+
216
+ T = ckpt_num_frame # checkpoint frame
217
+ new_T = cur_frame # testing frame
218
+ n_position = n_position // new_T * T # generate checkpoint position embedding
219
+ sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
220
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
221
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
222
+ sinusoid_table = torch.tensor(sinusoid_table, dtype=torch.float, requires_grad=False).unsqueeze(0)
223
+ # interpolate
224
+ P = int((n_position // T) ** 0.5)
225
+ C = d_hid
226
+ sinusoid_table = sinusoid_table.reshape(-1, T, P, P, C)
227
+ sinusoid_table = sinusoid_table.permute(0, 2, 3, 4, 1).reshape(-1, C, T) # BHW, C, T
228
+ sinusoid_table = torch.nn.functional.interpolate(sinusoid_table, size=new_T, mode='linear')
229
+ sinusoid_table = sinusoid_table.reshape(1, P, P, C, new_T).permute(0, 4, 1, 2, 3) # B, T, H, W, C
230
+ sinusoid_table = sinusoid_table.flatten(1, 3)
231
+ return sinusoid_table
232
+ else:
233
+ sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
234
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
235
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
236
+ return torch.tensor(sinusoid_table, dtype=torch.float, requires_grad=False).unsqueeze(0)
237
+
238
+
239
+ def get_sinusoid_encoding_table2(n_position=784, d_hid=1024, cur_frame=8, ckpt_num_frame=4, pre_n_position=784):
240
+ ''' Sinusoid position encoding table '''
241
+ # TODO: make it with torch instead of numpy
242
+ def get_position_angle_vec(position):
243
+ return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]
244
+
245
+ # generate checkpoint position embedding
246
+ sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(pre_n_position)])
247
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
248
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
249
+ sinusoid_table = torch.tensor(sinusoid_table, dtype=torch.float, requires_grad=False).unsqueeze(0)
250
+
251
+ # print(f"n_position: {n_position}")
252
+ # print(f"pre_n_position: {pre_n_position}")
253
+
254
+ if n_position != pre_n_position:
255
+ T = ckpt_num_frame # checkpoint frame
256
+ P = 14 # checkpoint size
257
+ C = d_hid
258
+ new_P = int((n_position // cur_frame) ** 0.5) # testing size
259
+ # print(f'Pretraining uses 14x14, but current version is {new_P}x{new_P}')
260
+ # print(f'Interpolate the position embedding')
261
+ sinusoid_table = sinusoid_table.reshape(-1, T, P, P, C)
262
+ sinusoid_table = sinusoid_table.reshape(-1, P, P, C).permute(0, 3, 1, 2)
263
+ sinusoid_table = torch.nn.functional.interpolate(
264
+ sinusoid_table, size=(new_P, new_P), mode='bicubic', align_corners=False)
265
+ # BT, C, H, W -> BT, H, W, C -> B, T, H, W, C
266
+ sinusoid_table = sinusoid_table.permute(0, 2, 3, 1).reshape(-1, T, new_P, new_P, C)
267
+ sinusoid_table = sinusoid_table.flatten(1, 3) # B, THW, C
268
+
269
+ if cur_frame != ckpt_num_frame:
270
+ # print(f'Pretraining uses 4 frames, but current frame is {cur_frame}')
271
+ # print(f'Interpolate the position embedding')
272
+ T = ckpt_num_frame # checkpoint frame
273
+ new_T = cur_frame # testing frame
274
+ # interpolate
275
+ P = int((n_position // cur_frame) ** 0.5) # testing size
276
+ C = d_hid
277
+ sinusoid_table = sinusoid_table.reshape(-1, T, P, P, C)
278
+ sinusoid_table = sinusoid_table.permute(0, 2, 3, 4, 1).reshape(-1, C, T) # BHW, C, T
279
+ sinusoid_table = torch.nn.functional.interpolate(sinusoid_table, size=new_T, mode='linear')
280
+ sinusoid_table = sinusoid_table.reshape(1, P, P, C, new_T).permute(0, 4, 1, 2, 3) # B, T, H, W, C
281
+ sinusoid_table = sinusoid_table.flatten(1, 3) # B, THW, C
282
+
283
+ return sinusoid_table
284
+
285
+
286
+ class PretrainVisionTransformerEncoder(nn.Module):
287
+ """ Vision Transformer with support for patch or hybrid CNN input stage
288
+ """
289
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, depth=12,
290
+ num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
291
+ drop_path_rate=0., norm_layer=nn.LayerNorm, init_values=None, num_frames=8, tubelet_size=1,
292
+ use_learnable_pos_emb=False,
293
+ use_checkpoint=False, checkpoint_num=0,
294
+ ckpt_num_frame=-1, with_ln=True, return_index=-1
295
+ ):
296
+ super().__init__()
297
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
298
+ self.patch_embed = PatchEmbed(
299
+ img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,
300
+ num_frames=num_frames, tubelet_size=tubelet_size
301
+ )
302
+ num_patches = self.patch_embed.num_patches
303
+ self.depth = depth + return_index + 1
304
+ self.use_checkpoint = use_checkpoint
305
+ self.checkpoint_num = checkpoint_num
306
+ # print('umt:', f"Use checkpoint: {use_checkpoint}")
307
+ # print('umt:', f"Checkpoint number: {checkpoint_num}")
308
+ # print('UMT:', f"Real runing depth: {self.depth}")
309
+
310
+ # TODO: Add the cls token
311
+ if use_learnable_pos_emb:
312
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
313
+ self.img_pos_embed = nn.Parameter(torch.zeros(1, num_patches//(num_frames//tubelet_size) + 1, embed_dim))
314
+ else:
315
+ # sine-cosine positional embeddings
316
+ if img_size != 224:
317
+ self.pos_embed = get_sinusoid_encoding_table2(num_patches, embed_dim, ckpt_num_frame=ckpt_num_frame, cur_frame=num_frames//tubelet_size)
318
+ self.img_pos_embed = get_sinusoid_encoding_table2(num_patches//(num_frames//tubelet_size), embed_dim, cur_frame=1, ckpt_num_frame=1, pre_n_position=14*14)
319
+ else:
320
+ self.pos_embed = get_sinusoid_encoding_table(num_patches, embed_dim, ckpt_num_frame=ckpt_num_frame, cur_frame=num_frames//tubelet_size)
321
+ self.img_pos_embed = get_sinusoid_encoding_table(num_patches//(num_frames//tubelet_size), embed_dim)
322
+
323
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
324
+ self.blocks = nn.ModuleList([
325
+ Block(
326
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
327
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
328
+ init_values=init_values)
329
+ for i in range(self.depth)])
330
+
331
+ if with_ln:
332
+ self.vision_layernorm = nn.LayerNorm(embed_dim, eps=1e-12)
333
+ else:
334
+ self.vision_layernorm = nn.Identity()
335
+
336
+ if use_learnable_pos_emb:
337
+ trunc_normal_(self.pos_embed, std=.02)
338
+
339
+ @torch.jit.ignore
340
+ def no_weight_decay(self):
341
+ return {'pos_embed', 'cls_token'}
342
+
343
+ def forward_features(self, x, use_image=False):
344
+ x = self.patch_embed(x)
345
+
346
+ if use_image:
347
+ x = x + self.img_pos_embed.type_as(x).to(x.device).clone().detach()
348
+ else:
349
+ x = x + self.pos_embed.type_as(x).to(x.device).clone().detach()
350
+
351
+ B, _, C = x.shape
352
+ x_vis = x
353
+
354
+ for idx, blk in enumerate(self.blocks):
355
+ if self.use_checkpoint and idx < self.checkpoint_num:
356
+ x_vis = checkpoint.checkpoint(blk, x_vis)
357
+ else:
358
+ x_vis = blk(x_vis)
359
+
360
+ # with ln ot not
361
+ x_vis = self.vision_layernorm(x_vis)
362
+ return x_vis
363
+
364
+ def forward(self, x, use_image=False):
365
+ x_vis = self.forward_features(x, use_image)
366
+ return x_vis
367
+
368
+
369
+ class PretrainVisionTransformer(nn.Module):
370
+ """ Vision Transformer with support for patch or hybrid CNN input stage
371
+ """
372
+ def __init__(self,
373
+ img_size=224,
374
+ patch_size=16,
375
+ encoder_in_chans=3,
376
+ encoder_embed_dim=768,
377
+ encoder_depth=12,
378
+ encoder_num_heads=12,
379
+ mlp_ratio=4.,
380
+ qkv_bias=True,
381
+ qk_scale=None,
382
+ drop_rate=0.,
383
+ attn_drop_rate=0.,
384
+ drop_path_rate=0.,
385
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
386
+ init_values=0.,
387
+ use_learnable_pos_emb=False,
388
+ num_frames=8,
389
+ tubelet_size=1,
390
+ use_checkpoint=False,
391
+ checkpoint_num=0,
392
+ ckpt_num_frame=4, # the pretrained model uses 4 frames
393
+ return_index=-1,
394
+ with_ln=False
395
+ ):
396
+ super().__init__()
397
+
398
+ self.encoder = PretrainVisionTransformerEncoder(
399
+ img_size=img_size,
400
+ patch_size=patch_size,
401
+ in_chans=encoder_in_chans,
402
+ embed_dim=encoder_embed_dim,
403
+ depth=encoder_depth,
404
+ num_heads=encoder_num_heads,
405
+ mlp_ratio=mlp_ratio,
406
+ qkv_bias=qkv_bias,
407
+ qk_scale=qk_scale,
408
+ drop_rate=drop_rate,
409
+ attn_drop_rate=attn_drop_rate,
410
+ drop_path_rate=drop_path_rate,
411
+ norm_layer=norm_layer,
412
+ init_values=init_values,
413
+ num_frames=num_frames,
414
+ tubelet_size=tubelet_size,
415
+ use_learnable_pos_emb=use_learnable_pos_emb,
416
+ use_checkpoint=use_checkpoint,
417
+ checkpoint_num=checkpoint_num,
418
+ ckpt_num_frame=ckpt_num_frame,
419
+ with_ln=with_ln,
420
+ return_index=return_index
421
+ )
422
+ # print('umt:', f'With LN: {with_ln}')
423
+ # print('UMT:', f'Total {encoder_depth} layer')
424
+ # print('UMT:', f'Return {encoder_depth+return_index+1}-th layer')
425
+
426
+ self.apply(self._init_weights)
427
+
428
+ def _init_weights(self, m):
429
+ if isinstance(m, nn.Linear):
430
+ nn.init.xavier_uniform_(m.weight)
431
+ if isinstance(m, nn.Linear) and m.bias is not None:
432
+ nn.init.constant_(m.bias, 0)
433
+ elif isinstance(m, nn.LayerNorm):
434
+ nn.init.constant_(m.bias, 0)
435
+ nn.init.constant_(m.weight, 1.0)
436
+
437
+ @torch.jit.ignore
438
+ def no_weight_decay(self):
439
+ return {'pos_embed', 'cls_token', 'clip_pos_embed'}
440
+
441
+ def forward(self, x, use_image=False):
442
+ T = x.shape[2]
443
+ x_vis = self.encoder(x, use_image) # [B, N_vis, C_e]
444
+ B, TL, C = x_vis.shape
445
+ x_vis = x_vis.view(B, T, TL // T, C)
446
+
447
+ return x_vis
448
+
449
+
450
+
451
+
452
+
453
+
454
+
455
+ class UMTImageProcessor:
456
+ def __init__(self, image_mean=(0.485, 0.456, 0.406), image_std=(0.229, 0.224, 0.225), size=(224, 224), crop_size: Dict[str, int] = None, resample=PILImageResampling.BICUBIC, rescale_factor=1 / 255, data_format=ChannelDimension.FIRST):
457
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
458
+ crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
459
+
460
+ self.image_mean = image_mean
461
+ self.image_std = image_std
462
+ self.size = size
463
+ self.resample = resample
464
+ self.rescale_factor = rescale_factor
465
+ self.data_format = data_format
466
+ self.crop_size = crop_size
467
+
468
+ def preprocess(self, images, return_tensors, target_size=None):
469
+ if isinstance(images, Image.Image):
470
+ images = [images]
471
+ else:
472
+ # to adapt video data
473
+ images = [to_numpy_array(image) for image in images]
474
+ assert isinstance(images, list)
475
+
476
+ if target_size is None:
477
+ target_size = self.size
478
+
479
+ transforms = [
480
+ convert_to_rgb,
481
+ to_numpy_array,
482
+ partial(resize, size=target_size, resample=self.resample, data_format=self.data_format),
483
+ partial(rescale, scale=self.rescale_factor, data_format=self.data_format),
484
+ partial(normalize, mean=self.image_mean, std=self.image_std, data_format=self.data_format),
485
+ partial(to_channel_dimension_format, channel_dim=self.data_format, input_channel_dim=self.data_format),
486
+ ]
487
+
488
+ images = reduce(lambda x, f: [*map(f, x)], transforms, images)
489
+ data = {"pixel_values": images}
490
+
491
+ return BatchFeature(data=data, tensor_type=return_tensors)
492
+
493
+
494
+ class UMTVisionConfig:
495
+ model_type = "umt_vision_model"
496
+
497
+ def __init__(
498
+ self,
499
+ num_frames=4,
500
+ hidden_size=1024,
501
+ num_hidden_layers=24,
502
+ num_attention_heads=16,
503
+ num_channels=3,
504
+ image_size=224,
505
+ patch_size=16,
506
+ return_idx=-2
507
+ # **kwargs,
508
+ ):
509
+ # super().__init__(**kwargs)
510
+ self.num_frames = num_frames
511
+ self.hidden_size = hidden_size
512
+ self.num_hidden_layers = num_hidden_layers
513
+ self.num_attention_heads = num_attention_heads
514
+ self.num_channels = num_channels
515
+ self.patch_size = patch_size
516
+ self.image_size = image_size
517
+ self.return_idx = return_idx
518
+
519
+
520
+ def build_vit(config, pt_type='origin'):
521
+ model = PretrainVisionTransformer(
522
+ img_size=config.image_size,
523
+ patch_size=16,
524
+ encoder_embed_dim=1024,
525
+ encoder_depth=24,
526
+ encoder_num_heads=16,
527
+ drop_path_rate=0.,
528
+ num_frames=config.num_frames,
529
+ tubelet_size=1,
530
+ use_checkpoint=False,
531
+ checkpoint_num=24,
532
+ return_index=config.return_idx,
533
+ with_ln=True, # merge vision_layernorm in it
534
+ )
535
+
536
+ # no need to load pt
537
+
538
+ return model
539
+
540
+
541
+
542
+ class UMTVisionTower(nn.Module):
543
+ def __init__(self, vision_tower, vision_tower_cfg, delay_load=False, pt_type='origin', image_size=224):
544
+ super().__init__()
545
+
546
+ self.is_loaded = False
547
+ self.pt_type = pt_type
548
+
549
+ self.config = UMTVisionConfig(num_frames=vision_tower_cfg.mm_local_num_frames, return_idx=vision_tower_cfg.mm_vision_select_layer, image_size=image_size)
550
+
551
+ self.vision_tower_name = vision_tower
552
+
553
+ self.image_processor = UMTImageProcessor(size=(image_size, image_size))
554
+
555
+ if not delay_load:
556
+ print(f"Loading vision tower: {vision_tower}")
557
+ self.load_model()
558
+ elif getattr(vision_tower_cfg, "unfreeze_mm_vision_tower", False):
559
+ # TODO: better detector is needed.
560
+ print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
561
+ self.load_model()
562
+ elif hasattr(vision_tower_cfg, "mm_tunable_parts") and "mm_vision_tower" in vision_tower_cfg.mm_tunable_parts:
563
+ print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
564
+ self.load_model()
565
+ else:
566
+ self.cfg_only = self.config
567
+
568
+ def load_model(self, device_map=None):
569
+ if self.is_loaded:
570
+ print("{} is already loaded, `load_model` called again, skipping.".format(self.vision_tower_name))
571
+ return
572
+
573
+ self.vision_tower = build_vit(self.config, pt_type=self.pt_type)
574
+ self.vision_tower.requires_grad_(False)
575
+
576
+ self.is_loaded = True
577
+
578
+ def forward(self, images):
579
+ if type(images) is list:
580
+ raise NotImplementedError
581
+ else:
582
+ # input: B T C H W
583
+ # output: B T*L C
584
+ T = images.shape[1]
585
+ images = images.permute(0, 2, 1, 3, 4)
586
+ image_embeds = self.vision_tower(images, use_image=(T == 1))
587
+ B, T, L, C = image_embeds.shape
588
+ image_embeds = image_embeds.reshape(B, -1, C)
589
+
590
+ return image_embeds
591
+
592
+ @property
593
+ def dummy_feature(self):
594
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
595
+
596
+ @property
597
+ def dtype(self):
598
+ for p in self.vision_tower.parameters():
599
+ return p.dtype
600
+
601
+ @property
602
+ def device(self):
603
+ for p in self.vision_tower.parameters():
604
+ return p.device
605
+
606
+ @property
607
+ def hidden_size(self):
608
+ return self.config.hidden_size
609
+
610
+ @property
611
+ def num_patches(self):
612
+ return (self.config.image_size // self.config.patch_size) ** 2
613
+
614
+ @property
615
+ def num_patches_per_side(self):
616
+ return self.config.image_size // self.config.patch_size
617
+
618
+ @property
619
+ def image_size(self):
620
+ return self.config.image_size
621
+
622
+
623
+ def build_vision_tower(vision_tower_cfg, **kwargs):
624
+ vision_tower = getattr(vision_tower_cfg, "mm_vision_tower", getattr(vision_tower_cfg, "vision_tower", None))
625
+
626
+
627
+ if "umt-hd" in vision_tower:
628
+ return UMTVisionTower(vision_tower, vision_tower_cfg=vision_tower_cfg, image_size=448, **kwargs)
629
+ elif "umt" in vision_tower:
630
+ return UMTVisionTower(vision_tower, vision_tower_cfg=vision_tower_cfg, **kwargs)
631
+
632
+ raise ValueError(f"Unknown vision tower: {vision_tower}")
vocab.json ADDED
The diff for this file is too large to render. See raw diff