BAAI
/

CharmingDog commited on
Commit
627f346
·
1 Parent(s): 0f06c51

update .py file

Browse files
Files changed (7) hide show
  1. configuration_qwen2.py +169 -0
  2. constants.py +12 -0
  3. conversation.py +554 -0
  4. llava_arch.py +742 -0
  5. llava_qwen.py +709 -0
  6. mm_utils.py +454 -0
  7. modeling_qwen2.py +1549 -0
configuration_qwen2.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Qwen2 model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ QWEN2_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "Qwen/Qwen2-7B-beta": "https://huggingface.co/Qwen/Qwen2-7B-beta/resolve/main/config.json",
25
+ }
26
+
27
+
28
+ class Qwen2Config(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
31
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
32
+ with the defaults will yield a similar configuration to that of
33
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 151936):
41
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`Qwen2Model`]
43
+ hidden_size (`int`, *optional*, defaults to 4096):
44
+ Dimension of the hidden representations.
45
+ intermediate_size (`int`, *optional*, defaults to 22016):
46
+ Dimension of the MLP representations.
47
+ num_hidden_layers (`int`, *optional*, defaults to 32):
48
+ Number of hidden layers in the Transformer encoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 32):
50
+ Number of attention heads for each attention layer in the Transformer encoder.
51
+ num_key_value_heads (`int`, *optional*, defaults to 32):
52
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
53
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
54
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
55
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
56
+ by meanpooling all the original heads within that group. For more details checkout [this
57
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
58
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
59
+ The non-linear activation function (function or string) in the decoder.
60
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
61
+ The maximum sequence length that this model might ever be used with.
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
70
+ Whether the model's input and output word embeddings should be tied.
71
+ rope_theta (`float`, *optional*, defaults to 10000.0):
72
+ The base period of the RoPE embeddings.
73
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
74
+ Whether to use sliding window attention.
75
+ sliding_window (`int`, *optional*, defaults to 4096):
76
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
77
+ max_window_layers (`int`, *optional*, defaults to 28):
78
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
79
+ attention_dropout (`float`, *optional*, defaults to 0.0):
80
+ The dropout ratio for the attention probabilities.
81
+
82
+ ```python
83
+ >>> from transformers import Qwen2Model, Qwen2Config
84
+
85
+ >>> # Initializing a Qwen2 style configuration
86
+ >>> configuration = Qwen2Config()
87
+
88
+ >>> # Initializing a model from the Qwen2-7B style configuration
89
+ >>> model = Qwen2Model(configuration)
90
+
91
+ >>> # Accessing the model configuration
92
+ >>> configuration = model.config
93
+ ```"""
94
+
95
+ model_type = "qwen2"
96
+ keys_to_ignore_at_inference = ["past_key_values"]
97
+
98
+ def __init__(
99
+ self,
100
+ vocab_size=151936,
101
+ hidden_size=4096,
102
+ intermediate_size=22016,
103
+ num_hidden_layers=32,
104
+ num_attention_heads=32,
105
+ num_key_value_heads=32,
106
+ hidden_act="silu",
107
+ max_position_embeddings=32768,
108
+ initializer_range=0.02,
109
+ rms_norm_eps=1e-6,
110
+ use_cache=True,
111
+ tie_word_embeddings=False,
112
+ rope_theta=10000.0,
113
+ use_sliding_window=False,
114
+ sliding_window=4096,
115
+ rope_scaling=None,
116
+ max_window_layers=28,
117
+ attention_dropout=0.0,
118
+ beacon_window=1024,
119
+ beacon_stride=1024,
120
+ beacon_attn="full-coverage",
121
+ beacon_ratio=[2,4,8,16,32],
122
+ beacon_ratio_mix="step-random",
123
+ beacon_param=[],
124
+ beacon_embed_init="eos",
125
+ beacon_sink_size=0,
126
+ beacon_attend_prev=True,
127
+ beacon_pos="interleave",
128
+ beacon_parallel_window=1,
129
+ **kwargs,
130
+ ):
131
+ self.vocab_size = vocab_size
132
+ self.max_position_embeddings = max_position_embeddings
133
+ self.hidden_size = hidden_size
134
+ self.intermediate_size = intermediate_size
135
+ self.num_hidden_layers = num_hidden_layers
136
+ self.num_attention_heads = num_attention_heads
137
+ self.use_sliding_window = use_sliding_window
138
+ self.sliding_window = sliding_window
139
+ self.max_window_layers = max_window_layers
140
+ self.rope_scaling = rope_scaling
141
+
142
+ # for backward compatibility
143
+ if num_key_value_heads is None:
144
+ num_key_value_heads = num_attention_heads
145
+
146
+ self.num_key_value_heads = num_key_value_heads
147
+ self.hidden_act = hidden_act
148
+ self.initializer_range = initializer_range
149
+ self.rms_norm_eps = rms_norm_eps
150
+ self.use_cache = use_cache
151
+ self.rope_theta = rope_theta
152
+ self.attention_dropout = attention_dropout
153
+
154
+ self.beacon_window = beacon_window
155
+ self.beacon_stride = beacon_stride
156
+ self.beacon_attn = beacon_attn
157
+ self.beacon_ratio = beacon_ratio
158
+ self.beacon_ratio_mix = beacon_ratio_mix
159
+ self.beacon_param = beacon_param
160
+ self.beacon_embed_init = beacon_embed_init
161
+ self.beacon_sink_size = beacon_sink_size
162
+ self.beacon_attend_prev = beacon_attend_prev
163
+ self.beacon_pos = beacon_pos
164
+ self.beacon_parallel_window = beacon_parallel_window
165
+
166
+ super().__init__(
167
+ tie_word_embeddings=tie_word_embeddings,
168
+ **kwargs,
169
+ )
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,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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:
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 to_gradio_chatbot(self):
243
+ ret = []
244
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
245
+ if i % 2 == 0:
246
+ if type(msg) is tuple:
247
+ msg, image, image_process_mode = msg
248
+ if type(image) != list:
249
+ image = [image]
250
+ if len(image) == 1:
251
+ msg = "<image>\n" + msg.replace("<image>", "").strip()
252
+ else:
253
+ msg = re.sub(r"(<image>)\n(?=<image>)", r"\1 ", msg)
254
+ for img in image:
255
+ img_b64_str = self.process_image(img, "Default", return_pil=False, image_format="JPEG")
256
+ img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}"/>'
257
+ msg = msg.replace("<image>", img_str, 1).strip()
258
+ if len(msg) > 0:
259
+ ret.append([msg, None])
260
+ else:
261
+ ret.append([msg, None])
262
+ else:
263
+ ret[-1][-1] = msg
264
+ return ret
265
+
266
+ def copy(self):
267
+ 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)
268
+
269
+ def dict(self):
270
+ if len(self.get_images()) > 0:
271
+ return {
272
+ "system": self.system,
273
+ "roles": self.roles,
274
+ "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
275
+ "offset": self.offset,
276
+ "sep": self.sep,
277
+ "sep2": self.sep2,
278
+ }
279
+ return {
280
+ "system": self.system,
281
+ "roles": self.roles,
282
+ "messages": self.messages,
283
+ "offset": self.offset,
284
+ "sep": self.sep,
285
+ "sep2": self.sep2,
286
+ }
287
+
288
+
289
+ conv_vicuna_v0 = Conversation(
290
+ 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.",
291
+ roles=("Human", "Assistant"),
292
+ messages=[
293
+ ["Human", "What are the key differences between renewable and non-renewable energy sources?"],
294
+ [
295
+ "Assistant",
296
+ "Renewable energy sources are those that can be replenished naturally in a relatively "
297
+ "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
298
+ "Non-renewable energy sources, on the other hand, are finite and will eventually be "
299
+ "depleted, such as coal, oil, and natural gas. Here are some key differences between "
300
+ "renewable and non-renewable energy sources:\n"
301
+ "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
302
+ "energy sources are finite and will eventually run out.\n"
303
+ "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
304
+ "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
305
+ "and other negative effects.\n"
306
+ "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
307
+ "have lower operational costs than non-renewable sources.\n"
308
+ "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
309
+ "locations than non-renewable sources.\n"
310
+ "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
311
+ "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
312
+ "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
313
+ "non-renewable sources are not, and their depletion can lead to economic and social instability.\n",
314
+ ],
315
+ ],
316
+ offset=2,
317
+ sep_style=SeparatorStyle.SINGLE,
318
+ sep="###",
319
+ )
320
+
321
+ conv_vicuna_v1 = Conversation(
322
+ 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.",
323
+ roles=("USER", "ASSISTANT"),
324
+ version="v1",
325
+ messages=[],
326
+ offset=0,
327
+ sep_style=SeparatorStyle.TWO,
328
+ sep=" ",
329
+ sep2="</s>",
330
+ )
331
+
332
+ conv_llama_2 = Conversation(
333
+ 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.
334
+
335
+ 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.""",
336
+ roles=("USER", "ASSISTANT"),
337
+ version="llama_v2",
338
+ messages=[],
339
+ offset=0,
340
+ sep_style=SeparatorStyle.LLAMA_2,
341
+ sep="<s>",
342
+ sep2="</s>",
343
+ )
344
+
345
+ conv_llava_llama_2 = Conversation(
346
+ 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.",
347
+ roles=("USER", "ASSISTANT"),
348
+ version="llama_v2",
349
+ messages=[],
350
+ offset=0,
351
+ sep_style=SeparatorStyle.LLAMA_2,
352
+ sep="<s>",
353
+ sep2="</s>",
354
+ )
355
+
356
+ # This will lead to a bug when user can not access Meta-Llama-3-8B-Instruct
357
+ # conv_llava_llama_3 = Conversation(
358
+ # 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.",
359
+ # roles=("user", "assistant"),
360
+ # version="llama_v3",
361
+ # messages=[],
362
+ # offset=0,
363
+ # sep="<|eot_id|>",
364
+ # sep_style=SeparatorStyle.LLAMA_3,
365
+ # tokenizer_id="meta-llama/Meta-Llama-3-8B-Instruct",
366
+ # tokenizer=AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct"),
367
+ # stop_token_ids=[128009],
368
+ # )
369
+
370
+ conv_mistral_instruct = Conversation(
371
+ system="",
372
+ roles=("USER", "ASSISTANT"),
373
+ version="llama_v2",
374
+ messages=[],
375
+ offset=0,
376
+ sep_style=SeparatorStyle.LLAMA_2,
377
+ sep="",
378
+ sep2="</s>",
379
+ )
380
+
381
+ conv_llava_llama_2_simple = Conversation(
382
+ system="Answer the questions about the visual content that the user provides.",
383
+ roles=("USER", "ASSISTANT"),
384
+ version="llama_v2",
385
+ messages=[],
386
+ offset=0,
387
+ sep_style=SeparatorStyle.LLAMA_2,
388
+ sep="<s>",
389
+ sep2="</s>",
390
+ )
391
+
392
+ conv_llava_llama_2_mmtag = Conversation(
393
+ 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>.",
394
+ roles=("USER", "ASSISTANT"),
395
+ version="llama_v2_mmtag",
396
+ messages=[],
397
+ offset=0,
398
+ sep_style=SeparatorStyle.LLAMA_2,
399
+ sep="<s>",
400
+ sep2="</s>",
401
+ )
402
+
403
+ conv_mpt = Conversation(
404
+ system="""<|im_start|>system
405
+ A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
406
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
407
+ version="mpt",
408
+ messages=[],
409
+ offset=0,
410
+ sep_style=SeparatorStyle.MPT,
411
+ sep="<|im_end|>",
412
+ )
413
+
414
+ conv_qwen = Conversation(
415
+ system="""<|im_start|>system
416
+ You are a helpful assistant.""",
417
+ roles=("<|im_start|>user", "<|im_start|>assistant"),
418
+ version="qwen",
419
+ messages=[],
420
+ offset=0,
421
+ sep_style=SeparatorStyle.CHATML,
422
+ sep="<|im_end|>",
423
+ )
424
+
425
+ 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")
426
+
427
+ conv_llava_plain = Conversation(
428
+ system="",
429
+ roles=("", ""),
430
+ messages=[],
431
+ offset=0,
432
+ sep_style=SeparatorStyle.PLAIN,
433
+ sep="\n",
434
+ )
435
+
436
+ conv_llava_v0 = Conversation(
437
+ 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.",
438
+ roles=("Human", "Assistant"),
439
+ messages=[],
440
+ offset=0,
441
+ sep_style=SeparatorStyle.SINGLE,
442
+ sep="###",
443
+ )
444
+
445
+ conv_llava_v0_mmtag = Conversation(
446
+ system="A chat between a curious user and an artificial intelligence assistant. "
447
+ "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."
448
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
449
+ roles=("Human", "Assistant"),
450
+ messages=[],
451
+ offset=0,
452
+ sep_style=SeparatorStyle.SINGLE,
453
+ sep="###",
454
+ version="v0_mmtag",
455
+ )
456
+
457
+ conv_llava_v1 = Conversation(
458
+ 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.",
459
+ roles=("USER", "ASSISTANT"),
460
+ version="v1",
461
+ messages=[],
462
+ offset=0,
463
+ sep_style=SeparatorStyle.TWO,
464
+ sep=" ",
465
+ sep2="</s>",
466
+ )
467
+
468
+ conv_llava_v1_mmtag = Conversation(
469
+ system="A chat between a curious user and an artificial intelligence assistant. "
470
+ "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."
471
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
472
+ roles=("USER", "ASSISTANT"),
473
+ messages=[],
474
+ offset=0,
475
+ sep_style=SeparatorStyle.TWO,
476
+ sep=" ",
477
+ sep2="</s>",
478
+ version="v1_mmtag",
479
+ )
480
+
481
+ conv_mistral_orca = Conversation(
482
+ system="""<|im_start|>system
483
+ 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!""",
484
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
485
+ version="mpt",
486
+ messages=[],
487
+ offset=0,
488
+ sep_style=SeparatorStyle.MPT,
489
+ sep="<|im_end|>",
490
+ )
491
+
492
+ conv_mistral_zephyr = Conversation(
493
+ system="""<|system|>
494
+ You are a helpful AI assistant.""",
495
+ roles=("<|user|>\n", "<|assistant|>\n"),
496
+ version="mpt",
497
+ messages=[],
498
+ offset=0,
499
+ sep_style=SeparatorStyle.MPT,
500
+ sep="</s>",
501
+ )
502
+
503
+ conv_mistral_direct = Conversation(
504
+ system="""<|im_start|>system
505
+ Answer the questions.""",
506
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
507
+ version="mpt",
508
+ messages=[],
509
+ offset=0,
510
+ sep_style=SeparatorStyle.MPT,
511
+ sep="<|im_end|>",
512
+ )
513
+
514
+ conv_chatml_direct = Conversation(
515
+ system="""<|im_start|>system
516
+ Answer the questions.""",
517
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
518
+ version="mpt",
519
+ messages=[],
520
+ offset=0,
521
+ sep_style=SeparatorStyle.MPT,
522
+ sep="<|im_end|>",
523
+ )
524
+
525
+ default_conversation = conv_vicuna_v0
526
+ conv_templates = {
527
+ "default": conv_vicuna_v0,
528
+ "v0": conv_vicuna_v0,
529
+ "v1": conv_vicuna_v1,
530
+ "vicuna_v1": conv_vicuna_v1,
531
+ "llama_2": conv_llama_2,
532
+ "mistral_instruct": conv_mistral_instruct,
533
+ "mistral_orca": conv_mistral_orca,
534
+ "mistral_zephyr": conv_mistral_zephyr,
535
+ "mistral_direct": conv_mistral_direct,
536
+ "plain": conv_llava_plain,
537
+ "v0_plain": conv_llava_plain,
538
+ "chatml_direct": conv_chatml_direct,
539
+ "llava_v0": conv_llava_v0,
540
+ "llava_v0_mmtag": conv_llava_v0_mmtag,
541
+ "llava_v1": conv_llava_v1,
542
+ "llava_v1_mmtag": conv_llava_v1_mmtag,
543
+ "llava_llama_2": conv_llava_llama_2,
544
+ "llava_llama_2_simple": conv_llava_llama_2_simple,
545
+ "llava_llama_2_mmtag": conv_llava_llama_2_mmtag,
546
+ "llava_mistral_instruct": conv_mistral_instruct,
547
+ "mpt": conv_mpt,
548
+ "qwen_1_5": conv_qwen,
549
+ "gemma_instruct": conv_gemma_instruct,
550
+ }
551
+
552
+
553
+ if __name__ == "__main__":
554
+ print(default_conversation.get_prompt())
llava_arch.py ADDED
@@ -0,0 +1,742 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
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
+
16
+ from abc import ABC, abstractmethod
17
+
18
+ import math
19
+ import re
20
+ import time
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+ from .multimodal_encoder.builder import build_vision_tower
25
+ from .multimodal_resampler.builder import build_vision_resampler
26
+ from .multimodal_projector.builder import build_vision_projector
27
+ from transformers import AutoTokenizer
28
+
29
+ from longva.longva.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
30
+
31
+ from longva.longva.mm_utils import get_anyres_image_grid_shape
32
+ from longva.longva.utils import rank0_print
33
+ import random
34
+ from .sae import SiglipAE
35
+ from .WindowTimeToTokenAttention import WindowTimeToTokenAttention
36
+ import numpy as np
37
+ import torch.nn.functional as F
38
+ import pdb
39
+ class LlavaMetaModel:
40
+
41
+ def __init__(self, config):
42
+ super(LlavaMetaModel, self).__init__(config)
43
+
44
+ if hasattr(config, "mm_vision_tower"):
45
+ delay_load = getattr(config, "delay_load", False)
46
+ self.vision_tower = build_vision_tower(config, delay_load=delay_load)
47
+ self.vision_resampler = build_vision_resampler(config, vision_tower=self.vision_tower)
48
+ self.mm_projector = build_vision_projector(config, vision_cfg=self.vision_tower.config)
49
+
50
+ if "unpad" in getattr(config, "mm_patch_merge_type", ""):
51
+ self.image_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
52
+
53
+ # self.llm_tokenizer = AutoTokenizer.from_pretrained(config._name_or_path)
54
+ self.hidden_size=config.hidden_size
55
+ # print(config)
56
+ # exit(0)
57
+
58
+ # self.text_tokenizer = T5Tokenizer.from_pretrained('google-t5/t5-small')
59
+ ##############################################################################
60
+ # self.text_select_model = T5EncoderModel.from_pretrained('google-t5/t5-small')
61
+
62
+ # self.text_gamma=0.75
63
+
64
+ ###############################################################################
65
+ self.text_mlp=nn.Sequential(
66
+ nn.Linear(config.hidden_size,config.hidden_size),
67
+ nn.GELU(),
68
+ )
69
+ self.sae=SiglipAE()
70
+ #self.sae.load_state_dict(torch.load('/share/LXRlxr0_0/code/videoxl2/videoxl2/longva/longva/model/encoder.pth'),strict=False)
71
+
72
+ ###############################################################################
73
+ # self.vision_select=nn.Parameter(
74
+ # torch.randn((4, self.config.hidden_size), dtype=self.dtype)
75
+ # )
76
+ ##############################################################################
77
+
78
+ def get_vision_tower(self):
79
+ vision_tower = getattr(self, "vision_tower", None)
80
+ if type(vision_tower) is list:
81
+ vision_tower = vision_tower[0]
82
+ return vision_tower
83
+
84
+ def initialize_vision_modules(self, model_args, fsdp=None):
85
+ vision_tower = model_args.vision_tower
86
+ mm_vision_select_layer = model_args.mm_vision_select_layer
87
+ mm_vision_select_feature = model_args.mm_vision_select_feature
88
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
89
+ mm_patch_merge_type = model_args.mm_patch_merge_type
90
+
91
+ self.config.mm_vision_tower = vision_tower
92
+ self.config.vision_tower_pretrained = getattr(model_args, "vision_tower_pretrained", "")
93
+
94
+ if self.get_vision_tower() is None:
95
+ vision_tower = build_vision_tower(model_args)
96
+ vision_resampler = build_vision_resampler(model_args, vision_tower=vision_tower)
97
+ for k, v in vision_resampler.config.items():
98
+ setattr(self.config, k, v)
99
+
100
+ if fsdp is not None and len(fsdp) > 0:
101
+ self.vision_tower = [vision_tower]
102
+ self.vision_resampler = [vision_resampler]
103
+ else:
104
+ self.vision_tower = vision_tower
105
+ self.vision_resampler = vision_resampler
106
+ else:
107
+ if fsdp is not None and len(fsdp) > 0:
108
+ vision_resampler = self.vision_resampler[0]
109
+ vision_tower = self.vision_tower[0]
110
+ else:
111
+ vision_resampler = self.vision_resampler
112
+ vision_tower = self.vision_tower
113
+ vision_tower.load_model()
114
+
115
+ # In case it is frozen by LoRA
116
+ for p in self.vision_resampler.parameters():
117
+ p.requires_grad = True
118
+
119
+ self.config.use_mm_proj = True
120
+ self.config.mm_projector_type = getattr(model_args, "mm_projector_type", "linear")
121
+ self.config.mm_hidden_size = getattr(vision_resampler, "hidden_size", vision_tower.hidden_size)
122
+ self.config.mm_vision_select_layer = mm_vision_select_layer
123
+ self.config.mm_vision_select_feature = mm_vision_select_feature
124
+ self.config.mm_patch_merge_type = mm_patch_merge_type
125
+
126
+ self.sae=SiglipAE()
127
+ self.sae.load_state_dict(torch.load('/share/LXRlxr0_0/code/videoxl2/videoxl2/longva/longva/model/encoder.pth'),strict=False)
128
+ ##############################################################################
129
+ # self.vision_select=nn.Parameter(
130
+ # torch.randn((30, self.config.hidden_size), dtype=self.dtype)
131
+ # )
132
+
133
+ # #self.text_tokenizer = T5Tokenizer.from_pretrained('google-t5/t5-small')
134
+ # self.text_select_model = T5EncoderModel.from_pretrained('google-t5/t5-small')
135
+
136
+ # self.text_mlp=nn.Sequential(
137
+ # nn.Linear(512,self.config.hidden_size),
138
+ # nn.GELU(),
139
+ # # nn.Linear(config.hidden_size,config.hidden_size),
140
+ # # nn.GELU(),
141
+ # )
142
+ ##############################################################################
143
+
144
+
145
+ if getattr(self, "mm_projector", None) is None:
146
+ self.mm_projector = build_vision_projector(self.config, vision_cfg=vision_tower.config)
147
+
148
+ if "unpad" in mm_patch_merge_type:
149
+ embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
150
+ self.image_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
151
+ else:
152
+ # In case it is frozen by LoRA
153
+ for p in self.mm_projector.parameters():
154
+ p.requires_grad = True
155
+
156
+ if pretrain_mm_mlp_adapter is not None:
157
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location="cpu")
158
+
159
+ def get_w(weights, keyword):
160
+ return {k.split(keyword + ".")[1]: v for k, v in weights.items() if keyword in k}
161
+
162
+ incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"))
163
+ rank0_print(f"Loaded mm projector weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}")
164
+ incompatible_keys = self.vision_resampler.load_state_dict(get_w(mm_projector_weights, "vision_resampler"), strict=False)
165
+ rank0_print(f"Loaded vision resampler weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}")
166
+
167
+
168
+ # self.vision_select.data = mm_projector_weights["model.vision_select"]
169
+
170
+ # self.text_mlp.load_state_dict(get_w(mm_projector_weights, "text_mlp"))
171
+
172
+ # self.text_select_model.load_state_dict(get_w(mm_projector_weights, "text_select_model"),strict=False)
173
+ #self.vision_tower.load_state_dict(get_w(mm_projector_weights, "vision_tower"),strict=False)
174
+
175
+ def unpad_image(tensor, original_size):
176
+ """
177
+ Unpads a PyTorch tensor of a padded and resized image.
178
+
179
+ Args:
180
+ tensor (torch.Tensor): The image tensor, assumed to be in CxHxW format.
181
+ original_size (tuple): The original size of the image (height, width).
182
+
183
+ Returns:
184
+ torch.Tensor: The unpadded image tensor.
185
+ """
186
+ original_width, original_height = original_size
187
+ current_height, current_width = tensor.shape[1:]
188
+
189
+ # Compute aspect ratios
190
+ original_aspect_ratio = original_width / original_height
191
+ current_aspect_ratio = current_width / current_height
192
+
193
+ # Determine padding size and direction
194
+ if original_aspect_ratio > current_aspect_ratio:
195
+ # Padding was added to the height
196
+ scale_factor = current_width / original_width
197
+ new_height = int(original_height * scale_factor)
198
+ padding = (current_height - new_height) // 2
199
+ unpadded_tensor = tensor[:, padding : current_height - padding, :]
200
+ else:
201
+ # Padding was added to the width
202
+ scale_factor = current_height / original_height
203
+ new_width = int(original_width * scale_factor)
204
+ padding = (current_width - new_width) // 2
205
+ unpadded_tensor = tensor[:, :, padding : current_width - padding]
206
+
207
+ return unpadded_tensor
208
+
209
+ def rotary_position_embedding(q):
210
+ seq_len, dim = q.shape
211
+
212
+ position = torch.arange(seq_len, dtype=torch.float).unsqueeze(-1).to(q.device)
213
+
214
+ div_term = torch.exp(torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(1000000.0) / dim)).to(q.device)
215
+
216
+ pos_emb = position * div_term
217
+ pos_emb = torch.stack([torch.sin(pos_emb), torch.cos(pos_emb)], dim=-1).flatten(-2, -1)
218
+
219
+ cos_emb = pos_emb[..., 1::2].repeat_interleave(2, dim=-1)
220
+ sin_emb = pos_emb[..., ::2].repeat_interleave(2, dim=-1)
221
+
222
+ q_alternate = torch.stack([-q[..., 1::2], q[..., ::2]], dim=-1).reshape(q.size())
223
+
224
+ q_rotated = q * cos_emb + q_alternate * sin_emb
225
+
226
+ return q_rotated
227
+
228
+ class LlavaMetaForCausalLM(ABC):
229
+
230
+ @abstractmethod
231
+ def get_model(self):
232
+ pass
233
+
234
+ def get_vision_tower(self):
235
+ return self.get_model().get_vision_tower()
236
+
237
+ def get_2dPool(self, image_feature):
238
+ height = width = self.get_vision_tower().num_patches_per_side
239
+ num_frames, num_tokens, num_dim = image_feature.shape
240
+ image_feature = image_feature.view(num_frames, height, width, -1)
241
+ image_feature = image_feature.permute(0, 3, 1, 2).contiguous()
242
+ # image_feature = nn.functional.max_pool2d(image_feature, self.config.mm_spatial_pool_stride)
243
+ if self.config.mm_spatial_pool_mode == "average":
244
+ image_feature = nn.functional.avg_pool2d(image_feature, self.config.mm_spatial_pool_stride)
245
+ elif self.config.mm_spatial_pool_mode == "max":
246
+ image_feature = nn.functional.max_pool2d(image_feature, self.config.mm_spatial_pool_stride)
247
+ else:
248
+ raise ValueError(f"Unexpected mm_spatial_pool_mode: {self.config.mm_spatial_pool_mode}")
249
+ image_feature = image_feature.permute(0, 2, 3, 1)
250
+ image_feature = image_feature.view(num_frames, -1, num_dim)
251
+ return image_feature
252
+
253
+ def encode_images(self, images):
254
+ image_features = self.get_model().get_vision_tower()(images)
255
+ #image_features = self.get_model().vision_resampler(image_features, images=images)
256
+ image_features = self.get_model().mm_projector(image_features)
257
+ image_features = self.get_model().vision_resampler(image_features, images=images)
258
+ return image_features
259
+
260
+ def add_image(self, image_features):
261
+ return torch.repeat_interleave(image_features, repeats=4, dim=0)
262
+
263
+ def add_video(self, video_features):
264
+ if video_features.size(0)<4:
265
+ last_feature = video_features[-1:]
266
+
267
+ repeated_features = last_feature.repeat(4 - video_features.size(0), 1,1,1)
268
+ expanded_x = torch.cat([video_features, repeated_features], dim=0)
269
+ return expanded_x
270
+
271
+ repeat_counts = torch.ones(video_features.size(0), dtype=torch.long, device=video_features.device)
272
+
273
+ sum_counts=torch.sum(repeat_counts)
274
+ if sum_counts % 4!=0:
275
+ padding_size = 4 - (sum_counts % 4)
276
+ random_indices = torch.randperm(repeat_counts.size(0))[:padding_size].to(video_features.device)
277
+ repeat_counts[random_indices] += 1
278
+
279
+ expanded_x = torch.repeat_interleave(video_features, repeat_counts, dim=0)
280
+
281
+ return expanded_x
282
+
283
+ def encode_multimodals(self, videos_or_images, video_idx_in_batch, split_sizes=None):
284
+ #################################################################################
285
+ # if videos_or_images.shape[0] > 360:
286
+ # random_indices = np.random.choice(videos_or_images.shape[0], size=360, replace=False)
287
+ # videos_or_images = videos_or_images[random_indices]
288
+ # split_sizes=videos_or_images.shape[0]
289
+
290
+ #################################################################################
291
+ # Define the maximum batch size (1024 frames)
292
+ max_batch_size = 60
293
+ num_frames = videos_or_images.shape[0]
294
+ # Initialize a list to store the features from each batch
295
+ videos_or_images_features = []
296
+
297
+ # Split videos_or_images into smaller batches if num_frames > max_batch_size
298
+ if num_frames > max_batch_size:
299
+ # Calculate the number of batches needed
300
+ num_batches = (num_frames + max_batch_size - 1) // max_batch_size
301
+ for i in range(num_batches):
302
+ start_idx = i * max_batch_size
303
+ end_idx = min((i + 1) * max_batch_size, num_frames)
304
+
305
+ # Process each batch separately
306
+ batch_videos_or_images = videos_or_images[start_idx:end_idx]
307
+ batch_features = self.get_model().get_vision_tower()(batch_videos_or_images)
308
+ videos_or_images_features.append(batch_features)
309
+
310
+ # Concatenate the features of all batches
311
+ videos_or_images_features = torch.cat(videos_or_images_features, dim=0)
312
+ else:
313
+ videos_or_images_features = self.get_model().get_vision_tower()(videos_or_images)
314
+
315
+ per_videos_or_images_features = torch.split(videos_or_images_features, split_sizes, dim=0) # tuple, (dim_1, 576, 4096)
316
+ all_videos_or_images_features = []
317
+
318
+
319
+ for idx, feat in enumerate(per_videos_or_images_features):
320
+ #print(feat.shape,end='1\n')
321
+ feat=self.interpolate(feat)
322
+ #######################################################
323
+ if idx in video_idx_in_batch:
324
+ feat=self.add_video(feat)
325
+ else:
326
+ feat=self.add_image(feat)
327
+
328
+ bc,ch,h,w=feat.shape
329
+
330
+ feat = feat.view(bc//4,ch,4,h,w)
331
+ if bc//4>24:
332
+ chunk_size = 24
333
+ chunks = torch.split(feat, chunk_size, dim=0)
334
+ interpolated_chunks = []
335
+ for chunk in chunks:
336
+ interpolated_chunk=self.get_model().sae(chunk).squeeze(2)
337
+ interpolated_chunks.append(interpolated_chunk)
338
+ feat = torch.cat(interpolated_chunks, dim=0)
339
+ del interpolated_chunks
340
+ del chunks
341
+ else:
342
+ feat=self.get_model().sae(feat).squeeze(2)
343
+ feat = feat.permute(0, 2, 3, 1).contiguous().flatten(1, 2)
344
+ #print(feat.shape,end='3\n')
345
+ feat = self.get_model().mm_projector(feat)
346
+ #print(feat.shape,end='4\n')
347
+ # Post pooling
348
+ if idx in video_idx_in_batch:
349
+ #print('************************',idx,video_idx_in_batch)
350
+ feat = self.get_2dPool(feat)
351
+ all_videos_or_images_features.append(feat)
352
+
353
+ del per_videos_or_images_features
354
+ return all_videos_or_images_features
355
+ ########################################################
356
+ def interpolate(self,image_features):
357
+ b, num_tokens, dim = image_features.shape
358
+
359
+ #print(str(image_features.shape)+' i\n')
360
+
361
+ target_h = target_w = int(576**0.5)
362
+ h = w = int(num_tokens**0.5)
363
+
364
+ image_features = image_features.view(b, h, w, dim)
365
+ image_features = image_features.permute(0, 3, 1, 2).contiguous()
366
+
367
+ chunk_size = 24
368
+ chunks = torch.split(image_features, chunk_size, dim=0)
369
+ interpolated_chunks = []
370
+ for chunk in chunks:
371
+ interpolated_chunk = F.interpolate(
372
+ chunk.to(torch.float32),
373
+ size=(target_h, target_w),
374
+ mode="bilinear",
375
+ align_corners=False,
376
+ ).to(chunk.dtype)
377
+ interpolated_chunks.append(interpolated_chunk)
378
+ image_features = torch.cat(interpolated_chunks, dim=0)
379
+ del interpolated_chunks
380
+
381
+ del chunks
382
+
383
+ return image_features
384
+
385
+ def prepare_inputs_labels_for_multimodal(self, input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities=["image"], image_sizes=None,time_embedding=None):
386
+ vision_tower = self.get_vision_tower()
387
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
388
+ return input_ids, position_ids, attention_mask, past_key_values, None, labels
389
+
390
+ if type(images) is list or images.ndim == 5:
391
+ if type(images) is list:
392
+ images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]
393
+
394
+ video_idx_in_batch = []
395
+ for _ in range(len(modalities)):
396
+ if modalities[_] == "video":
397
+ video_idx_in_batch.append(_)
398
+
399
+ images_list = []
400
+ for image in images:
401
+ if image.ndim == 4:
402
+ images_list.append(image)
403
+ else:
404
+ images_list.append(image.unsqueeze(0))
405
+ #print(len(images_list),images_list[0].shape)
406
+
407
+ concat_images = torch.cat([image for image in images_list], dim=0)
408
+ split_sizes = [image.shape[0] for image in images_list]
409
+
410
+ image_features = self.encode_multimodals(concat_images, video_idx_in_batch, split_sizes) #16,144,3584
411
+
412
+ mm_patch_merge_type = getattr(self.config, "mm_patch_merge_type", "flat")
413
+ image_aspect_ratio = getattr(self.config, "image_aspect_ratio", "square")
414
+
415
+ visual_drop_score=[]
416
+ new_image_features=[]
417
+
418
+ if mm_patch_merge_type == "flat":
419
+
420
+ if image_features[0].ndim>2:
421
+ image_features = [x.flatten(0, 1) for x in image_features]
422
+ elif mm_patch_merge_type== "unires":
423
+ #print('unires')
424
+ for image_idx, image_feature in enumerate(image_features):
425
+ # rank0_print(f"Initial feature size : {image_feature.shape}")
426
+ if image_idx in video_idx_in_batch: # video operations
427
+ #print(image_feature.shape)
428
+ image_feature = image_feature.flatten(0, 1)
429
+
430
+ elif image_feature.shape[0] > 1:
431
+ # base image feature is never used in unires
432
+ base_image_feature = image_feature[0]
433
+ image_feature = image_feature[1:]
434
+
435
+ height = width = self.get_vision_tower().num_patches_per_side
436
+ assert height * width == base_image_feature.shape[0]
437
+
438
+ kernel_size = mm_patch_merge_type.split("avgpool")[-1].split("x")[-1]
439
+ kernel_size = 2
440
+ image_feature = image_feature.view(image_feature.shape[0], height, width, -1) # [4, 24, 24, 4096]
441
+ image_feature = image_feature.permute(0, 3, 1, 2).contiguous() # [4, 4096, 24, 24]
442
+ image_feature = nn.functional.avg_pool2d(image_feature,kernel_size) # [4, 4096, 12, 12]
443
+ image_feature = image_feature.flatten(2, 3) # [4, 4096, 144]
444
+ image_feature = image_feature.permute(0, 2, 1).contiguous() # [4, 144, 4096]
445
+
446
+ #print(image_feature.shape)
447
+ image_feature = image_feature.flatten(0, 1)
448
+
449
+ else:
450
+
451
+ image_feature = image_feature[0]
452
+
453
+ new_image_features.append(image_feature)
454
+
455
+ image_features = new_image_features
456
+
457
+ elif mm_patch_merge_type.startswith("spatial"):
458
+ new_image_features = []
459
+ for image_idx, image_feature in enumerate(image_features):
460
+ # FIXME: now assume the image is square, and split to 2x2 patches
461
+ # num_patches = h * w, where h = w = sqrt(num_patches)
462
+ # currently image_feature is a tensor of shape (4, num_patches, hidden_size)
463
+ # we want to first unflatten it to (2, 2, h, w, hidden_size)
464
+ if image_idx in video_idx_in_batch: # video operations
465
+ if "unpad" in mm_patch_merge_type:
466
+ # image_feature = image_feature.permute(2, 0, 1).contiguous()
467
+ # image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
468
+ # image_feature = image_feature.permute(1, 2, 0).contiguous()
469
+ image_feature = image_feature.flatten(0, 1)
470
+ image_feature = torch.cat((image_feature, self.model.image_newline[None].to(image_feature.device)), dim=0)
471
+
472
+ elif image_feature.shape[0] > 1: # multi patches and multi images operations
473
+ base_image_feature = image_feature[0]
474
+ image_feature = image_feature[1:]
475
+ height = width = self.get_vision_tower().num_patches_per_side
476
+ assert height * width == base_image_feature.shape[0]
477
+
478
+ if "anyres_max" in image_aspect_ratio:
479
+ matched_anyres_max_num_patches = re.match(r"anyres_max_(\d+)", image_aspect_ratio)
480
+ if matched_anyres_max_num_patches:
481
+ max_num_patches = int(matched_anyres_max_num_patches.group(1))
482
+
483
+ if image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio:
484
+ if hasattr(self.get_vision_tower(), "image_size"):
485
+ vision_tower_image_size = self.get_vision_tower().image_size
486
+ else:
487
+ raise ValueError("vision_tower_image_size is not found in the vision tower.")
488
+ num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, vision_tower_image_size)
489
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
490
+ else:
491
+ image_feature = image_feature.view(2, 2, height, width, -1)
492
+
493
+ if "maxpool2x2" in mm_patch_merge_type:
494
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
495
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
496
+ image_feature = nn.functional.max_pool2d(image_feature, 2)
497
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
498
+ elif "unpad" in mm_patch_merge_type and "anyres_max" in image_aspect_ratio and matched_anyres_max_num_patches:
499
+ unit = image_feature.shape[2]
500
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
501
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
502
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
503
+ c, h, w = image_feature.shape
504
+ times = math.sqrt(h * w / (max_num_patches * unit**2))
505
+ if times > 1.1:
506
+ image_feature = image_feature[None]
507
+ image_feature = nn.functional.interpolate(image_feature, [int(h // times), int(w // times)], mode="bilinear")[0]
508
+ image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
509
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
510
+ elif "unpad" in mm_patch_merge_type:
511
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
512
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
513
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
514
+ image_feature = torch.cat((image_feature, self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)), dim=-1)
515
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
516
+ else:
517
+ image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
518
+ image_feature = image_feature.flatten(0, 3)
519
+ if "nobase" in mm_patch_merge_type:
520
+ pass
521
+ else:
522
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
523
+ else: # single image operations
524
+ image_feature = image_feature[0]
525
+ if "unpad" in mm_patch_merge_type:
526
+ image_feature = torch.cat((image_feature, self.model.image_newline[None]), dim=0)
527
+
528
+ new_image_features.append(image_feature)
529
+ image_features = new_image_features
530
+ else:
531
+ raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")
532
+ else:
533
+ error_message = """
534
+ Something is wrong with the input shape. Most likely, you did not wrap the image or video input in a list:
535
+ This is correct:
536
+ model.generate(input_ids, images=[video_tensor], modalities=["video"], **gen_kwargs)
537
+ model.generate(input_ids, images=[image_tensor], modalities=["image"], **gen_kwargs)
538
+ This is wrong:
539
+ model.generate(input_ids, images=video_tensor, modalities=["video"], **gen_kwargs)
540
+ model.generate(input_ids, images=image_tensor, modalities=["image"], **gen_kwargs)
541
+ """
542
+ raise ValueError(error_message)
543
+
544
+ #print(time_embedding[0].shape)
545
+ #video_token_indices=[]
546
+ for image_idx, image_feature in enumerate(image_features):
547
+ if time_embedding[image_idx] is not None:
548
+ mask = (time_embedding[image_idx] == 151654)
549
+ indices = torch.nonzero(mask).squeeze()
550
+
551
+ embed_token=self.get_model().embed_tokens(time_embedding[image_idx])
552
+ embed_token[indices]=image_features[image_idx]
553
+
554
+ #video_token_indices.append(indices)
555
+
556
+ image_features[image_idx]=embed_token
557
+
558
+ if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(self.config, "mm_use_im_start_end", False):
559
+ raise NotImplementedError
560
+
561
+ # Let's just add dummy tensors if they do not exist,
562
+ # it is a headache to deal with None all the time.
563
+ # But it is not ideal, and if you have a better idea,
564
+ # please open an issue / submit a PR, thanks.
565
+ _labels = labels
566
+ _position_ids = position_ids
567
+ _attention_mask = attention_mask
568
+ if attention_mask is None:
569
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
570
+ else:
571
+ attention_mask = attention_mask.bool()
572
+ if position_ids is None:
573
+ position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
574
+ if labels is None:
575
+ labels = torch.full_like(input_ids, IGNORE_INDEX)
576
+
577
+ # remove the padding using attention_mask -- FIXME
578
+ _input_ids = input_ids
579
+ input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
580
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
581
+
582
+ new_input_embeds = []
583
+ new_labels = []
584
+ cur_image_idx = 0
585
+
586
+ for batch_idx, cur_input_ids in enumerate(input_ids):
587
+ num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
588
+ #print(num_images)
589
+ if num_images>=2:
590
+ print(num_images,input_ids)
591
+ if num_images == 0:
592
+ cur_image_features = image_features[cur_image_idx]
593
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
594
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
595
+ new_input_embeds.append(cur_input_embeds)
596
+ new_labels.append(labels[batch_idx])
597
+ cur_image_idx += 1
598
+ continue
599
+
600
+ image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
601
+ #print(image_token_indices) #[-1, 14, 236]
602
+ cur_input_ids_noim = []
603
+ cur_labels = labels[batch_idx]
604
+
605
+ # print(cur_input_ids)
606
+ # print(labels[batch_idx])
607
+
608
+ cur_labels_noim = []
609
+ for i in range(len(image_token_indices) - 1):
610
+ cur_input_ids_noim.append(cur_input_ids[image_token_indices[i] + 1 : image_token_indices[i + 1]])
611
+ cur_labels_noim.append(cur_labels[image_token_indices[i] + 1 : image_token_indices[i + 1]])
612
+ split_sizes = [x.shape[0] for x in cur_labels_noim]
613
+
614
+ #print(torch.cat(cur_input_ids_noim).shape,torch.cat(cur_input_ids_noim))
615
+
616
+ cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
617
+ cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
618
+ cur_new_input_embeds = []
619
+ cur_new_labels = []
620
+
621
+ for i in range(num_images + 1):
622
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
623
+ cur_new_labels.append(cur_labels_noim[i])
624
+ if i < num_images:
625
+ ##############
626
+ cur_image_features = image_features[cur_image_idx]
627
+ cur_image_idx += 1
628
+ cur_new_input_embeds.append(cur_image_features)
629
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
630
+
631
+ cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]
632
+
633
+ # import pdb; pdb.set_trace()
634
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
635
+
636
+ cur_new_labels = torch.cat(cur_new_labels)
637
+
638
+ new_input_embeds.append(cur_new_input_embeds)
639
+ new_labels.append(cur_new_labels)
640
+
641
+ # Truncate sequences to max length as image embeddings can make the sequence longer
642
+ tokenizer_model_max_length = getattr(self.config, "tokenizer_model_max_length", None)
643
+ # NOTE: qmh 注释
644
+ # new_input_embeds = [x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)]
645
+ # new_labels = [x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)]
646
+
647
+ # TODO: Hard code for control loss spike
648
+ # if tokenizer_model_max_length is not None:
649
+ # new_input_embeds = [x[:4096] if modality != "video" else x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)]
650
+ # new_labels = [x[:4096] if modality != "video" else x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)]
651
+
652
+ # Combine them
653
+ max_len = max(x.shape[0] for x in new_input_embeds)
654
+ batch_size = len(new_input_embeds)
655
+
656
+ new_input_embeds_padded = []
657
+ new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
658
+ attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
659
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
660
+
661
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
662
+ cur_len = cur_new_embed.shape[0]
663
+ if getattr(self.config, "tokenizer_padding_side", "right") == "left":
664
+ 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))
665
+ if cur_len > 0:
666
+ new_labels_padded[i, -cur_len:] = cur_new_labels
667
+ attention_mask[i, -cur_len:] = True
668
+ position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
669
+ else:
670
+ 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))
671
+ if cur_len > 0:
672
+ new_labels_padded[i, :cur_len] = cur_new_labels
673
+ attention_mask[i, :cur_len] = True
674
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
675
+
676
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
677
+
678
+ if _labels is None:
679
+ new_labels = None
680
+ else:
681
+ new_labels = new_labels_padded
682
+
683
+ if _attention_mask is None:
684
+ attention_mask = None
685
+ else:
686
+ attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
687
+
688
+ if _position_ids is None:
689
+ position_ids = None
690
+ if getattr(self.config, "use_pos_skipping", False) and self.training:
691
+ position_ids = torch.arange(new_input_embeds.size(1), device=new_input_embeds.device).unsqueeze(0).to(new_input_embeds.device)
692
+ split_position = random.randint(0, new_input_embeds.size(1))
693
+ left_add = random.randint(0, self.config.pos_skipping_range)
694
+ right_add = random.randint(left_add, self.config.pos_skipping_range)
695
+ position_ids[:, :split_position] += left_add
696
+ position_ids[:, split_position:] += right_add
697
+ # import pdb; pdb.set_trace()
698
+ return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
699
+
700
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
701
+ if model_args.mm_use_im_patch_token:
702
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
703
+ self.resize_token_embeddings(len(tokenizer))
704
+
705
+ if model_args.mm_use_im_start_end:
706
+ num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
707
+ self.resize_token_embeddings(len(tokenizer))
708
+
709
+ if num_new_tokens > 0:
710
+ input_embeddings = self.get_input_embeddings().weight.data
711
+ output_embeddings = self.get_output_embeddings().weight.data
712
+
713
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
714
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
715
+
716
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
717
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
718
+
719
+ if model_args.tune_mm_mlp_adapter:
720
+ for p in self.get_input_embeddings().parameters():
721
+ p.requires_grad = True
722
+ for p in self.get_output_embeddings().parameters():
723
+ p.requires_grad = False
724
+
725
+ if model_args.pretrain_mm_mlp_adapter:
726
+ mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location="cpu")
727
+ embed_tokens_weight = mm_projector_weights["model.embed_tokens.weight"]
728
+ assert num_new_tokens == 2
729
+ if input_embeddings.shape == embed_tokens_weight.shape:
730
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
731
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
732
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
733
+ else:
734
+ raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
735
+
736
+ elif model_args.mm_use_im_patch_token:
737
+ if model_args.tune_mm_mlp_adapter:
738
+ for p in self.get_input_embeddings().parameters():
739
+ p.requires_grad = False
740
+ for p in self.get_output_embeddings().parameters():
741
+ p.requires_grad = False
742
+
llava_qwen.py ADDED
@@ -0,0 +1,709 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Hao Zhang
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
+
16
+ from typing import List, Optional, Tuple, Union, Dict
17
+ import torch
18
+ import torch.nn as nn
19
+ from torch.nn import CrossEntropyLoss
20
+ import transformers
21
+ from transformers import AutoConfig, AutoModelForCausalLM, LlamaConfig, LlamaModel, LlamaForCausalLM
22
+ from transformers.modeling_outputs import CausalLMOutputWithPast
23
+ from transformers.generation.utils import GenerateOutput
24
+ from longva.longva.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
25
+ from .modeling_qwen2 import Qwen2Config, Qwen2Model, Qwen2ForCausalLM
26
+ import pdb
27
+ import time
28
+ import random
29
+ random.seed(42)
30
+ import torch
31
+ from statistics import mean
32
+ import torch.nn.functional as F
33
+ import PIL
34
+ from decord import VideoReader, cpu
35
+ from .conversation import conv_templates, SeparatorStyle
36
+ from .constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_IMAGE_TOKEN
37
+ from .mm_utils import tokenizer_image_token, load_video
38
+
39
+
40
+ class LlavaQwenConfig(Qwen2Config):
41
+ model_type = "llava_qwen"
42
+
43
+
44
+ class LlavaQwenModel(LlavaMetaModel, Qwen2Model):
45
+ config_class = LlavaQwenConfig
46
+
47
+ def __init__(self, config: Qwen2Config):
48
+ super(LlavaQwenModel, self).__init__(config)
49
+
50
+
51
+ class LlavaQwenForCausalLM(Qwen2ForCausalLM, LlavaMetaForCausalLM):
52
+ config_class = LlavaQwenConfig
53
+
54
+ def __init__(self, config):
55
+ # super(Qwen2ForCausalLM, self).__init__(config)
56
+ Qwen2ForCausalLM.__init__(self, config)
57
+ config.model_type = "llava_qwen"
58
+ config.rope_scaling = None
59
+
60
+ self.model = LlavaQwenModel(config)
61
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
62
+ # Initialize weights and apply final processing
63
+ self.post_init()
64
+
65
+ def get_model(self):
66
+ return self.model
67
+
68
+ def uniform_sampling(self, embeds, start_idx, end_idx, step):
69
+ indices = torch.arange(start_idx, end_idx, step).to(device=embeds.device)
70
+ return embeds.index_select(1, indices), indices
71
+ def pooling_sampling(self, embeds, start_idx, end_idx, step, pool_type='avg'):
72
+ selected = embeds[:, start_idx:end_idx, :]
73
+ B, D, L = selected.shape
74
+ kernel_size = step
75
+ stride = step
76
+
77
+ selected_transposed = selected.transpose(1, 2) # shape: (1, 12, 4)
78
+
79
+ if pool_type == 'avg_pool':
80
+ pooled = F.avg_pool1d(selected_transposed, kernel_size=kernel_size, stride=stride)
81
+ elif pool_type == 'max_pool':
82
+ pooled = F.max_pool1d(selected_transposed, kernel_size=kernel_size, stride=stride)
83
+ else:
84
+ raise ValueError(f"Unsupported pooling type: {pool_type}")
85
+
86
+ pooled = pooled.transpose(1, 2) # shape: (1, 2, 12)
87
+ return pooled, torch.arange(start_idx, start_idx + pooled.shape[1] * step, step).to(device=embeds.device)
88
+
89
+ def process_block(self, block_embeds, current_past_key_values=None, bsz=1, device=None, position_ids=None, key_position_ids=None):
90
+ if current_past_key_values is None:
91
+ seq_len = block_embeds.size(1)
92
+ position_ids = torch.arange(0, seq_len, device=device).expand(bsz, -1)
93
+ attention_mask = torch.ones((bsz, seq_len), device=device, dtype=torch.long)
94
+ else:
95
+ seq_len = block_embeds.size(1)
96
+ prefix_len = current_past_key_values[0][0].size(2)
97
+ attention_mask = torch.ones((bsz, prefix_len + seq_len), device=device, dtype=torch.long)
98
+
99
+
100
+ outputs = self.model(
101
+ inputs_embeds=block_embeds,
102
+ attention_mask=attention_mask,
103
+ position_ids=position_ids,
104
+ key_position_ids=key_position_ids,
105
+ past_key_values=current_past_key_values,
106
+ use_cache=True,
107
+ return_dict=True,
108
+ )
109
+ return outputs.past_key_values
110
+
111
+ def pooling_kvs(self, kvs, step):
112
+ # kvs shape: (bsz, 4, seq_len, head_dim)
113
+ kernel_size = step
114
+ stride = step
115
+ # kvs = kvs.transpose(2, 3)
116
+ # pooled_kvs = F.avg_pool1d(kvs, kernel_size=kernel_size, stride=stride)
117
+ kvs_permuted = kvs.permute(0, 1, 3, 2) # (batch_size, num_heads, feature_dim, sequence_length)
118
+ N_flat = kvs_permuted.shape[0] * kvs_permuted.shape[1]
119
+ C = kvs_permuted.shape[2]
120
+ L = kvs_permuted.shape[3]
121
+ kvs_for_pool = kvs_permuted.reshape(N_flat, C, L)
122
+ pooled_kvs = F.avg_pool1d(kvs_for_pool, kernel_size=kernel_size, stride=stride)
123
+ pooled_kvs_restored = pooled_kvs.view(kvs.shape[0], kvs.shape[1], pooled_kvs.shape[1], pooled_kvs.shape[2]).permute(0, 1, 3, 2)
124
+ return pooled_kvs_restored
125
+
126
+
127
+ def get_sparse_attention_mask(self, total_len, num_blocks, block_size, time_token_start_indices, time_token_end_indices, time_token_indices, visual_token_start_pos, visual_token_end_pos, attention_mask, inputs_embeds, prev_blocks_num=None):
128
+
129
+ causal_mask = torch.tril(torch.ones((total_len, total_len), dtype=torch.bool)).unsqueeze(0).repeat(1, 1, 1)
130
+ mask = torch.zeros(total_len, total_len, dtype=torch.bool)
131
+ start = visual_token_start_pos
132
+
133
+ record_block_start = []
134
+ for i in range(num_blocks):
135
+ next_time_token_pos = (i + 1)*block_size
136
+ if next_time_token_pos >= len(time_token_start_indices):
137
+ end = visual_token_end_pos
138
+ else:
139
+ end = time_token_start_indices[ next_time_token_pos ]
140
+
141
+ mask[start:end, start:end] = True
142
+
143
+ if len(record_block_start) >= prev_blocks_num:
144
+ prev_start = record_block_start[-prev_blocks_num]
145
+ else:
146
+ prev_start = visual_token_start_pos
147
+
148
+ mask[start:end, prev_start:start] = True
149
+ record_block_start.append(start)
150
+ start = end
151
+
152
+
153
+ mask[:, :visual_token_start_pos] = True
154
+ mask[visual_token_end_pos:, :] = True
155
+
156
+ for idx in time_token_indices:
157
+ mask[idx, :] = True
158
+ mask[:, idx] = True
159
+
160
+ causal_mask = torch.tril(torch.ones(total_len, total_len, dtype=torch.bool))
161
+ final_mask = (mask & causal_mask).unsqueeze(0).unsqueeze(0).to(dtype=attention_mask.dtype, device=attention_mask.device)
162
+
163
+ num_allowed = final_mask.sum().item()
164
+ upper_triangle_num = total_len * (total_len + 1) // 2
165
+ ratio = num_allowed / upper_triangle_num
166
+
167
+ invert_mask = 1.0 - final_mask
168
+ final_mask = ((1.0 - final_mask) * -1e9).to(dtype=inputs_embeds.dtype)
169
+ return final_mask, ratio
170
+
171
+
172
+ def cat_history_kvs(self, prefix_kvs, kvs_part2, kvs_part3):
173
+ prefix_kvs = [[kvs] for kvs in prefix_kvs]
174
+ cat_kvs = []
175
+ for prefix_kvs_this_layer, kvs_part2_this_layer, kvs_part3_this_layer in zip(prefix_kvs, kvs_part2, kvs_part3):
176
+ prefix_key_this_layer = [tmp[0] for tmp in prefix_kvs_this_layer]
177
+ prefix_val_this_layer = [tmp[1] for tmp in prefix_kvs_this_layer]
178
+
179
+ key_part2_this_layer = [tmp[0] for tmp in kvs_part2_this_layer]
180
+ val_part2_this_layer = [tmp[1] for tmp in kvs_part2_this_layer]
181
+
182
+ key_part3_this_layer = [tmp[0] for tmp in kvs_part3_this_layer]
183
+ val_part3_this_layer = [tmp[1] for tmp in kvs_part3_this_layer]
184
+
185
+ key_this_layer = torch.cat(prefix_key_this_layer + key_part2_this_layer + key_part3_this_layer, dim=-2)
186
+ val_this_layer = torch.cat(prefix_val_this_layer + val_part2_this_layer + val_part3_this_layer, dim=-2)
187
+
188
+ cat_kvs.append((key_this_layer, val_this_layer))
189
+ return cat_kvs
190
+
191
+ def forward_streaming(
192
+ self,
193
+ input_ids: torch.LongTensor = None,
194
+ attention_mask: Optional[torch.Tensor] = None,
195
+ position_ids: Optional[torch.LongTensor] = None,
196
+ key_position_ids: Optional[torch.LongTensor] = None,
197
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
198
+ inputs_embeds: Optional[torch.FloatTensor] = None,
199
+ labels: Optional[torch.LongTensor] = None,
200
+ use_cache: Optional[bool] = None,
201
+ output_attentions: Optional[bool] = None,
202
+ output_hidden_states: Optional[bool] = None,
203
+ return_dict: Optional[bool] = None,
204
+ dpo_forward: Optional[bool] = False,
205
+ cache_position=None,
206
+ visual_token_start_pos=None,
207
+ visual_token_end_pos=None,
208
+ time_token_start_indices=None,
209
+ frames_num=None,
210
+ time_token_indices=None,
211
+ time_token_end_indices=None,
212
+ block_size_chosed=None,
213
+ prev_blocks_num=None,
214
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
215
+
216
+ block_size = block_size_chosed
217
+ visual_token_start_pos = visual_token_start_pos
218
+ visual_token_end_pos = visual_token_end_pos
219
+ visual_len = visual_token_end_pos - visual_token_start_pos
220
+ num_blocks = (frames_num + block_size * 4 - 1) // (block_size * 4)
221
+ # print(f'block_size: {block_size}, num_blocks: {num_blocks}')
222
+
223
+ # streaming inps
224
+ blocks_positions = [[(0, 0, visual_token_start_pos)]]
225
+ frames_groups = [(0, visual_token_start_pos)]
226
+ for idx, (time_start, time_end) in enumerate(zip(time_token_start_indices, time_token_end_indices)):
227
+ if idx + 1 < len(time_token_start_indices):
228
+ frames_group_end = time_token_start_indices[idx + 1]
229
+ else:
230
+ frames_group_end = visual_token_end_pos
231
+ frames_groups.append(
232
+ (time_start, time_end, frames_group_end)
233
+ )
234
+
235
+ single_block = []
236
+ for group in frames_groups[1:]:
237
+ single_block.append(group)
238
+ if len(single_block) == block_size:
239
+ blocks_positions.append(single_block)
240
+ single_block = []
241
+ if len(single_block) != 0:
242
+ blocks_positions.append(single_block)
243
+ num_blocks = len(blocks_positions)
244
+
245
+ start = time.time()
246
+ record_prefill_time = 0
247
+
248
+ full_inputs_embeds = inputs_embeds
249
+ bsz, total_len, embed_dim = full_inputs_embeds.size()
250
+ device = full_inputs_embeds.device
251
+
252
+ prefix_embeds = full_inputs_embeds[:, :visual_token_start_pos, :]
253
+ visual_embeds = full_inputs_embeds[:, visual_token_start_pos:visual_token_end_pos, :]
254
+ suffix_embeds = full_inputs_embeds[:, visual_token_end_pos:, :]
255
+ num_visual_tokens = visual_embeds.size(1)
256
+
257
+ all_past_key_values = [[] for _ in range(len(self.model.layers))] # 假设 model 有 layers 属性
258
+ prefix_past_key_values = []
259
+
260
+ torch.cuda.reset_peak_memory_stats()
261
+
262
+ if prefix_embeds.size(1) > 0:
263
+ pkv = self.process_block(prefix_embeds, bsz=bsz, device=device)
264
+ for i in range(len(pkv)):
265
+ all_past_key_values[i].append(pkv[i])
266
+ prefix_past_key_values.append(pkv[i])
267
+
268
+ prev_blocks = blocks_positions[1:1+prev_blocks_num]
269
+ prev_the_first_block = prev_blocks[0]
270
+ prev_b_start = prev_the_first_block[0][0]
271
+ prev_the_last_block = prev_blocks[-1]
272
+ prev_b_end = prev_the_last_block[-1][-1]
273
+
274
+ block_streaming_past_key_values = prefix_past_key_values
275
+
276
+ query_position_ids = torch.arange(prev_b_start, prev_b_end, dtype=torch.long, device=device)
277
+ past_key_position_ids = torch.arange(0, block_streaming_past_key_values[0][0].size(2), dtype=torch.long, device=device)
278
+ key_position_ids = torch.cat([past_key_position_ids, query_position_ids], dim=0)
279
+
280
+ visual_embeds_this_block = full_inputs_embeds[:,prev_b_start:prev_b_end,:]
281
+ pkv = self.process_block(visual_embeds_this_block, current_past_key_values=block_streaming_past_key_values, bsz=bsz, device=device, position_ids=query_position_ids.unsqueeze(0), key_position_ids=key_position_ids.unsqueeze(0))
282
+
283
+ for i in range(len(pkv)):
284
+ for block in prev_blocks:
285
+ block_start, _, _ = block[0]
286
+ _, _, block_end = block[-1]
287
+ all_past_key_values[i].append( (pkv[i][0][:,:,block_start:block_end], pkv[i][1][:,:,block_start:block_end]) )
288
+
289
+ block_streaming_past_key_values_part1 = prefix_past_key_values
290
+ position_ids_part1 = torch.arange(0, prefix_past_key_values[0][0].size(2), dtype=torch.long, device=device)
291
+ block_streaming_past_key_values_part2 = [[] for _ in range(len(self.model.layers))] # 存
292
+ position_ids_part2 = torch.tensor([], dtype=torch.long, device=device)
293
+ block_streaming_past_key_values_part3=None
294
+ position_ids_part3 = None
295
+
296
+ query_position_ids = None
297
+ for idx, single_block in enumerate(blocks_positions[:]):
298
+ if idx == 0:
299
+ continue
300
+ if idx <= prev_blocks_num:
301
+ continue
302
+
303
+ b_start, _, _ = single_block[0]
304
+ _, _, b_end = single_block[-1]
305
+ visual_embeds_this_block = full_inputs_embeds[:,b_start:b_end,:]
306
+ prev_blocks = blocks_positions[max(idx - prev_blocks_num, 1):idx]
307
+ prev_the_first_block = prev_blocks[0]
308
+ prev_b_start = prev_the_first_block[0][0]
309
+
310
+ this_block_length = b_end - prev_b_start
311
+ prev_block_length = b_start - prev_b_start
312
+ true_block_length = b_end - b_start
313
+
314
+ block_streaming_past_key_values_part3 = [tmp[-prev_blocks_num:] for tmp in all_past_key_values]
315
+ # block_streaming_past_key_values_part3 = [
316
+ # [
317
+ # (t[0].to(device=device), t[1].to(device=device))
318
+ # for t in sublist
319
+ # ]
320
+ # for sublist in block_streaming_past_key_values_part3
321
+ # ]
322
+
323
+ block_streaming_past_key_values = self.cat_history_kvs(block_streaming_past_key_values_part1, block_streaming_past_key_values_part2, block_streaming_past_key_values_part3)
324
+
325
+ query_position_ids = torch.arange(b_start, b_end, dtype=torch.long, device=device)
326
+ position_ids_part3 = torch.arange(prev_b_start, b_start, dtype=torch.long, device=device)
327
+ key_position_ids = torch.cat([position_ids_part1, position_ids_part2, position_ids_part3, query_position_ids], dim=0)
328
+
329
+ start_1 = time.time()
330
+ pkv = self.process_block(visual_embeds_this_block, current_past_key_values=block_streaming_past_key_values, bsz=bsz, device=device, position_ids=query_position_ids.unsqueeze(0), key_position_ids=key_position_ids.unsqueeze(0))
331
+ end_1 = time.time()
332
+
333
+ record_prefill_time += end_1-start_1
334
+
335
+ for i in range(len(pkv)):
336
+ length_before_chunk = block_streaming_past_key_values[i][0].size(2)
337
+ key_this_block, val_this_block = pkv[i]
338
+ key_this_block = key_this_block[:,:,length_before_chunk:,:]
339
+ val_this_block = val_this_block[:,:,length_before_chunk:,:]
340
+ all_past_key_values[i].append( (key_this_block, val_this_block) )
341
+ # all_past_key_values[i].append( (key_this_block.to('cpu'), val_this_block.to('cpu')) )
342
+
343
+ time_keys_list = []
344
+ time_vals_list = []
345
+
346
+ extract_timestamps_position_ids_list = []
347
+ for group in prev_the_first_block:
348
+ time_start, time_end, _ = group
349
+ extract_timestamps_position_ids_list.append(torch.arange(time_start, time_end, dtype=torch.long, device=device))
350
+
351
+ time_start = time_start - prev_b_start
352
+ time_end = time_end - prev_b_start
353
+
354
+ time_keys_list.append(block_streaming_past_key_values_part3[i][0][0][:,:,time_start:time_end,:])
355
+ time_vals_list.append(block_streaming_past_key_values_part3[i][0][1][:,:,time_start:time_end,:])
356
+
357
+ time_keys = torch.cat(time_keys_list, dim=2)
358
+ time_vals = torch.cat(time_vals_list, dim=2)
359
+
360
+ block_streaming_past_key_values_part2[i].append( (time_keys, time_vals) )
361
+
362
+ if i == 0:
363
+ position_ids_part2 = torch.cat([position_ids_part2] + extract_timestamps_position_ids_list, dim=0)
364
+
365
+
366
+ merged_pkv = []
367
+ for layer_pkvs in all_past_key_values:
368
+ if not layer_pkvs:
369
+ continue
370
+ keys = torch.cat([pkv[0].to(device=device) for pkv in layer_pkvs], dim=2) # dim=2 是 sequence 维度
371
+ values = torch.cat([pkv[1].to(device=device) for pkv in layer_pkvs], dim=2)
372
+ merged_pkv.append((keys, values))
373
+
374
+
375
+ pkv = merged_pkv
376
+ del block_streaming_past_key_values
377
+ del all_past_key_values
378
+ del block_streaming_past_key_values_part1
379
+ del block_streaming_past_key_values_part2
380
+ del block_streaming_past_key_values_part3
381
+ torch.cuda.empty_cache()
382
+
383
+ # TODO: bi-decoding acceleration
384
+ mixed_prefill_past_key_values = pkv
385
+ prefill_len = visual_token_end_pos
386
+
387
+ # Process suffix
388
+ if suffix_embeds.size(1) > 0:
389
+ seq_len = suffix_embeds.size(1)
390
+ total_len = prefill_len + seq_len
391
+ position_ids = torch.arange(prefill_len, total_len, device=device, dtype=torch.long).expand(bsz, -1)
392
+ key_position_ids = torch.arange(0, total_len, device=device, dtype=torch.long).expand(bsz, -1)
393
+ attention_mask = torch.ones((bsz, total_len), device=device, dtype=torch.long)
394
+
395
+ outputs = super().forward(
396
+ inputs_embeds=suffix_embeds,
397
+ attention_mask=attention_mask,
398
+ position_ids=position_ids,
399
+ key_position_ids=key_position_ids,
400
+ past_key_values=mixed_prefill_past_key_values,
401
+ output_attentions=output_attentions,
402
+ output_hidden_states=output_hidden_states,
403
+ use_cache=True,
404
+ return_dict=return_dict,
405
+ # blocks_positions=None,
406
+ )
407
+ del mixed_prefill_past_key_values
408
+ torch.cuda.empty_cache()
409
+
410
+ return outputs
411
+ def forward_mask(
412
+ self,
413
+ input_ids: torch.LongTensor = None,
414
+ attention_mask: Optional[torch.Tensor] = None,
415
+ position_ids: Optional[torch.LongTensor] = None,
416
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
417
+ inputs_embeds: Optional[torch.FloatTensor] = None,
418
+ labels: Optional[torch.LongTensor] = None,
419
+ use_cache: Optional[bool] = None,
420
+ output_attentions: Optional[bool] = None,
421
+ output_hidden_states: Optional[bool] = None,
422
+ return_dict: Optional[bool] = None,
423
+ dpo_forward: Optional[bool] = False,
424
+ cache_position=None,
425
+ visual_token_start_pos=None,
426
+ visual_token_end_pos=None,
427
+ time_token_start_indices=None,
428
+ time_token_end_indices=None,
429
+ frames_num=None,
430
+ time_token_indices=None,
431
+ prev_blocks_num=None,
432
+ block_size_chosed=None
433
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
434
+ bsz, total_len, embed_dim = inputs_embeds.size()
435
+ visual_token_start_pos = visual_token_start_pos
436
+ visual_token_end_pos = visual_token_end_pos
437
+ visual_len = visual_token_end_pos - visual_token_start_pos
438
+
439
+ block_size_list = [2,4,8,16,32]
440
+ best_block_size = None
441
+ min_diff = float('inf')
442
+
443
+ block_size = block_size_chosed
444
+ num_blocks = (frames_num + block_size * 4 - 1) // (block_size * 4)
445
+ final_mask, ratio = self.get_sparse_attention_mask(total_len, num_blocks, block_size, time_token_start_indices, time_token_end_indices, time_token_indices, visual_token_start_pos, visual_token_end_pos, attention_mask, inputs_embeds, prev_blocks_num)
446
+
447
+ # print(f'frames:{frames_num}, block_num:{num_blocks}, bsz:{block_size}, prev_blocks_num:{prev_blocks_num}, ratio:{ratio}')
448
+
449
+ return super().forward(
450
+ input_ids=input_ids,
451
+ attention_mask=final_mask, # final_mask
452
+ position_ids=position_ids,
453
+ past_key_values=past_key_values,
454
+ inputs_embeds=inputs_embeds,
455
+ labels=labels,
456
+ use_cache=use_cache,
457
+ output_attentions=output_attentions,
458
+ output_hidden_states=output_hidden_states,
459
+ return_dict=return_dict,
460
+ )
461
+
462
+ def forward(
463
+ self,
464
+ input_ids: torch.LongTensor = None,
465
+ attention_mask: Optional[torch.Tensor] = None,
466
+ position_ids: Optional[torch.LongTensor] = None,
467
+ key_position_ids: Optional[torch.LongTensor] = None,
468
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
469
+ inputs_embeds: Optional[torch.FloatTensor] = None,
470
+ labels: Optional[torch.LongTensor] = None,
471
+ use_cache: Optional[bool] = None,
472
+ output_attentions: Optional[bool] = None,
473
+ output_hidden_states: Optional[bool] = None,
474
+ images: Optional[torch.FloatTensor] = None,
475
+ image_sizes: Optional[List[List[int]]] = None,
476
+ return_dict: Optional[bool] = None,
477
+ modalities: Optional[List[str]] = ["image"],
478
+ dpo_forward: Optional[bool] = False,
479
+ cache_position=None,
480
+ time_embedding=None,
481
+ visual_token_start_pos=None,
482
+ visual_token_end_pos=None,
483
+ time_token_start_indices=None,
484
+ frames_num=None,
485
+ time_token_indices=None,
486
+ time_token_end_indices=None,
487
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
488
+
489
+ if input_ids is not None and input_ids.size(1) == 1:
490
+ past_key_len = past_key_values[0][0].size(-2)
491
+ key_position_ids = torch.arange(0, past_key_len+1, device=position_ids.device,dtype=torch.long).expand(1, -1)
492
+ if position_ids[0][0] != past_key_len:
493
+ position_ids = torch.tensor([[past_key_len]]).to(device=position_ids.device, dtype=position_ids.dtype)
494
+ key_position_ids = torch.arange(0, past_key_len+1, device=position_ids.device,dtype=torch.long).expand(1, -1)
495
+
496
+ return super().forward(
497
+ input_ids=input_ids,
498
+ attention_mask=attention_mask,
499
+ position_ids=position_ids,
500
+ key_position_ids=key_position_ids,
501
+ past_key_values=past_key_values,
502
+ inputs_embeds=inputs_embeds,
503
+ labels=labels,
504
+ use_cache=use_cache,
505
+ output_attentions=output_attentions,
506
+ output_hidden_states=output_hidden_states,
507
+ return_dict=return_dict,
508
+ )
509
+
510
+ if inputs_embeds is None:
511
+ (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, time_embedding)
512
+
513
+ if self.config.enable_sparse:
514
+ block_size_chosed = self.config.sparse_config['block_size_chosed']
515
+ prev_blocks_num = self.config.sparse_config['prev_blocks_num']
516
+ if self.config.sparse_mode=='streaming':
517
+ return self.forward_streaming(
518
+ input_ids=input_ids,
519
+ attention_mask=attention_mask,
520
+ position_ids=position_ids,
521
+ key_position_ids=key_position_ids,
522
+ past_key_values=past_key_values,
523
+ inputs_embeds=inputs_embeds,
524
+ labels=labels,
525
+ use_cache=use_cache,
526
+ output_attentions=output_attentions,
527
+ output_hidden_states=output_hidden_states,
528
+ return_dict=return_dict,
529
+ cache_position=cache_position,
530
+ visual_token_start_pos=visual_token_start_pos,
531
+ visual_token_end_pos=visual_token_end_pos,
532
+ time_token_start_indices=time_token_start_indices,
533
+ frames_num=frames_num,
534
+ time_token_indices=time_token_indices,
535
+ time_token_end_indices=time_token_end_indices,
536
+ block_size_chosed=block_size_chosed,
537
+ prev_blocks_num=prev_blocks_num,
538
+ )
539
+ elif self.config.sparse_mode=='mask':
540
+ return self.forward_mask(
541
+ input_ids=input_ids,
542
+ attention_mask=attention_mask,
543
+ position_ids=position_ids,
544
+ past_key_values=past_key_values,
545
+ inputs_embeds=inputs_embeds,
546
+ labels=labels,
547
+ use_cache=use_cache,
548
+ output_attentions=output_attentions,
549
+ output_hidden_states=output_hidden_states,
550
+ return_dict=return_dict,
551
+ cache_position=cache_position,
552
+ visual_token_start_pos=visual_token_start_pos,
553
+ visual_token_end_pos=visual_token_end_pos,
554
+ time_token_start_indices=time_token_start_indices,
555
+ frames_num=frames_num,
556
+ time_token_indices=time_token_indices,
557
+ time_token_end_indices=time_token_end_indices,
558
+ block_size_chosed=block_size_chosed,
559
+ prev_blocks_num=prev_blocks_num,
560
+ )
561
+ else:
562
+ return super().forward(
563
+ input_ids=input_ids,
564
+ attention_mask=attention_mask,
565
+ position_ids=position_ids,
566
+ past_key_values=past_key_values,
567
+ inputs_embeds=inputs_embeds,
568
+ labels=labels,
569
+ use_cache=use_cache,
570
+ output_attentions=output_attentions,
571
+ output_hidden_states=output_hidden_states,
572
+ return_dict=return_dict,
573
+ )
574
+
575
+
576
+ @torch.no_grad()
577
+ def generate(
578
+ self,
579
+ inputs: Optional[torch.Tensor] = None,
580
+ images: Optional[torch.Tensor] = None,
581
+ image_sizes: Optional[torch.Tensor] = None,
582
+ modalities: Optional[List[str]] = ["image"],
583
+ time_embedding=None,
584
+ **kwargs,
585
+ ) -> Union[GenerateOutput, torch.LongTensor]:
586
+
587
+ position_ids = kwargs.pop("position_ids", None)
588
+ attention_mask = kwargs.pop("attention_mask", None)
589
+
590
+ if "inputs_embeds" in kwargs:
591
+ raise NotImplementedError("`inputs_embeds` is not supported")
592
+
593
+ if images is not None and images[0].size(0) > 0:
594
+ IMAGE_TOKEN_INDEX = -200
595
+ TOKEN_PERFRAME = 36
596
+ frames_num = images[0].size(0)
597
+ visual_token_start_pos = (inputs == IMAGE_TOKEN_INDEX).nonzero(as_tuple=True)[1].item()
598
+ num_tokens = time_embedding[0].size(0)
599
+ visual_token_end_pos = visual_token_start_pos + num_tokens
600
+ kwargs['visual_token_start_pos'] = visual_token_start_pos
601
+ kwargs['visual_token_end_pos'] = visual_token_end_pos
602
+ # time_token_start_indices = (time_embedding[0] == 1462).nonzero(as_tuple=True)
603
+ time_token_start_indices = (time_embedding[0] == 1462).nonzero(as_tuple=True)[0].cpu().tolist()
604
+ kwargs['time_token_start_indices'] = [idx + visual_token_start_pos for idx in time_token_start_indices]
605
+ # kwargs['time_token_start_indices'] = time_token_start_indices + visual_token_start_pos
606
+ kwargs['frames_num'] = frames_num
607
+ time_token_indices = (time_embedding[0] != 151654).nonzero(as_tuple=True)[0].cpu().tolist()
608
+ kwargs['time_token_indices'] = [idx + visual_token_start_pos for idx in time_token_indices]
609
+ time_token_end_indices = (time_embedding[0] == 25).nonzero(as_tuple=True)[0].cpu().tolist()
610
+ kwargs['time_token_end_indices'] = [idx + visual_token_start_pos + 1 for idx in time_token_end_indices]
611
+ # kwargs['time_token_end_indices'] = time_token_end_indices + visual_token_start_pos
612
+
613
+ #print(images[0].shape)
614
+ if images is not None:
615
+ (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,time_embedding=time_embedding)
616
+
617
+ else:
618
+ inputs_embeds = self.get_model().embed_tokens(inputs)
619
+
620
+ #print(inputs_embeds.shape)
621
+ return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs)
622
+
623
+ @torch.no_grad()
624
+ def chat(self,
625
+ video_path,
626
+ tokenizer,
627
+ user_prompt,
628
+ chat_history=None,
629
+ return_history=True,
630
+ max_num_frames=512,
631
+ sample_fps=1,
632
+ max_sample_fps=4,
633
+ generation_config={}):
634
+
635
+ # prepare text input
636
+ conv = conv_templates["qwen_1_5"].copy()
637
+ if chat_history is None or len(chat_history) == 0:
638
+ user_prompt = f'{DEFAULT_IMAGE_TOKEN}\n{user_prompt}'
639
+ else:
640
+ assert DEFAULT_IMAGE_TOKEN in chat_history[0]['content'], chat_history
641
+ for msg in chat_history:
642
+ conv.append_message(msg['role'], msg['content'])
643
+
644
+ conv.append_message(conv.roles[0], user_prompt)
645
+ conv.append_message(conv.roles[1], None)
646
+ prompt = conv.get_prompt()
647
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(self.model.device)
648
+
649
+ # prepare video input
650
+ frames, timestamps = load_video(video_path, max_num_frames, fps=sample_fps, max_fps=max_sample_fps)
651
+
652
+ time_stamps=[]
653
+ token_frames_sum=(len(timestamps)+3)//4
654
+ compress_frame = timestamps[::4]
655
+ time_embedding = []
656
+ for time in compress_frame:
657
+ item = f"Time {time}s:"
658
+ time_embedding.append(tokenizer(item).input_ids)
659
+ time_embedding.append([151654]*144)
660
+
661
+ time_embedding = [item for sublist in time_embedding for item in sublist]
662
+ time_embedding = torch.tensor(time_embedding, dtype=torch.long).to(self.model.device)
663
+ time_stamps.append(time_embedding)
664
+
665
+ video_tensor = self.get_vision_tower().image_processor.preprocess(frames, return_tensors="pt")["pixel_values"].to(self.model.device, dtype=torch.float16)
666
+
667
+ with torch.inference_mode():
668
+ output_ids = self.generate(input_ids, images=[video_tensor],time_embedding=time_stamps, modalities=["video"], **generation_config)
669
+
670
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
671
+
672
+ if chat_history is None:
673
+ chat_history = []
674
+
675
+ chat_history.append({"role":conv.roles[0], "content":user_prompt})
676
+ chat_history.append({"role":conv.roles[1], "content":outputs})
677
+ if return_history:
678
+ return outputs, chat_history
679
+ else:
680
+ return outputs
681
+
682
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
683
+ images = kwargs.pop("images", None)
684
+ image_sizes = kwargs.pop("image_sizes", None)
685
+ visual_token_start_pos = kwargs.get("visual_token_start_pos", None)
686
+ visual_token_end_pos = kwargs.get("visual_token_end_pos", None)
687
+ time_token_start_indices = kwargs.get("time_token_start_indices", None)
688
+ frames_num = kwargs.get("frames_num", None)
689
+ time_token_indices = kwargs.get("time_token_indices", None)
690
+ time_token_end_indices = kwargs.get("time_token_end_indices", None)
691
+
692
+ inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs)
693
+
694
+ inputs["visual_token_start_pos"] = visual_token_start_pos
695
+ inputs["visual_token_end_pos"] = visual_token_end_pos
696
+ inputs["time_token_start_indices"] = time_token_start_indices
697
+ inputs["frames_num"] = frames_num
698
+ inputs["time_token_indices"] = time_token_indices
699
+ inputs["time_token_end_indices"] = time_token_end_indices
700
+
701
+ if images is not None:
702
+ inputs["images"] = images
703
+ if image_sizes is not None:
704
+ inputs["image_sizes"] = image_sizes
705
+ return inputs
706
+
707
+
708
+ AutoConfig.register("llava_qwen", LlavaQwenConfig)
709
+ AutoModelForCausalLM.register(LlavaQwenConfig, LlavaQwenConfig)
mm_utils.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 pdb
11
+ import numpy as np
12
+
13
+ def transform_input_id(input_ids,num_tokens,special_token):
14
+ start_value = -200
15
+ insert_index = (input_ids == start_value).nonzero(as_tuple=True)[1][0].item()
16
+ negative_tokens = torch.arange(start_value, start_value - num_tokens, -1, device=input_ids.device)
17
+ before_input_ids = input_ids[:, :insert_index]
18
+ after_input_ids = input_ids[:, insert_index + 1:]
19
+ input_ids = torch.cat((before_input_ids, negative_tokens.unsqueeze(0), after_input_ids), dim=1)
20
+ input_ids[input_ids < 0] = special_token
21
+ return input_ids
22
+
23
+ def resize_and_center_crop(image, shortest_edge_length):
24
+ # Calculate new dimensions and resize
25
+ aspect_ratio = float(image.width) / float(image.height)
26
+ if aspect_ratio > 1:
27
+ new_width = int(shortest_edge_length * aspect_ratio)
28
+ new_height = shortest_edge_length
29
+ else:
30
+ new_width = shortest_edge_length
31
+ new_height = int(shortest_edge_length / aspect_ratio)
32
+ resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
33
+
34
+ # Calculate the position and perform the center crop
35
+ left = (new_width - shortest_edge_length) / 2
36
+ top = (new_height - shortest_edge_length) / 2
37
+ right = (new_width + shortest_edge_length) / 2
38
+ bottom = (new_height + shortest_edge_length) / 2
39
+ cropped_image = resized_image.crop((left, top, right, bottom))
40
+
41
+ return cropped_image
42
+
43
+
44
+ def auto_pad_images(image, grid_params):
45
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
46
+ assert len(grid_params) > 0, "Grid parameters should not be empty"
47
+
48
+ # Step 1: Calculate and find the closest aspect ratio
49
+ input_width, input_height = image.size
50
+ input_aspect_ratio = input_width / input_height
51
+ candidate_resolutions = [(w / h, w, h) for w in grid_params for h in grid_params]
52
+ closest_aspect_ratio = min(candidate_resolutions, key=lambda x: abs(input_aspect_ratio - x[0]))
53
+
54
+ candidate_resolutions = [(x[1], x[2]) for x in candidate_resolutions if abs(x[0] - closest_aspect_ratio[0]) < 1e-3]
55
+
56
+ target_resolution = min(candidate_resolutions, key=lambda res: abs(max(input_width, input_height) / max(res) - 1))
57
+
58
+ resize_width, resize_height = target_resolution
59
+ if input_width > input_height:
60
+ resize_height = int(resize_width / input_aspect_ratio)
61
+ else:
62
+ resize_width = int(resize_height * input_aspect_ratio)
63
+ resized_image = image.resize((resize_width, resize_height), Image.ANTIALIAS)
64
+
65
+ # Step 5: Pad the resized image if necessary to match the target resolution
66
+ pad_width = target_resolution[0] - resize_width
67
+ pad_height = target_resolution[1] - resize_height
68
+ padded_image = Image.new("RGB", target_resolution, color=(0, 0, 0))
69
+ padded_image.paste(resized_image, (pad_width // 2, pad_height // 2))
70
+
71
+ return padded_image
72
+
73
+
74
+ def extract_patches(image, patch_size, overlap_ratio):
75
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
76
+ assert patch_size > 0, "Patch size should be greater than 0"
77
+ assert 0 <= overlap_ratio < 1, "Overlap ratio should be between 0 and 1"
78
+
79
+ W, H = image.size
80
+ patches = []
81
+
82
+ stride = int(patch_size * (1 - overlap_ratio))
83
+
84
+ num_patches_y = (H - patch_size) // stride + 1
85
+ num_patches_x = (W - patch_size) // stride + 1
86
+
87
+ y_start = (H - (num_patches_y - 1) * stride - patch_size) // 2
88
+ x_start = (W - (num_patches_x - 1) * stride - patch_size) // 2
89
+
90
+ for y in range(y_start, y_start + num_patches_y * stride, stride):
91
+ for x in range(x_start, x_start + num_patches_x * stride, stride):
92
+ patch = image.crop((x, y, x + patch_size, y + patch_size))
93
+ patches.append(patch)
94
+
95
+ return patches
96
+
97
+
98
+ def process_highres_image_crop_split(image, data_args, processor=None):
99
+ crop_resolution = data_args.image_crop_resolution
100
+ split_resolution = data_args.image_split_resolution
101
+ if processor is None:
102
+ processor = data_args.image_processor
103
+ image_crop = resize_and_center_crop(image, crop_resolution)
104
+ image_patches = extract_patches(image_crop, patch_size=split_resolution, overlap_ratio=0)
105
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
106
+ return torch.stack(image_patches, dim=0)
107
+
108
+
109
+ def process_highres_image(image, processor, grid_pinpoints):
110
+ grid_params = [int(x) for x in grid_pinpoints.split(",")]
111
+ width_height = max(image.size)
112
+ fit_grid_params = [x for x in grid_params if x >= width_height]
113
+ if len(fit_grid_params) == 0:
114
+ select_size = max(grid_params)
115
+ else:
116
+ select_size = min(fit_grid_params)
117
+ # FIXME: always select the 448
118
+ select_size = max(grid_params)
119
+ image_padded = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
120
+
121
+ # FIXME: this seems to be a bug that it always resizes instead of padding
122
+ image_original_resize = image.resize((processor.size["shortest_edge"], processor.size["shortest_edge"]))
123
+ image_padded = image_padded.resize((select_size, select_size))
124
+ image_patches = extract_patches(image_padded, patch_size=processor.size["shortest_edge"], overlap_ratio=0)
125
+ image_patches = [image_original_resize] + image_patches
126
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
127
+ return torch.stack(image_patches, dim=0)
128
+
129
+
130
+ def select_best_resolution(original_size, possible_resolutions):
131
+ """
132
+ Selects the best resolution from a list of possible resolutions based on the original size.
133
+
134
+ Args:
135
+ original_size (tuple): The original size of the image in the format (width, height).
136
+ possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
137
+
138
+ Returns:
139
+ tuple: The best fit resolution in the format (width, height).
140
+ """
141
+ original_width, original_height = original_size
142
+ best_fit = None
143
+ max_effective_resolution = 0
144
+ min_wasted_resolution = float("inf")
145
+
146
+ for width, height in possible_resolutions:
147
+ # Calculate the downscaled size to keep the aspect ratio
148
+ scale = min(width / original_width, height / original_height)
149
+ downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
150
+
151
+ # Calculate effective and wasted resolutions
152
+ effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
153
+ wasted_resolution = (width * height) - effective_resolution
154
+
155
+ if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
156
+ max_effective_resolution = effective_resolution
157
+ min_wasted_resolution = wasted_resolution
158
+ best_fit = (width, height)
159
+
160
+ return best_fit
161
+
162
+
163
+ def resize_and_pad_image(image, target_resolution):
164
+ """
165
+ Resize and pad an image to a target resolution while maintaining aspect ratio.
166
+
167
+ Args:
168
+ image (PIL.Image.Image): The input image.
169
+ target_resolution (tuple): The target resolution (width, height) of the image.
170
+
171
+ Returns:
172
+ PIL.Image.Image: The resized and padded image.
173
+ """
174
+ original_width, original_height = image.size
175
+ target_width, target_height = target_resolution
176
+
177
+ # Determine which dimension (width or height) to fill
178
+ scale_w = target_width / original_width
179
+ scale_h = target_height / original_height
180
+
181
+ if scale_w < scale_h:
182
+ # Width will be filled completely
183
+ new_width = target_width
184
+ new_height = min(math.ceil(original_height * scale_w), target_height)
185
+ else:
186
+ # Height will be filled completely
187
+ new_height = target_height
188
+ new_width = min(math.ceil(original_width * scale_h), target_width)
189
+
190
+ # Resize the image
191
+ resized_image = image.resize((new_width, new_height))
192
+
193
+ # Create a new image with the target size and paste the resized image onto it
194
+ new_image = Image.new("RGB", (target_width, target_height), (0, 0, 0))
195
+ paste_x = (target_width - new_width) // 2
196
+ paste_y = (target_height - new_height) // 2
197
+ new_image.paste(resized_image, (paste_x, paste_y))
198
+
199
+ return new_image
200
+
201
+
202
+ def divide_to_patches(image, patch_size):
203
+ """
204
+ Divides an image into patches of a specified size.
205
+
206
+ Args:
207
+ image (PIL.Image.Image): The input image.
208
+ patch_size (int): The size of each patch.
209
+
210
+ Returns:
211
+ list: A list of PIL.Image.Image objects representing the patches.
212
+ """
213
+ patches = []
214
+ width, height = image.size
215
+ for i in range(0, height, patch_size):
216
+ for j in range(0, width, patch_size):
217
+ box = (j, i, j + patch_size, i + patch_size)
218
+ patch = image.crop(box)
219
+ patches.append(patch)
220
+
221
+ return patches
222
+
223
+
224
+ def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
225
+ """
226
+ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
227
+
228
+ Args:
229
+ image_size (tuple): The size of the input image in the format (width, height).
230
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
231
+ patch_size (int): The size of each image patch.
232
+
233
+ Returns:
234
+ tuple: The shape of the image patch grid in the format (width, height).
235
+ """
236
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
237
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
238
+ # Use regex to extract the range from the input string
239
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
240
+ range_start = tuple(map(int, matches[0]))
241
+ range_end = tuple(map(int, matches[-1]))
242
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
243
+ 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)]
244
+ # Multiply all elements by patch_size
245
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
246
+ if type(grid_pinpoints) is list:
247
+ possible_resolutions = grid_pinpoints
248
+ else:
249
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
250
+ width, height = select_best_resolution(image_size, possible_resolutions)
251
+ return width // patch_size, height // patch_size
252
+
253
+
254
+ def process_anyres_image(image, processor, grid_pinpoints):
255
+ """
256
+ Process an image with variable resolutions.
257
+
258
+ Args:
259
+ image (PIL.Image.Image): The input image to be processed.
260
+ processor: The image processor object.
261
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
262
+
263
+ Returns:
264
+ torch.Tensor: A tensor containing the processed image patches.
265
+ """
266
+ # Convert grid_pinpoints from string to list
267
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
268
+ try:
269
+ patch_size = processor.size[0]
270
+ except Exception as e:
271
+ patch_size = processor.size["shortest_edge"]
272
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
273
+ #print(patch_size)
274
+ # Use regex to extract the range from the input string
275
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
276
+ range_start = tuple(map(int, matches[0]))
277
+ range_end = tuple(map(int, matches[-1]))
278
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
279
+ 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)]
280
+ # Multiply all elements by patch_size
281
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
282
+
283
+ if type(grid_pinpoints) is list:
284
+ possible_resolutions = grid_pinpoints
285
+ else:
286
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
287
+ best_resolution = select_best_resolution(image.size, possible_resolutions)
288
+ image_padded = resize_and_pad_image(image, best_resolution)
289
+
290
+ patches = divide_to_patches(image_padded, processor.crop_size["height"])
291
+
292
+ # FIXME: this seems to be a bug that it resizes instead of pad.
293
+ # but to keep it consistent with previous, i will keep it as it is
294
+ # TODO: uncomment below to ablate with the padding
295
+ if isinstance(processor.size, dict):
296
+ shortest_edge = processor.size["shortest_edge"]
297
+ else:
298
+ shortest_edge = min(processor.size)
299
+ image_original_resize = image.resize((shortest_edge, shortest_edge))
300
+ # image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
301
+ # image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
302
+
303
+ image_patches = [image_original_resize] + patches
304
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
305
+ return torch.stack(image_patches, dim=0)
306
+
307
+
308
+ def load_image_from_base64(image):
309
+ return Image.open(BytesIO(base64.b64decode(image)))
310
+
311
+
312
+ def expand2square(pil_img, background_color):
313
+ width, height = pil_img.size
314
+ if width == height:
315
+ return pil_img
316
+ elif width > height:
317
+ result = Image.new(pil_img.mode, (width, width), background_color)
318
+ result.paste(pil_img, (0, (width - height) // 2))
319
+ return result
320
+ else:
321
+ result = Image.new(pil_img.mode, (height, height), background_color)
322
+ result.paste(pil_img, ((height - width) // 2, 0))
323
+ return result
324
+
325
+ def process_images_mvbench(images, image_processor, model_cfg):
326
+ image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
327
+ new_images = []
328
+
329
+ for image in images:
330
+ image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean))
331
+ image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
332
+ new_images.append(image)
333
+
334
+ if all(x.shape == new_images[0].shape for x in new_images):
335
+ new_images = torch.stack(new_images, dim=0)
336
+ return new_images
337
+ def process_images(images, image_processor, model_cfg):
338
+ image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
339
+ new_images = []
340
+ if image_aspect_ratio == "highres":
341
+ for image in images:
342
+ image = process_highres_image(image, image_processor, model_cfg.image_grid_pinpoints)
343
+ new_images.append(image)
344
+ elif image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio:
345
+ for image in images:
346
+ image = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints)
347
+ new_images.append(image)
348
+ elif image_aspect_ratio == "crop_split":
349
+ for image in images:
350
+ image = process_highres_image_crop_split(image, model_cfg, image_processor)
351
+ new_images.append(image)
352
+ elif image_aspect_ratio == "pad":
353
+ for image in images:
354
+ image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean))
355
+ image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
356
+ new_images.append(image)
357
+ else:
358
+ return image_processor(images, return_tensors="pt")["pixel_values"]
359
+ if all(x.shape == new_images[0].shape for x in new_images):
360
+ new_images = torch.stack(new_images, dim=0)
361
+ return new_images
362
+
363
+
364
+ def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
365
+ prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
366
+
367
+ def insert_separator(X, sep):
368
+ return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
369
+
370
+ input_ids = []
371
+ offset = 0
372
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
373
+ offset = 1
374
+ input_ids.append(prompt_chunks[0][0])
375
+
376
+ for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
377
+ input_ids.extend(x[offset:])
378
+
379
+ if return_tensors is not None:
380
+ if return_tensors == "pt":
381
+ return torch.tensor(input_ids, dtype=torch.long)
382
+ raise ValueError(f"Unsupported tensor type: {return_tensors}")
383
+ return input_ids
384
+
385
+
386
+ def get_model_name_from_path(model_path):
387
+ model_path = model_path.strip("/")
388
+ model_paths = model_path.split("/")
389
+ if model_paths[-1].startswith("checkpoint-"):
390
+ return model_paths[-2] + "_" + model_paths[-1]
391
+ else:
392
+ return model_paths[-1]
393
+
394
+
395
+ class KeywordsStoppingCriteria(StoppingCriteria):
396
+ def __init__(self, keywords, tokenizer, input_ids):
397
+ self.keywords = keywords
398
+ self.keyword_ids = []
399
+ for keyword in keywords:
400
+ cur_keyword_ids = tokenizer(keyword).input_ids
401
+ if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
402
+ cur_keyword_ids = cur_keyword_ids[1:]
403
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
404
+ self.tokenizer = tokenizer
405
+ self.start_len = input_ids.shape[1]
406
+
407
+ def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
408
+ assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
409
+ offset = min(output_ids.shape[1] - self.start_len, 3)
410
+ self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
411
+ for keyword_id in self.keyword_ids:
412
+ if output_ids[0, -keyword_id.shape[0] :] == keyword_id:
413
+ return True
414
+ outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
415
+ for keyword in self.keywords:
416
+ if keyword in outputs:
417
+ return True
418
+ return False
419
+
420
+ from decord import VideoReader, cpu
421
+ def load_video(video_path, max_frames_num, fps=1, max_fps=4):
422
+ if isinstance(video_path, str):
423
+ vr = VideoReader(video_path, ctx=cpu(0))
424
+ else:
425
+ vr = VideoReader(video_path[0], ctx=cpu(0))
426
+ total_frame_num = len(vr)
427
+ avg_fps_from_decord = vr.get_avg_fps()
428
+
429
+ if avg_fps_from_decord <= 0:
430
+ print("Warning: Effective FPS is 0, cannot estimate timestamps.")
431
+ return None, None, []
432
+
433
+ video_fps = fps
434
+ step = round(avg_fps_from_decord / video_fps) if video_fps > 0 and avg_fps_from_decord > 0 else 1
435
+ frame_idx = [i for i in range(0, total_frame_num, step)]
436
+
437
+ fps_upbound = max_fps
438
+ frames_upbound = max_frames_num
439
+
440
+ if fps_upbound is not None:
441
+ higher_fps = min(frames_upbound//len(frame_idx), fps_upbound)
442
+ if higher_fps > video_fps:
443
+ higher_steps = round(avg_fps_from_decord / higher_fps)
444
+ frame_idx = [i for i in range(0, total_frame_num, higher_steps)]
445
+
446
+ if frames_upbound > 0:
447
+ if len(frame_idx) > frames_upbound:
448
+ uniform_sampled_frames = np.linspace(0, total_frame_num - 1, frames_upbound, dtype=int)
449
+ frame_idx = uniform_sampled_frames.tolist()
450
+
451
+ timestamps = [round(idx / avg_fps_from_decord, 1) for idx in frame_idx]
452
+ video = vr.get_batch(frame_idx).asnumpy()
453
+ vr.seek(0)
454
+ return video, timestamps
modeling_qwen2.py ADDED
@@ -0,0 +1,1549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """PyTorch Qwen2 model."""
21
+
22
+ import math
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
32
+ from transformers.modeling_attn_mask_utils import (
33
+ AttentionMaskConverter,
34
+ )
35
+ from transformers.modeling_outputs import (
36
+ BaseModelOutputWithPast,
37
+ CausalLMOutputWithPast,
38
+ SequenceClassifierOutputWithPast,
39
+ TokenClassifierOutput,
40
+ )
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
51
+
52
+
53
+ if is_flash_attn_2_available():
54
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
55
+
56
+ import pdb
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+
61
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
62
+ _CONFIG_FOR_DOC = "Qwen2Config"
63
+
64
+
65
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
66
+ class Qwen2RMSNorm(nn.Module):
67
+ def __init__(self, hidden_size, eps=1e-6):
68
+ """
69
+ Qwen2RMSNorm is equivalent to T5LayerNorm
70
+ """
71
+ super().__init__()
72
+ self.weight = nn.Parameter(torch.ones(hidden_size))
73
+ self.variance_epsilon = eps
74
+
75
+ def forward(self, hidden_states):
76
+ input_dtype = hidden_states.dtype
77
+ hidden_states = hidden_states.to(torch.float32)
78
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
79
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
80
+ return self.weight * hidden_states.to(input_dtype)
81
+
82
+
83
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralRotaryEmbedding with Mixtral->Qwen2
84
+ class Qwen2RotaryEmbedding(nn.Module):
85
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
86
+ super().__init__()
87
+
88
+ self.dim = dim
89
+ self.max_position_embeddings = max_position_embeddings
90
+ self.base = base
91
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
92
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
93
+
94
+ # Build here to make `torch.jit.trace` work.
95
+ self._set_cos_sin_cache(
96
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
97
+ )
98
+
99
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
100
+ self.max_seq_len_cached = seq_len
101
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
102
+
103
+ freqs = torch.outer(t, self.inv_freq)
104
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
105
+ emb = torch.cat((freqs, freqs), dim=-1)
106
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
107
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
108
+
109
+ def forward(self, x, seq_len=None):
110
+ # x: [bs, num_attention_heads, seq_len, head_size]
111
+ if seq_len > self.max_seq_len_cached:
112
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
113
+
114
+ return (
115
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
116
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
117
+ )
118
+
119
+
120
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
121
+ def rotate_half(x):
122
+ """Rotates half the hidden dims of the input."""
123
+ x1 = x[..., : x.shape[-1] // 2]
124
+ x2 = x[..., x.shape[-1] // 2 :]
125
+ return torch.cat((-x2, x1), dim=-1)
126
+
127
+
128
+ # Copied from transformers.models.mixtral.modeling_mixtral.apply_rotary_pos_emb
129
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, key_position_ids=None, unsqueeze_dim=1):
130
+ """Applies Rotary Position Embedding to the query and key tensors.
131
+
132
+ Args:
133
+ q (`torch.Tensor`): The query tensor.
134
+ k (`torch.Tensor`): The key tensor.
135
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
136
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
137
+ position_ids (`torch.Tensor`):
138
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
139
+ used to pass offsetted position ids when working with a KV-cache.
140
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
141
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
142
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
143
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
144
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
145
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
146
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
147
+ Returns:
148
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
149
+ """
150
+ q_cos = cos[position_ids].unsqueeze(unsqueeze_dim)
151
+ q_sin = sin[position_ids].unsqueeze(unsqueeze_dim)
152
+ q_embed = (q * q_cos) + (rotate_half(q) * q_sin)
153
+ if key_position_ids is None:
154
+ k_embed = (k * q_cos) + (rotate_half(k) * q_sin)
155
+ else:
156
+ k_cos = cos[key_position_ids].unsqueeze(unsqueeze_dim)
157
+ k_sin = sin[key_position_ids].unsqueeze(unsqueeze_dim)
158
+ k_embed = (k * k_cos) + (rotate_half(k) * k_sin)
159
+
160
+ return q_embed, k_embed
161
+
162
+
163
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
164
+ class Qwen2MLP(nn.Module):
165
+ def __init__(self, config):
166
+ super().__init__()
167
+ self.hidden_size = config.hidden_size
168
+ self.intermediate_size = config.intermediate_size
169
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
170
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
171
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
172
+ self.act_fn = ACT2FN[config.hidden_act]
173
+
174
+ def forward(self, hidden_state):
175
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
176
+
177
+
178
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
179
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
180
+ """
181
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
182
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
183
+ """
184
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
185
+ if n_rep == 1:
186
+ return hidden_states
187
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
188
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
189
+
190
+
191
+ class Qwen2Attention(nn.Module):
192
+ """
193
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
194
+ and "Generating Long Sequences with Sparse Transformers".
195
+ """
196
+
197
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
198
+ super().__init__()
199
+ self.config = config
200
+ self.layer_idx = layer_idx
201
+ if layer_idx is None:
202
+ logger.warning_once(
203
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
204
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
205
+ "when creating this class."
206
+ )
207
+
208
+ self.hidden_size = config.hidden_size
209
+ self.num_heads = config.num_attention_heads
210
+ self.head_dim = self.hidden_size // self.num_heads
211
+ self.num_key_value_heads = config.num_key_value_heads
212
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
213
+ self.max_position_embeddings = config.max_position_embeddings
214
+ self.rope_theta = config.rope_theta
215
+ self.is_causal = True
216
+ self.attention_dropout = config.attention_dropout
217
+
218
+ if (self.head_dim * self.num_heads) != self.hidden_size:
219
+ raise ValueError(
220
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
221
+ f" and `num_heads`: {self.num_heads})."
222
+ )
223
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
224
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
225
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
226
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
227
+
228
+ self.rotary_emb = Qwen2RotaryEmbedding(
229
+ self.head_dim,
230
+ max_position_embeddings=self.max_position_embeddings,
231
+ base=self.rope_theta,
232
+ )
233
+
234
+ def forward(
235
+ self,
236
+ hidden_states: torch.Tensor,
237
+ attention_mask: Optional[torch.Tensor] = None,
238
+ position_ids: Optional[torch.LongTensor] = None,
239
+ past_key_value: Optional[Cache] = None,
240
+ output_attentions: bool = False,
241
+ use_cache: bool = False,
242
+ cache_position: Optional[torch.LongTensor] = None,
243
+ blocks_positions=None,
244
+ key_position_ids=None,
245
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
246
+ bsz, q_len, _ = hidden_states.size()
247
+
248
+ query_states = self.q_proj(hidden_states)
249
+ key_states = self.k_proj(hidden_states)
250
+ value_states = self.v_proj(hidden_states)
251
+
252
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
253
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
254
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
255
+
256
+ kv_seq_len = key_states.shape[-2]
257
+ if past_key_value is not None:
258
+ if self.layer_idx is None:
259
+ raise ValueError(
260
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
261
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
262
+ "with a layer index."
263
+ )
264
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
265
+
266
+ # cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
267
+ # query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
268
+
269
+ if past_key_value is not None:
270
+ # cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
271
+ cache_kwargs = None
272
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
273
+
274
+ # kv_seq_len = key_states.shape[-2]
275
+ max_seq_len = position_ids[0][-1] + 1
276
+ cos, sin = self.rotary_emb(value_states, seq_len=max_seq_len)
277
+
278
+ try:
279
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids, key_position_ids)
280
+ except:
281
+ pdb.set_trace()
282
+
283
+ # repeat k/v heads if n_kv_heads < n_heads
284
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
285
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
286
+
287
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
288
+
289
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
290
+ raise ValueError(
291
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
292
+ f" {attn_weights.size()}"
293
+ )
294
+
295
+ if attention_mask is not None: # no matter the length, we just slice it
296
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
297
+ attn_weights = attn_weights + causal_mask
298
+
299
+ # upcast attention to fp32
300
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
301
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
302
+ attn_output = torch.matmul(attn_weights, value_states)
303
+
304
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
305
+ raise ValueError(
306
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
307
+ f" {attn_output.size()}"
308
+ )
309
+
310
+ attn_output = attn_output.transpose(1, 2).contiguous()
311
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
312
+
313
+ attn_output = self.o_proj(attn_output)
314
+
315
+ if not output_attentions:
316
+ attn_weights = None
317
+
318
+ return attn_output, attn_weights, past_key_value
319
+
320
+
321
+ # class Qwen2FlashAttention2(Qwen2Attention):
322
+ # """
323
+ # Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
324
+ # as the weights of the module stays untouched. The only required change would be on the forward pass
325
+ # where it needs to correctly call the public API of flash attention and deal with padding tokens
326
+ # in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
327
+ # config.max_window_layers layers.
328
+ # """
329
+
330
+ # # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
331
+ # def __init__(self, *args, **kwargs):
332
+ # super().__init__(*args, **kwargs)
333
+
334
+ # # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
335
+ # # 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.
336
+ # # 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).
337
+ # self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
338
+
339
+ # def forward(
340
+ # self,
341
+ # hidden_states: torch.Tensor,
342
+ # attention_mask: Optional[torch.Tensor] = None,
343
+ # position_ids: Optional[torch.LongTensor] = None,
344
+ # past_key_value: Optional[Cache] = None,
345
+ # output_attentions: bool = False,
346
+ # use_cache: bool = False,
347
+ # cache_position: Optional[torch.LongTensor] = None,
348
+ # ):
349
+ # import pdb
350
+
351
+ # bsz, q_len, _ = hidden_states.size()
352
+
353
+ # query_states = self.q_proj(hidden_states)
354
+ # key_states = self.k_proj(hidden_states)
355
+ # value_states = self.v_proj(hidden_states)
356
+
357
+ # query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
358
+ # key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
359
+ # value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
360
+
361
+ # kv_seq_len = key_states.shape[-2]
362
+ # if past_key_value is not None:
363
+ # if self.layer_idx is None:
364
+ # raise ValueError(
365
+ # f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
366
+ # "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
367
+ # "with a layer index."
368
+ # )
369
+ # kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
370
+
371
+ # # Because the input can be padded, the absolute sequence length depends on the max position id.
372
+ # rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
373
+ # cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
374
+
375
+ # # if self.layer_idx == 0:
376
+ # # pdb.set_trace()
377
+
378
+ # if past_key_value is not None:
379
+ # # Activate slicing cache only if the config has a value `sliding_windows` attribute
380
+ # cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
381
+ # if (
382
+ # getattr(self.config, "sliding_window", None) is not None
383
+ # and kv_seq_len > self.config.sliding_window
384
+ # and cache_has_contents
385
+ # ):
386
+ # slicing_tokens = 1 - self.config.sliding_window
387
+
388
+ # past_key = past_key_value[self.layer_idx][0]
389
+ # past_value = past_key_value[self.layer_idx][1]
390
+
391
+ # past_key = past_key[:, :, slicing_tokens:, :].contiguous()
392
+ # past_value = past_value[:, :, slicing_tokens:, :].contiguous()
393
+
394
+ # if past_key.shape[-2] != self.config.sliding_window - 1:
395
+ # raise ValueError(
396
+ # f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
397
+ # f" {past_key.shape}"
398
+ # )
399
+
400
+ # if attention_mask is not None:
401
+ # attention_mask = attention_mask[:, slicing_tokens:]
402
+ # attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
403
+
404
+ # cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
405
+ # key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
406
+
407
+ # key_position_ids = torch.arange(0, key_states.size(2), device=key_states.device).expand(1, -1)
408
+ # else:
409
+ # key_position_ids = None
410
+
411
+ # # if self.layer_idx == 0:
412
+ # # if not torch.equal(key_position_ids, position_ids):
413
+ # # print(f'key_position_ids: {key_position_ids[:3]}')
414
+ # # print(f'position_ids: {position_ids[:3]}')
415
+ # # print(f'='*50)
416
+
417
+ # query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids, key_position_ids)
418
+
419
+ # # repeat k/v heads if n_kv_heads < n_heads
420
+ # key_states = repeat_kv(key_states, self.num_key_value_groups)
421
+ # value_states = repeat_kv(value_states, self.num_key_value_groups)
422
+ # dropout_rate = 0.0 if not self.training else self.attention_dropout
423
+
424
+ # # In PEFT, usually we cast the layer norms in float32 for training stability reasons
425
+ # # therefore the input hidden states gets silently casted in float32. Hence, we need
426
+ # # cast them back in float16 just to be sure everything works as expected.
427
+ # input_dtype = query_states.dtype
428
+ # if input_dtype == torch.float32:
429
+ # if torch.is_autocast_enabled():
430
+ # target_dtype = torch.get_autocast_gpu_dtype()
431
+ # # Handle the case where the model is quantized
432
+ # elif hasattr(self.config, "_pre_quantization_dtype"):
433
+ # target_dtype = self.config._pre_quantization_dtype
434
+ # else:
435
+ # target_dtype = self.q_proj.weight.dtype
436
+
437
+ # logger.warning_once(
438
+ # f"The input hidden states seems to be silently casted in float32, this might be related to"
439
+ # f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
440
+ # f" {target_dtype}."
441
+ # )
442
+
443
+ # query_states = query_states.to(target_dtype)
444
+ # key_states = key_states.to(target_dtype)
445
+ # value_states = value_states.to(target_dtype)
446
+
447
+ # # Reashape to the expected shape for Flash Attention
448
+ # query_states = query_states.transpose(1, 2)
449
+ # key_states = key_states.transpose(1, 2)
450
+ # value_states = value_states.transpose(1, 2)
451
+
452
+ # if (
453
+ # self.config.use_sliding_window
454
+ # and getattr(self.config, "sliding_window", None) is not None
455
+ # and self.layer_idx >= self.config.max_window_layers
456
+ # ):
457
+ # sliding_window = self.config.sliding_window
458
+ # else:
459
+ # sliding_window = None
460
+
461
+ # attn_output = _flash_attention_forward(
462
+ # query_states,
463
+ # key_states,
464
+ # value_states,
465
+ # attention_mask,
466
+ # q_len,
467
+ # dropout=dropout_rate,
468
+ # sliding_window=sliding_window,
469
+ # is_causal=self.is_causal,
470
+ # use_top_left_mask=self._flash_attn_uses_top_left_mask,
471
+ # )
472
+
473
+ # attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
474
+ # attn_output = self.o_proj(attn_output)
475
+
476
+ # if not output_attentions:
477
+ # attn_weights = None
478
+
479
+ # return attn_output, attn_weights, past_key_value
480
+
481
+
482
+
483
+ class Qwen2FlashAttention2(Qwen2Attention):
484
+ """
485
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
486
+ as the weights of the module stays untouched. The only required change would be on the forward pass
487
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
488
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
489
+ config.max_window_layers layers.
490
+ """
491
+
492
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
493
+ def __init__(self, *args, **kwargs):
494
+ super().__init__(*args, **kwargs)
495
+
496
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
497
+ # 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.
498
+ # 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).
499
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
500
+
501
+ def forward(
502
+ self,
503
+ hidden_states: torch.Tensor,
504
+ attention_mask: Optional[torch.Tensor] = None,
505
+ position_ids: Optional[torch.LongTensor] = None,
506
+ past_key_value: Optional[Cache] = None,
507
+ output_attentions: bool = False,
508
+ use_cache: bool = False,
509
+ cache_position: Optional[torch.LongTensor] = None,
510
+ ):
511
+ bsz, q_len, _ = hidden_states.size()
512
+
513
+ query_states = self.q_proj(hidden_states)
514
+ key_states = self.k_proj(hidden_states)
515
+ value_states = self.v_proj(hidden_states)
516
+
517
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
518
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
519
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
520
+
521
+ kv_seq_len = key_states.shape[-2]
522
+ if past_key_value is not None:
523
+ if self.layer_idx is None:
524
+ raise ValueError(
525
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
526
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
527
+ "with a layer index."
528
+ )
529
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
530
+
531
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
532
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
533
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
534
+
535
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
536
+
537
+ if past_key_value is not None:
538
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
539
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
540
+ if (
541
+ getattr(self.config, "sliding_window", None) is not None
542
+ and kv_seq_len > self.config.sliding_window
543
+ and cache_has_contents
544
+ ):
545
+ slicing_tokens = 1 - self.config.sliding_window
546
+
547
+ past_key = past_key_value[self.layer_idx][0]
548
+ past_value = past_key_value[self.layer_idx][1]
549
+
550
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
551
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
552
+
553
+ if past_key.shape[-2] != self.config.sliding_window - 1:
554
+ raise ValueError(
555
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
556
+ f" {past_key.shape}"
557
+ )
558
+
559
+ if attention_mask is not None:
560
+ attention_mask = attention_mask[:, slicing_tokens:]
561
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
562
+
563
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
564
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
565
+
566
+ # repeat k/v heads if n_kv_heads < n_heads
567
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
568
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
569
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
570
+
571
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
572
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
573
+ # cast them back in float16 just to be sure everything works as expected.
574
+ input_dtype = query_states.dtype
575
+ if input_dtype == torch.float32:
576
+ if torch.is_autocast_enabled():
577
+ target_dtype = torch.get_autocast_gpu_dtype()
578
+ # Handle the case where the model is quantized
579
+ elif hasattr(self.config, "_pre_quantization_dtype"):
580
+ target_dtype = self.config._pre_quantization_dtype
581
+ else:
582
+ target_dtype = self.q_proj.weight.dtype
583
+
584
+ logger.warning_once(
585
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
586
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
587
+ f" {target_dtype}."
588
+ )
589
+
590
+ query_states = query_states.to(target_dtype)
591
+ key_states = key_states.to(target_dtype)
592
+ value_states = value_states.to(target_dtype)
593
+
594
+ # Reashape to the expected shape for Flash Attention
595
+ query_states = query_states.transpose(1, 2)
596
+ key_states = key_states.transpose(1, 2)
597
+ value_states = value_states.transpose(1, 2)
598
+
599
+ if (
600
+ self.config.use_sliding_window
601
+ and getattr(self.config, "sliding_window", None) is not None
602
+ and self.layer_idx >= self.config.max_window_layers
603
+ ):
604
+ sliding_window = self.config.sliding_window
605
+ else:
606
+ sliding_window = None
607
+
608
+ attn_output = _flash_attention_forward(
609
+ query_states,
610
+ key_states,
611
+ value_states,
612
+ attention_mask,
613
+ q_len,
614
+ dropout=dropout_rate,
615
+ sliding_window=sliding_window,
616
+ is_causal=self.is_causal,
617
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
618
+ )
619
+
620
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
621
+ attn_output = self.o_proj(attn_output)
622
+
623
+ if not output_attentions:
624
+ attn_weights = None
625
+
626
+ return attn_output, attn_weights, past_key_value
627
+
628
+
629
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralSdpaAttention with Mixtral->Qwen2
630
+ class Qwen2SdpaAttention(Qwen2Attention):
631
+ """
632
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
633
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
634
+ SDPA API.
635
+ """
636
+
637
+ def compute_similarity(self, q_reps, p_reps):
638
+ if len(p_reps.size()) == 2:
639
+ return torch.matmul(q_reps, p_reps.transpose(0, 1))
640
+ return torch.matmul(q_reps, p_reps.transpose(-2, -1))
641
+
642
+ # Adapted from Qwen2Attention.forward
643
+ def forward(
644
+ self,
645
+ hidden_states: torch.Tensor,
646
+ attention_mask: Optional[torch.Tensor] = None,
647
+ position_ids: Optional[torch.LongTensor] = None,
648
+ key_position_ids: Optional[torch.LongTensor] = None,
649
+ past_key_value: Optional[Cache] = None,
650
+ output_attentions: bool = False,
651
+ use_cache: bool = False,
652
+ cache_position: Optional[torch.LongTensor] = None,
653
+ blocks_positions=None,
654
+ layer_idx=None,
655
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
656
+ if output_attentions:
657
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
658
+ logger.warning_once(
659
+ "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, "
660
+ '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.'
661
+ )
662
+ return super().forward(
663
+ hidden_states=hidden_states,
664
+ attention_mask=attention_mask,
665
+ position_ids=position_ids,
666
+ past_key_value=past_key_value,
667
+ output_attentions=output_attentions,
668
+ use_cache=use_cache,
669
+ )
670
+
671
+ bsz, q_len, _ = hidden_states.size()
672
+
673
+ query_states = self.q_proj(hidden_states)
674
+ key_states = self.k_proj(hidden_states)
675
+ value_states = self.v_proj(hidden_states)
676
+
677
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
678
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
679
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
680
+
681
+ if past_key_value is not None:
682
+ # cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
683
+ cache_kwargs = None
684
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
685
+
686
+ max_seq_len = position_ids[0][-1] + 1
687
+ cos, sin = self.rotary_emb(value_states, seq_len=max_seq_len)
688
+
689
+ try:
690
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids, key_position_ids)
691
+ except:
692
+ pdb.set_trace()
693
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
694
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
695
+
696
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
697
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
698
+ if query_states.device.type == "cuda" and attention_mask is not None:
699
+ query_states = query_states.contiguous()
700
+ key_states = key_states.contiguous()
701
+ value_states = value_states.contiguous()
702
+
703
+ causal_mask = attention_mask
704
+ if attention_mask is not None: # no matter the length, we just slice it
705
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
706
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
707
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
708
+ # 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.
709
+ is_causal = True if causal_mask is None and q_len > 1 else False
710
+
711
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
712
+ query_states,
713
+ key_states,
714
+ value_states,
715
+ attn_mask=causal_mask,
716
+ dropout_p=self.attention_dropout if self.training else 0.0,
717
+ is_causal=is_causal,
718
+ )
719
+
720
+ attn_output = attn_output.transpose(1, 2).contiguous()
721
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
722
+
723
+ attn_output = self.o_proj(attn_output)
724
+
725
+ return attn_output, None, past_key_value
726
+
727
+
728
+ QWEN2_ATTENTION_CLASSES = {
729
+ "eager": Qwen2Attention,
730
+ "flash_attention_2": Qwen2FlashAttention2,
731
+ "sdpa": Qwen2SdpaAttention,
732
+ }
733
+
734
+
735
+ class Qwen2DecoderLayer(nn.Module):
736
+ def __init__(self, config: Qwen2Config, layer_idx: int):
737
+ super().__init__()
738
+ self.hidden_size = config.hidden_size
739
+
740
+ if config.sliding_window and config._attn_implementation != "flash_attention_2":
741
+ logger.warning_once(
742
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
743
+ "unexpected results may be encountered."
744
+ )
745
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
746
+
747
+ self.mlp = Qwen2MLP(config)
748
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
749
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
750
+
751
+ def forward(
752
+ self,
753
+ hidden_states: torch.Tensor,
754
+ attention_mask: Optional[torch.Tensor] = None,
755
+ position_ids: Optional[torch.LongTensor] = None,
756
+ key_position_ids: Optional[torch.LongTensor] = None,
757
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
758
+ output_attentions: Optional[bool] = False,
759
+ use_cache: Optional[bool] = False,
760
+ cache_position: Optional[torch.LongTensor] = None,
761
+ blocks_positions=None,
762
+ **kwargs,
763
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
764
+ """
765
+ Args:
766
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
767
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
768
+ `(batch, sequence_length)` where padding elements are indicated by 0.
769
+ output_attentions (`bool`, *optional*):
770
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
771
+ returned tensors for more detail.
772
+ use_cache (`bool`, *optional*):
773
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
774
+ (see `past_key_values`).
775
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
776
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
777
+ Indices depicting the position of the input sequence tokens in the sequence.
778
+ kwargs (`dict`, *optional*):
779
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
780
+ into the model
781
+ """
782
+
783
+ residual = hidden_states
784
+
785
+ hidden_states = self.input_layernorm(hidden_states)
786
+
787
+ # Self Attention
788
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
789
+ hidden_states=hidden_states,
790
+ attention_mask=attention_mask,
791
+ position_ids=position_ids,
792
+ key_position_ids=key_position_ids,
793
+ past_key_value=past_key_value,
794
+ output_attentions=output_attentions,
795
+ use_cache=use_cache,
796
+ cache_position=cache_position,
797
+ blocks_positions=blocks_positions,
798
+ )
799
+ hidden_states = residual + hidden_states
800
+ # self.self_attn.record_unselected_block
801
+ # Fully Connected
802
+ residual = hidden_states
803
+ hidden_states = self.post_attention_layernorm(hidden_states)
804
+ hidden_states = self.mlp(hidden_states)
805
+ hidden_states = residual + hidden_states
806
+
807
+ outputs = (hidden_states,)
808
+
809
+ if output_attentions:
810
+ outputs += (self_attn_weights,)
811
+
812
+ if use_cache:
813
+ outputs += (present_key_value,)
814
+
815
+ return outputs
816
+
817
+
818
+ QWEN2_START_DOCSTRING = r"""
819
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
820
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
821
+ etc.)
822
+
823
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
824
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
825
+ and behavior.
826
+
827
+ Parameters:
828
+ config ([`Qwen2Config`]):
829
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
830
+ load the weights associated with the model, only the configuration. Check out the
831
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
832
+ """
833
+
834
+
835
+ @add_start_docstrings(
836
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
837
+ QWEN2_START_DOCSTRING,
838
+ )
839
+ class Qwen2PreTrainedModel(PreTrainedModel):
840
+ config_class = Qwen2Config
841
+ base_model_prefix = "model"
842
+ supports_gradient_checkpointing = True
843
+ _no_split_modules = ["Qwen2DecoderLayer"]
844
+ _skip_keys_device_placement = "past_key_values"
845
+ _supports_flash_attn_2 = True
846
+ _supports_sdpa = True
847
+ _supports_cache_class = True
848
+
849
+ def _init_weights(self, module):
850
+ std = self.config.initializer_range
851
+ if isinstance(module, nn.Linear):
852
+ module.weight.data.normal_(mean=0.0, std=std)
853
+ if module.bias is not None:
854
+ module.bias.data.zero_()
855
+ elif isinstance(module, nn.Embedding):
856
+ module.weight.data.normal_(mean=0.0, std=std)
857
+ if module.padding_idx is not None:
858
+ module.weight.data[module.padding_idx].zero_()
859
+
860
+
861
+ QWEN2_INPUTS_DOCSTRING = r"""
862
+ Args:
863
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
864
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
865
+ it.
866
+
867
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
868
+ [`PreTrainedTokenizer.__call__`] for details.
869
+
870
+ [What are input IDs?](../glossary#input-ids)
871
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
872
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
873
+
874
+ - 1 for tokens that are **not masked**,
875
+ - 0 for tokens that are **masked**.
876
+
877
+ [What are attention masks?](../glossary#attention-mask)
878
+
879
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
880
+ [`PreTrainedTokenizer.__call__`] for details.
881
+
882
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
883
+ `past_key_values`).
884
+
885
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
886
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
887
+ information on the default strategy.
888
+
889
+ - 1 indicates the head is **not masked**,
890
+ - 0 indicates the head is **masked**.
891
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
892
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
893
+ config.n_positions - 1]`.
894
+
895
+ [What are position IDs?](../glossary#position-ids)
896
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
897
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
898
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
899
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
900
+
901
+ Two formats are allowed:
902
+ - a [`~cache_utils.Cache`] instance;
903
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
904
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
905
+ cache format.
906
+
907
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
908
+ legacy cache format will be returned.
909
+
910
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
911
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
912
+ of shape `(batch_size, sequence_length)`.
913
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
914
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
915
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
916
+ model's internal embedding lookup matrix.
917
+ use_cache (`bool`, *optional*):
918
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
919
+ `past_key_values`).
920
+ output_attentions (`bool`, *optional*):
921
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
922
+ tensors for more detail.
923
+ output_hidden_states (`bool`, *optional*):
924
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
925
+ more detail.
926
+ return_dict (`bool`, *optional*):
927
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
928
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
929
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
930
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
931
+ the complete sequence length.
932
+ """
933
+
934
+
935
+ @add_start_docstrings(
936
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
937
+ QWEN2_START_DOCSTRING,
938
+ )
939
+ class Qwen2Model(Qwen2PreTrainedModel):
940
+ """
941
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
942
+
943
+ Args:
944
+ config: Qwen2Config
945
+ """
946
+
947
+ def __init__(self, config: Qwen2Config):
948
+ super().__init__(config)
949
+ self.padding_idx = config.pad_token_id
950
+ self.vocab_size = config.vocab_size
951
+
952
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
953
+ self.layers = nn.ModuleList(
954
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
955
+ )
956
+ self._attn_implementation = config._attn_implementation
957
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
958
+
959
+ self.gradient_checkpointing = False
960
+ # Initialize weights and apply final processing
961
+ self.post_init()
962
+
963
+ def get_input_embeddings(self):
964
+ return self.embed_tokens
965
+
966
+ def set_input_embeddings(self, value):
967
+ self.embed_tokens = value
968
+
969
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
970
+ def forward(
971
+ self,
972
+ input_ids: torch.LongTensor = None,
973
+ attention_mask: Optional[torch.Tensor] = None,
974
+ position_ids: Optional[torch.LongTensor] = None,
975
+ key_position_ids: Optional[torch.LongTensor] = None,
976
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
977
+ inputs_embeds: Optional[torch.FloatTensor] = None,
978
+ use_cache: Optional[bool] = None,
979
+ output_attentions: Optional[bool] = None,
980
+ output_hidden_states: Optional[bool] = None,
981
+ return_dict: Optional[bool] = None,
982
+ cache_position: Optional[torch.LongTensor] = None,
983
+ blocks_positions=None
984
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
985
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
986
+ output_hidden_states = (
987
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
988
+ )
989
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
990
+
991
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
992
+
993
+ if (input_ids is None) ^ (inputs_embeds is not None):
994
+ raise ValueError(
995
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
996
+ )
997
+
998
+ if self.gradient_checkpointing and self.training:
999
+ if use_cache:
1000
+ logger.warning_once(
1001
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1002
+ )
1003
+ use_cache = False
1004
+
1005
+ use_legacy_cache = False
1006
+ if use_cache and not isinstance(past_key_values, Cache):
1007
+ use_legacy_cache = True
1008
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1009
+ logger.warning_once(
1010
+ "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
1011
+ "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
1012
+ )
1013
+
1014
+ if inputs_embeds is None:
1015
+ inputs_embeds = self.embed_tokens(input_ids)
1016
+
1017
+ if cache_position is None:
1018
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1019
+ cache_position = torch.arange(
1020
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1021
+ )
1022
+ if position_ids is None:
1023
+ position_ids = cache_position.unsqueeze(0)
1024
+
1025
+ causal_mask = self._update_causal_mask(
1026
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1027
+ )
1028
+
1029
+ hidden_states = inputs_embeds
1030
+
1031
+ # decoder layers
1032
+ all_hidden_states = () if output_hidden_states else None
1033
+ all_self_attns = () if output_attentions else None
1034
+ next_decoder_cache = None
1035
+
1036
+ for decoder_layer in self.layers:
1037
+ if output_hidden_states:
1038
+ all_hidden_states += (hidden_states,)
1039
+
1040
+ if self.gradient_checkpointing and self.training:
1041
+ layer_outputs = self._gradient_checkpointing_func(
1042
+ decoder_layer.__call__,
1043
+ hidden_states,
1044
+ causal_mask,
1045
+ position_ids,
1046
+ past_key_values,
1047
+ output_attentions,
1048
+ use_cache,
1049
+ cache_position,
1050
+ )
1051
+ else:
1052
+ layer_outputs = decoder_layer(
1053
+ hidden_states,
1054
+ attention_mask=causal_mask,
1055
+ position_ids=position_ids,
1056
+ key_position_ids=key_position_ids,
1057
+ past_key_value=past_key_values,
1058
+ output_attentions=output_attentions,
1059
+ use_cache=use_cache,
1060
+ cache_position=cache_position,
1061
+ blocks_positions=blocks_positions
1062
+ )
1063
+
1064
+ hidden_states = layer_outputs[0]
1065
+
1066
+ if use_cache:
1067
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1068
+
1069
+ if output_attentions:
1070
+ all_self_attns += (layer_outputs[1],)
1071
+
1072
+ hidden_states = self.norm(hidden_states)
1073
+
1074
+ # add hidden states from the last decoder layer
1075
+ if output_hidden_states:
1076
+ all_hidden_states += (hidden_states,)
1077
+
1078
+ next_cache = None
1079
+ if use_cache:
1080
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1081
+
1082
+ if not return_dict:
1083
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1084
+ return BaseModelOutputWithPast(
1085
+ last_hidden_state=hidden_states,
1086
+ past_key_values=next_cache,
1087
+ hidden_states=all_hidden_states,
1088
+ attentions=all_self_attns,
1089
+ )
1090
+
1091
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
1092
+ def _update_causal_mask(
1093
+ self,
1094
+ attention_mask: torch.Tensor,
1095
+ input_tensor: torch.Tensor,
1096
+ cache_position: torch.Tensor,
1097
+ past_key_values: Cache,
1098
+ output_attentions: bool,
1099
+ ):
1100
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1101
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1102
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1103
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1104
+
1105
+ if self.config._attn_implementation == "flash_attention_2":
1106
+ if attention_mask is not None and 0.0 in attention_mask:
1107
+ return attention_mask
1108
+ return None
1109
+
1110
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1111
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1112
+ # to infer the attention mask.
1113
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1114
+ using_static_cache = isinstance(past_key_values, StaticCache)
1115
+
1116
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1117
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1118
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1119
+ attention_mask,
1120
+ inputs_embeds=input_tensor,
1121
+ past_key_values_length=past_seen_tokens,
1122
+ is_training=self.training,
1123
+ ):
1124
+ return None
1125
+
1126
+ dtype, device = input_tensor.dtype, input_tensor.device
1127
+ min_dtype = torch.finfo(dtype).min
1128
+ sequence_length = input_tensor.shape[1]
1129
+ if using_static_cache:
1130
+ target_length = past_key_values.get_max_length()
1131
+ else:
1132
+ target_length = (
1133
+ attention_mask.shape[-1]
1134
+ if isinstance(attention_mask, torch.Tensor)
1135
+ else past_seen_tokens + sequence_length + 1
1136
+ )
1137
+
1138
+ if attention_mask is not None and attention_mask.dim() == 4:
1139
+ # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
1140
+ if attention_mask.max() != 0:
1141
+ raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
1142
+ causal_mask = attention_mask
1143
+ else:
1144
+ causal_mask = torch.full(
1145
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1146
+ )
1147
+ if sequence_length != 1:
1148
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1149
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1150
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1151
+ if attention_mask is not None:
1152
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1153
+ mask_length = attention_mask.shape[-1]
1154
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1155
+ padding_mask = padding_mask == 0
1156
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1157
+ padding_mask, min_dtype
1158
+ )
1159
+ if (
1160
+ self.config._attn_implementation == "sdpa"
1161
+ and attention_mask is not None
1162
+ and attention_mask.device.type == "cuda"
1163
+ and not output_attentions
1164
+ ):
1165
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1166
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1167
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1168
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1169
+
1170
+ return causal_mask
1171
+
1172
+
1173
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel):
1174
+ _tied_weights_keys = ["lm_head.weight"]
1175
+
1176
+ def __init__(self, config):
1177
+ super().__init__(config)
1178
+ self.model = Qwen2Model(config)
1179
+ self.vocab_size = config.vocab_size
1180
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1181
+
1182
+ # Initialize weights and apply final processing
1183
+ self.post_init()
1184
+
1185
+ def get_input_embeddings(self):
1186
+ return self.model.embed_tokens
1187
+
1188
+ def set_input_embeddings(self, value):
1189
+ self.model.embed_tokens = value
1190
+
1191
+ def get_output_embeddings(self):
1192
+ return self.lm_head
1193
+
1194
+ def set_output_embeddings(self, new_embeddings):
1195
+ self.lm_head = new_embeddings
1196
+
1197
+ def set_decoder(self, decoder):
1198
+ self.model = decoder
1199
+
1200
+ def get_decoder(self):
1201
+ return self.model
1202
+
1203
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1204
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1205
+ def forward(
1206
+ self,
1207
+ input_ids: torch.LongTensor = None,
1208
+ attention_mask: Optional[torch.Tensor] = None,
1209
+ position_ids: Optional[torch.LongTensor] = None,
1210
+ key_position_ids: Optional[torch.LongTensor] = None,
1211
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1212
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1213
+ labels: Optional[torch.LongTensor] = None,
1214
+ use_cache: Optional[bool] = None,
1215
+ output_attentions: Optional[bool] = None,
1216
+ output_hidden_states: Optional[bool] = None,
1217
+ return_dict: Optional[bool] = None,
1218
+ cache_position: Optional[torch.LongTensor] = None,
1219
+ blocks_positions=None,
1220
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1221
+ r"""
1222
+ Args:
1223
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1224
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1225
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1226
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1227
+
1228
+ Returns:
1229
+
1230
+ Example:
1231
+
1232
+ ```python
1233
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1234
+
1235
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1236
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1237
+
1238
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1239
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1240
+
1241
+ >>> # Generate
1242
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1243
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1244
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1245
+ ```"""
1246
+
1247
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1248
+ output_hidden_states = (
1249
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1250
+ )
1251
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1252
+
1253
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1254
+ outputs = self.model(
1255
+ input_ids=input_ids,
1256
+ attention_mask=attention_mask,
1257
+ position_ids=position_ids,
1258
+ key_position_ids=key_position_ids,
1259
+ past_key_values=past_key_values,
1260
+ inputs_embeds=inputs_embeds,
1261
+ use_cache=use_cache,
1262
+ output_attentions=output_attentions,
1263
+ output_hidden_states=output_hidden_states,
1264
+ return_dict=return_dict,
1265
+ cache_position=cache_position,
1266
+ blocks_positions=blocks_positions,
1267
+ )
1268
+
1269
+ hidden_states = outputs[0]
1270
+ logits = self.lm_head(hidden_states)
1271
+ logits = logits.float()
1272
+
1273
+ loss = None
1274
+ if labels is not None:
1275
+ # Shift so that tokens < n predict n
1276
+ shift_logits = logits[..., :-1, :].contiguous()
1277
+ shift_labels = labels[..., 1:].contiguous()
1278
+ # Flatten the tokens
1279
+ loss_fct = CrossEntropyLoss()
1280
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1281
+ shift_labels = shift_labels.view(-1)
1282
+ # Enable model parallelism
1283
+ shift_labels = shift_labels.to(shift_logits.device)
1284
+ loss = loss_fct(shift_logits, shift_labels)
1285
+
1286
+ if not return_dict:
1287
+ output = (logits,) + outputs[1:]
1288
+ return (loss,) + output if loss is not None else output
1289
+
1290
+ return CausalLMOutputWithPast(
1291
+ loss=loss,
1292
+ logits=logits,
1293
+ past_key_values=outputs.past_key_values,
1294
+ hidden_states=outputs.hidden_states,
1295
+ attentions=outputs.attentions,
1296
+ )
1297
+
1298
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
1299
+ def prepare_inputs_for_generation(
1300
+ self,
1301
+ input_ids,
1302
+ past_key_values=None,
1303
+ attention_mask=None,
1304
+ inputs_embeds=None,
1305
+ cache_position=None,
1306
+ position_ids=None,
1307
+ use_cache=True,
1308
+ **kwargs,
1309
+ ):
1310
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1311
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1312
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1313
+ if past_key_values is not None:
1314
+ if inputs_embeds is not None: # Exception 1
1315
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1316
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1317
+ input_ids = input_ids[:, cache_position]
1318
+
1319
+ if attention_mask is not None and position_ids is None:
1320
+ # create position_ids on the fly for batch generation
1321
+ position_ids = attention_mask.long().cumsum(-1) - 1
1322
+ position_ids.masked_fill_(attention_mask == 0, 1)
1323
+ if past_key_values:
1324
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1325
+
1326
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1327
+ if inputs_embeds is not None and cache_position[0] == 0:
1328
+ model_inputs = {"inputs_embeds": inputs_embeds}
1329
+ else:
1330
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
1331
+
1332
+ model_inputs.update(
1333
+ {
1334
+ "position_ids": position_ids,
1335
+ "cache_position": cache_position,
1336
+ "past_key_values": past_key_values,
1337
+ "use_cache": use_cache,
1338
+ "attention_mask": attention_mask,
1339
+ }
1340
+ )
1341
+ return model_inputs
1342
+
1343
+
1344
+ @add_start_docstrings(
1345
+ """
1346
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1347
+
1348
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1349
+ (e.g. GPT-2) do.
1350
+
1351
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1352
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1353
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1354
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1355
+ each row of the batch).
1356
+ """,
1357
+ QWEN2_START_DOCSTRING,
1358
+ )
1359
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
1360
+ def __init__(self, config):
1361
+ super().__init__(config)
1362
+ self.num_labels = config.num_labels
1363
+ self.model = Qwen2Model(config)
1364
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1365
+
1366
+ # Initialize weights and apply final processing
1367
+ self.post_init()
1368
+
1369
+ def get_input_embeddings(self):
1370
+ return self.model.embed_tokens
1371
+
1372
+ def set_input_embeddings(self, value):
1373
+ self.model.embed_tokens = value
1374
+
1375
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1376
+ def forward(
1377
+ self,
1378
+ input_ids: torch.LongTensor = None,
1379
+ attention_mask: Optional[torch.Tensor] = None,
1380
+ position_ids: Optional[torch.LongTensor] = None,
1381
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1382
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1383
+ labels: Optional[torch.LongTensor] = None,
1384
+ use_cache: Optional[bool] = None,
1385
+ output_attentions: Optional[bool] = None,
1386
+ output_hidden_states: Optional[bool] = None,
1387
+ return_dict: Optional[bool] = None,
1388
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1389
+ r"""
1390
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1391
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1392
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1393
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1394
+ """
1395
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1396
+
1397
+ transformer_outputs = self.model(
1398
+ input_ids,
1399
+ attention_mask=attention_mask,
1400
+ position_ids=position_ids,
1401
+ past_key_values=past_key_values,
1402
+ inputs_embeds=inputs_embeds,
1403
+ use_cache=use_cache,
1404
+ output_attentions=output_attentions,
1405
+ output_hidden_states=output_hidden_states,
1406
+ return_dict=return_dict,
1407
+ )
1408
+ hidden_states = transformer_outputs[0]
1409
+ logits = self.score(hidden_states)
1410
+
1411
+ if input_ids is not None:
1412
+ batch_size = input_ids.shape[0]
1413
+ else:
1414
+ batch_size = inputs_embeds.shape[0]
1415
+
1416
+ if self.config.pad_token_id is None and batch_size != 1:
1417
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1418
+ if self.config.pad_token_id is None:
1419
+ sequence_lengths = -1
1420
+ else:
1421
+ if input_ids is not None:
1422
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1423
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1424
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1425
+ sequence_lengths = sequence_lengths.to(logits.device)
1426
+ else:
1427
+ sequence_lengths = -1
1428
+
1429
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1430
+
1431
+ loss = None
1432
+ if labels is not None:
1433
+ labels = labels.to(logits.device)
1434
+ if self.config.problem_type is None:
1435
+ if self.num_labels == 1:
1436
+ self.config.problem_type = "regression"
1437
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1438
+ self.config.problem_type = "single_label_classification"
1439
+ else:
1440
+ self.config.problem_type = "multi_label_classification"
1441
+
1442
+ if self.config.problem_type == "regression":
1443
+ loss_fct = MSELoss()
1444
+ if self.num_labels == 1:
1445
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1446
+ else:
1447
+ loss = loss_fct(pooled_logits, labels)
1448
+ elif self.config.problem_type == "single_label_classification":
1449
+ loss_fct = CrossEntropyLoss()
1450
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1451
+ elif self.config.problem_type == "multi_label_classification":
1452
+ loss_fct = BCEWithLogitsLoss()
1453
+ loss = loss_fct(pooled_logits, labels)
1454
+ if not return_dict:
1455
+ output = (pooled_logits,) + transformer_outputs[1:]
1456
+ return ((loss,) + output) if loss is not None else output
1457
+
1458
+ return SequenceClassifierOutputWithPast(
1459
+ loss=loss,
1460
+ logits=pooled_logits,
1461
+ past_key_values=transformer_outputs.past_key_values,
1462
+ hidden_states=transformer_outputs.hidden_states,
1463
+ attentions=transformer_outputs.attentions,
1464
+ )
1465
+
1466
+
1467
+ @add_start_docstrings(
1468
+ """
1469
+ The Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1470
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1471
+ """,
1472
+ QWEN2_START_DOCSTRING,
1473
+ )
1474
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->Qwen2, LLAMA->QWEN2
1475
+ class Qwen2ForTokenClassification(Qwen2PreTrainedModel):
1476
+ def __init__(self, config):
1477
+ super().__init__(config)
1478
+ self.num_labels = config.num_labels
1479
+ self.model = Qwen2Model(config)
1480
+ if getattr(config, "classifier_dropout", None) is not None:
1481
+ classifier_dropout = config.classifier_dropout
1482
+ elif getattr(config, "hidden_dropout", None) is not None:
1483
+ classifier_dropout = config.hidden_dropout
1484
+ else:
1485
+ classifier_dropout = 0.1
1486
+ self.dropout = nn.Dropout(classifier_dropout)
1487
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1488
+
1489
+ # Initialize weights and apply final processing
1490
+ self.post_init()
1491
+
1492
+ def get_input_embeddings(self):
1493
+ return self.model.embed_tokens
1494
+
1495
+ def set_input_embeddings(self, value):
1496
+ self.model.embed_tokens = value
1497
+
1498
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1499
+ def forward(
1500
+ self,
1501
+ input_ids: Optional[torch.LongTensor] = None,
1502
+ attention_mask: Optional[torch.Tensor] = None,
1503
+ position_ids: Optional[torch.LongTensor] = None,
1504
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1505
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1506
+ labels: Optional[torch.LongTensor] = None,
1507
+ use_cache: Optional[bool] = None,
1508
+ output_attentions: Optional[bool] = None,
1509
+ output_hidden_states: Optional[bool] = None,
1510
+ return_dict: Optional[bool] = None,
1511
+ ) -> Union[Tuple, TokenClassifierOutput]:
1512
+ r"""
1513
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1514
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1515
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1516
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1517
+ """
1518
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1519
+
1520
+ outputs = self.model(
1521
+ input_ids,
1522
+ attention_mask=attention_mask,
1523
+ position_ids=position_ids,
1524
+ past_key_values=past_key_values,
1525
+ inputs_embeds=inputs_embeds,
1526
+ use_cache=use_cache,
1527
+ output_attentions=output_attentions,
1528
+ output_hidden_states=output_hidden_states,
1529
+ return_dict=return_dict,
1530
+ )
1531
+ sequence_output = outputs[0]
1532
+ sequence_output = self.dropout(sequence_output)
1533
+ logits = self.score(sequence_output)
1534
+
1535
+ loss = None
1536
+ if labels is not None:
1537
+ loss_fct = CrossEntropyLoss()
1538
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1539
+
1540
+ if not return_dict:
1541
+ output = (logits,) + outputs[2:]
1542
+ return ((loss,) + output) if loss is not None else output
1543
+
1544
+ return TokenClassifierOutput(
1545
+ loss=loss,
1546
+ logits=logits,
1547
+ hidden_states=outputs.hidden_states,
1548
+ attentions=outputs.attentions,
1549
+ )