AnwenHu commited on
Commit
fc7239c
1 Parent(s): ccdd609

Upload 13 files

Browse files
config.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "mPLUGDocOwl2"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_mplug_docowl.MPLUGDocOwlConfig",
7
+ "AutoModel": "modeling_mplug_docowl.MPLUGDocOwl2",
8
+ "AutoModelForCausalLM": "modeling_mplug_docowl.MPLUGDocOwl2"
9
+ },
10
+ "attention_bias": false,
11
+ "bos_token_id": 1,
12
+ "eos_token_id": 2,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 4096,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 11008,
17
+ "max_position_embeddings": 2048,
18
+ "model_type": "mplug_docowl",
19
+ "num_attention_heads": 32,
20
+ "num_hidden_layers": 32,
21
+ "num_key_value_heads": 32,
22
+ "pretraining_tp": 1,
23
+ "rms_norm_eps": 1e-06,
24
+ "rope_scaling": null,
25
+ "rope_theta": 10000.0,
26
+ "tie_word_embeddings": false,
27
+ "transformers_version": "4.39.3",
28
+ "use_cache": true,
29
+ "visual_config": {
30
+ "visual_hrcompressor": {
31
+ "layer": 2,
32
+ "high_reso_cross_num_att_heads": 16,
33
+ "high_reso_cross_hid_size": 4096,
34
+ "high_reso_cross_dropout": 0.0
35
+ },
36
+ "visual_hreducer": {
37
+ "conv_shape": "1x4",
38
+ "hidden_size": 1024
39
+ },
40
+ "visual_model": {
41
+ "attention_dropout": 0.0,
42
+ "hidden_act": "quick_gelu",
43
+ "hidden_size": 1024,
44
+ "image_size": 504,
45
+ "initializer_factor": 1.0,
46
+ "initializer_range": 0.02,
47
+ "intermediate_size": 4096,
48
+ "layer_norm_eps": 1e-06,
49
+ "model_type": "mplug_owl_vision_model",
50
+ "num_attention_heads": 16,
51
+ "num_channels": 3,
52
+ "num_hidden_layers": 24,
53
+ "patch_size": 14,
54
+ "projection_dim": 768,
55
+ "use_flash_attn": false
56
+ }
57
+ },
58
+ "vocab_size": 32000
59
+ }
configuration_mplug_docowl.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ import copy
6
+ import os
7
+ from typing import Union
8
+
9
+ from transformers.configuration_utils import PretrainedConfig
10
+ from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
11
+ from transformers.utils import logging
12
+ from transformers.models.auto import CONFIG_MAPPING
13
+
14
+
15
+ class LlamaConfig(PretrainedConfig):
16
+ r"""
17
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
18
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
19
+ defaults will yield a similar configuration to that of the LLaMA-7B.
20
+
21
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
22
+ documentation from [`PretrainedConfig`] for more information.
23
+
24
+
25
+ Args:
26
+ vocab_size (`int`, *optional*, defaults to 32000):
27
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
28
+ `inputs_ids` passed when calling [`LlamaModel`]
29
+ hidden_size (`int`, *optional*, defaults to 4096):
30
+ Dimension of the hidden representations.
31
+ intermediate_size (`int`, *optional*, defaults to 11008):
32
+ Dimension of the MLP representations.
33
+ num_hidden_layers (`int`, *optional*, defaults to 32):
34
+ Number of hidden layers in the Transformer decoder.
35
+ num_attention_heads (`int`, *optional*, defaults to 32):
36
+ Number of attention heads for each attention layer in the Transformer decoder.
37
+ num_key_value_heads (`int`, *optional*):
38
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
39
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
40
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
41
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
42
+ by meanpooling all the original heads within that group. For more details checkout [this
43
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
44
+ `num_attention_heads`.
45
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
46
+ The non-linear activation function (function or string) in the decoder.
47
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
48
+ The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
49
+ Llama 2 up to 4096, CodeLlama up to 16384.
50
+ initializer_range (`float`, *optional*, defaults to 0.02):
51
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
52
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
53
+ The epsilon used by the rms normalization layers.
54
+ use_cache (`bool`, *optional*, defaults to `True`):
55
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
56
+ relevant if `config.is_decoder=True`.
57
+ pad_token_id (`int`, *optional*):
58
+ Padding token id.
59
+ bos_token_id (`int`, *optional*, defaults to 1):
60
+ Beginning of stream token id.
61
+ eos_token_id (`int`, *optional*, defaults to 2):
62
+ End of stream token id.
63
+ pretraining_tp (`int`, *optional*, defaults to 1):
64
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
65
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
66
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
67
+ issue](https://github.com/pytorch/pytorch/issues/76232).
68
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
69
+ Whether to tie weight embeddings
70
+ rope_theta (`float`, *optional*, defaults to 10000.0):
71
+ The base period of the RoPE embeddings.
72
+ rope_scaling (`Dict`, *optional*):
73
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
74
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
75
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
76
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
77
+ these scaling strategies behave:
78
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
79
+ experimental feature, subject to breaking API changes in future versions.
80
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
81
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
82
+
83
+
84
+ ```python
85
+ >>> from transformers import LlamaModel, LlamaConfig
86
+
87
+ >>> # Initializing a LLaMA llama-7b style configuration
88
+ >>> configuration = LlamaConfig()
89
+
90
+ >>> # Initializing a model from the llama-7b style configuration
91
+ >>> model = LlamaModel(configuration)
92
+
93
+ >>> # Accessing the model configuration
94
+ >>> configuration = model.config
95
+ ```"""
96
+ model_type = "llama"
97
+ keys_to_ignore_at_inference = ["past_key_values"]
98
+
99
+ def __init__(
100
+ self,
101
+ vocab_size=32000,
102
+ hidden_size=4096,
103
+ intermediate_size=11008,
104
+ num_hidden_layers=32,
105
+ num_attention_heads=32,
106
+ num_key_value_heads=None,
107
+ hidden_act="silu",
108
+ max_position_embeddings=2048,
109
+ initializer_range=0.02,
110
+ rms_norm_eps=1e-6,
111
+ use_cache=True,
112
+ pad_token_id=None,
113
+ bos_token_id=1,
114
+ eos_token_id=2,
115
+ pretraining_tp=1,
116
+ tie_word_embeddings=False,
117
+ rope_theta=10000.0,
118
+ rope_scaling=None,
119
+ attention_bias=False,
120
+ **kwargs,
121
+ ):
122
+ self.vocab_size = vocab_size
123
+ self.max_position_embeddings = max_position_embeddings
124
+ self.hidden_size = hidden_size
125
+ self.intermediate_size = intermediate_size
126
+ self.num_hidden_layers = num_hidden_layers
127
+ self.num_attention_heads = num_attention_heads
128
+
129
+ # for backward compatibility
130
+ if num_key_value_heads is None:
131
+ num_key_value_heads = num_attention_heads
132
+
133
+ self.num_key_value_heads = num_key_value_heads
134
+ self.hidden_act = hidden_act
135
+ self.initializer_range = initializer_range
136
+ self.rms_norm_eps = rms_norm_eps
137
+ self.pretraining_tp = pretraining_tp
138
+ self.use_cache = use_cache
139
+ self.rope_theta = rope_theta
140
+ self.rope_scaling = rope_scaling
141
+ self._rope_scaling_validation()
142
+ self.attention_bias = attention_bias
143
+
144
+ super().__init__(
145
+ pad_token_id=pad_token_id,
146
+ bos_token_id=bos_token_id,
147
+ eos_token_id=eos_token_id,
148
+ tie_word_embeddings=tie_word_embeddings,
149
+ **kwargs,
150
+ )
151
+
152
+ def _rope_scaling_validation(self):
153
+ """
154
+ Validate the `rope_scaling` configuration.
155
+ """
156
+ if self.rope_scaling is None:
157
+ return
158
+
159
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
160
+ raise ValueError(
161
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
162
+ f"got {self.rope_scaling}"
163
+ )
164
+ rope_scaling_type = self.rope_scaling.get("type", None)
165
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
166
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
167
+ raise ValueError(
168
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
169
+ )
170
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
171
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
172
+
173
+
174
+ class MplugOwlVisionConfig(PretrainedConfig):
175
+ r"""
176
+ This is the configuration class to store the configuration of a [`MplugOwlVisionModel`]. It is used to instantiate
177
+ a
178
+ mPLUG-Owl vision encoder according to the specified arguments, defining the model architecture. Instantiating a
179
+ configuration defaults will yield a similar configuration to that of the mPLUG-Owl
180
+ [x-plug/x_plug-llama-7b](https://huggingface.co/x-plug/x_plug-llama-7b) architecture.
181
+
182
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
183
+ documentation from [`PretrainedConfig`] for more information.
184
+
185
+ Args:
186
+ hidden_size (`int`, *optional*, defaults to 768):
187
+ Dimensionality of the encoder layers and the pooler layer.
188
+ intermediate_size (`int`, *optional*, defaults to 3072):
189
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
190
+ num_hidden_layers (`int`, *optional*, defaults to 12):
191
+ Number of hidden layers in the Transformer encoder.
192
+ num_attention_heads (`int`, *optional*, defaults to 12):
193
+ Number of attention heads for each attention layer in the Transformer encoder.
194
+ image_size (`int`, *optional*, defaults to 224):
195
+ The size (resolution) of each image.
196
+ patch_size (`int`, *optional*, defaults to 32):
197
+ The size (resolution) of each patch.
198
+ hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
199
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
200
+ `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
201
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
202
+ The epsilon used by the layer normalization layers.
203
+ attention_dropout (`float`, *optional*, defaults to 0.0):
204
+ The dropout ratio for the attention probabilities.
205
+ initializer_range (`float`, *optional*, defaults to 0.02):
206
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
207
+ initializer_factor (`float`, *optional*, defaults to 1):
208
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
209
+ testing).
210
+
211
+
212
+ ```"""
213
+
214
+ model_type = "mplug_owl_vision_model"
215
+
216
+ def __init__(
217
+ self,
218
+ hidden_size=1024,
219
+ intermediate_size=4096,
220
+ projection_dim=768,
221
+ num_hidden_layers=24,
222
+ num_attention_heads=16,
223
+ num_channels=3,
224
+ image_size=448,
225
+ patch_size=14,
226
+ hidden_act="quick_gelu",
227
+ layer_norm_eps=1e-6,
228
+ attention_dropout=0.0,
229
+ initializer_range=0.02,
230
+ initializer_factor=1.0,
231
+ use_flash_attn=False,
232
+ **kwargs,
233
+ ):
234
+ super().__init__(**kwargs)
235
+ self.hidden_size = hidden_size
236
+ self.intermediate_size = intermediate_size
237
+ self.projection_dim = projection_dim
238
+ self.num_hidden_layers = num_hidden_layers
239
+ self.num_attention_heads = num_attention_heads
240
+ self.num_channels = num_channels
241
+ self.patch_size = patch_size
242
+ self.image_size = image_size
243
+ self.initializer_range = initializer_range
244
+ self.initializer_factor = initializer_factor
245
+ self.attention_dropout = attention_dropout
246
+ self.layer_norm_eps = layer_norm_eps
247
+ self.hidden_act = hidden_act
248
+ self.use_flash_attn = use_flash_attn
249
+
250
+ @classmethod
251
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
252
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
253
+
254
+ # get the vision config dict if we are loading from MplugOwlConfig
255
+ if config_dict.get("model_type") == "mplug-owl":
256
+ config_dict = config_dict["vision_config"]
257
+
258
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
259
+ logger.warning(
260
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
261
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
262
+ )
263
+
264
+ return cls.from_dict(config_dict, **kwargs)
265
+
266
+
267
+ class MplugDocOwlHReducerConfig(PretrainedConfig):
268
+ model_type = "mplug_docowl_hreducer"
269
+
270
+ def __init__(
271
+ self,
272
+ hidden_size=1024,
273
+ initializer_range=0.02,
274
+ layer_norm_eps=1e-6,
275
+ conv_shape='1x4',
276
+ **kwargs,
277
+ ):
278
+ super().__init__(**kwargs)
279
+ self.hidden_size = hidden_size
280
+ self.initializer_range = initializer_range
281
+ self.layer_norm_eps = layer_norm_eps
282
+ self.conv_shape = conv_shape
283
+
284
+ @classmethod
285
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
286
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
287
+
288
+ # get the visual_abstractor config dict if we are loading from MplugOwlConfig
289
+ if config_dict.get("model_type") == "mplug-docowl":
290
+ config_dict = config_dict["hreducer_config"]
291
+
292
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
293
+ logger.warning(
294
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
295
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
296
+ )
297
+
298
+ return cls.from_dict(config_dict, **kwargs)
299
+
300
+
301
+ class MplugDocOwlHRDocCompressorConfig(PretrainedConfig):
302
+ model_type = "mplug_docowl_hrcompressor"
303
+
304
+ def __init__(
305
+ self,
306
+ initializer_range=0.02,
307
+ layer_norm_eps=1e-6,
308
+ layer=2,
309
+ high_reso_cross_num_att_heads=16,
310
+ high_reso_cross_hid_size=4096,
311
+ high_reso_cross_dropout=0.0,
312
+ **kwargs,
313
+ ):
314
+ super().__init__(**kwargs)
315
+ self.initializer_range = initializer_range
316
+ self.layer_norm_eps = layer_norm_eps
317
+ self.layer = layer
318
+ self.high_reso_cross_num_att_heads=high_reso_cross_num_att_heads
319
+ self.high_reso_cross_hid_size=high_reso_cross_hid_size
320
+ self.high_reso_cross_dropout=high_reso_cross_dropout
321
+
322
+ @classmethod
323
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
324
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
325
+
326
+ # get the visual_abstractor config dict if we are loading from MplugOwlConfig
327
+ if config_dict.get("model_type") == "mplug-docowl":
328
+ config_dict = config_dict["hrcompressor_config"]
329
+
330
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
331
+ logger.warning(
332
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
333
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
334
+ )
335
+
336
+ return cls.from_dict(config_dict, **kwargs)
337
+
338
+
339
+ DEFAULT_VISUAL_CONFIG = {
340
+ "visual_model": MplugOwlVisionConfig().to_dict(),
341
+ "visual_hreducer": MplugDocOwlHReducerConfig().to_dict(),
342
+ "visual_hrcompressor": MplugDocOwlHRDocCompressorConfig().to_dict()
343
+ }
344
+
345
+ class MPLUGDocOwlConfig(LlamaConfig):
346
+ model_type = "mplug_docowl"
347
+ def __init__(self, visual_config=None, **kwargs):
348
+ if visual_config is None:
349
+ self.visual_config = DEFAULT_VISUAL_CONFIG
350
+ else:
351
+ self.visual_config = visual_config
352
+
353
+ super().__init__(
354
+ **kwargs,
355
+ )
356
+
357
+ if __name__ == "__main__":
358
+ print(MplugOwlVisionConfig().to_dict())
constants.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
2
+ WORKER_HEART_BEAT_INTERVAL = 15
3
+
4
+ LOGDIR = "./demo_logs"
5
+
6
+ # Model Constants
7
+ IGNORE_INDEX = -100
8
+ IMAGE_TOKEN_INDEX = -200
9
+ DEFAULT_IMAGE_TOKEN = "<|image|>"
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 1,
3
+ "eos_token_id": 2,
4
+ "max_length": 4096,
5
+ "pad_token_id": 0,
6
+ "temperature": 0.9,
7
+ "top_p": 0.6,
8
+ "transformers_version": "4.31.0"
9
+ }
modeling_llama2_mam.py ADDED
@@ -0,0 +1,1048 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI 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 LLaMA model."""
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
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.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
32
+ from transformers.modeling_utils import PreTrainedModel
33
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
34
+ # from .configuration_llama import LlamaConfig
35
+ from .configuration_mplug_docowl import LlamaConfig
36
+
37
+ from functools import partial
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ _CONFIG_FOR_DOC = "LlamaConfig"
42
+
43
+
44
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
45
+ def _make_causal_mask(
46
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
47
+ ):
48
+ """
49
+ Make causal mask used for bi-directional self-attention.
50
+ """
51
+ bsz, tgt_len = input_ids_shape
52
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
53
+ mask_cond = torch.arange(mask.size(-1), device=device)
54
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
55
+ mask = mask.to(dtype)
56
+
57
+ if past_key_values_length > 0:
58
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
59
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
60
+
61
+
62
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
63
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
64
+ """
65
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
66
+ """
67
+ bsz, src_len = mask.size()
68
+ tgt_len = tgt_len if tgt_len is not None else src_len
69
+
70
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
71
+
72
+ inverted_mask = 1.0 - expanded_mask
73
+
74
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
75
+
76
+
77
+ class LlamaRMSNorm(nn.Module):
78
+ def __init__(self, hidden_size, eps=1e-6):
79
+ """
80
+ LlamaRMSNorm is equivalent to T5LayerNorm
81
+ """
82
+ super().__init__()
83
+ self.weight = nn.Parameter(torch.ones(hidden_size))
84
+ self.variance_epsilon = eps
85
+
86
+ def forward(self, hidden_states):
87
+ input_dtype = hidden_states.dtype
88
+ hidden_states = hidden_states.to(torch.float32)
89
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
90
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
91
+ return self.weight * hidden_states.to(input_dtype)
92
+
93
+
94
+ class LlamaRotaryEmbedding(torch.nn.Module):
95
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
96
+ super().__init__()
97
+
98
+ self.dim = dim
99
+ self.max_position_embeddings = max_position_embeddings
100
+ self.base = base
101
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
102
+ self.register_buffer("inv_freq", inv_freq)
103
+
104
+ # Build here to make `torch.jit.trace` work.
105
+ self._set_cos_sin_cache(
106
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
107
+ )
108
+
109
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
110
+ self.max_seq_len_cached = seq_len
111
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
112
+
113
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
114
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
115
+ emb = torch.cat((freqs, freqs), dim=-1)
116
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
117
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
118
+
119
+ def forward(self, x, seq_len=None):
120
+ # x: [bs, num_attention_heads, seq_len, head_size]
121
+ if seq_len > self.max_seq_len_cached:
122
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
123
+
124
+ return (
125
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
126
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
127
+ )
128
+
129
+
130
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
131
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
132
+
133
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
134
+ self.scaling_factor = scaling_factor
135
+ super().__init__(dim, max_position_embeddings, base, device)
136
+
137
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
138
+ self.max_seq_len_cached = seq_len
139
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
140
+ t = t / self.scaling_factor
141
+
142
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
143
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
144
+ emb = torch.cat((freqs, freqs), dim=-1)
145
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
146
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
147
+
148
+
149
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
150
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
151
+
152
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
153
+ self.scaling_factor = scaling_factor
154
+ super().__init__(dim, max_position_embeddings, base, device)
155
+
156
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
157
+ self.max_seq_len_cached = seq_len
158
+
159
+ if seq_len > self.max_position_embeddings:
160
+ base = self.base * (
161
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
162
+ ) ** (self.dim / (self.dim - 2))
163
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
164
+ self.register_buffer("inv_freq", inv_freq)
165
+
166
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
167
+
168
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
169
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
170
+ emb = torch.cat((freqs, freqs), dim=-1)
171
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
172
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
173
+
174
+
175
+ def rotate_half(x):
176
+ """Rotates half the hidden dims of the input."""
177
+ x1 = x[..., : x.shape[-1] // 2]
178
+ x2 = x[..., x.shape[-1] // 2 :]
179
+ return torch.cat((-x2, x1), dim=-1)
180
+
181
+
182
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
183
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
184
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
185
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
186
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
187
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
188
+ q_embed = (q * cos) + (rotate_half(q) * sin)
189
+ k_embed = (k * cos) + (rotate_half(k) * sin)
190
+ return q_embed, k_embed
191
+
192
+
193
+ class LlamaMLP(nn.Module):
194
+ def __init__(self, config):
195
+ super().__init__()
196
+ self.pretraining_tp = config.pretraining_tp
197
+ self.hidden_size = config.hidden_size
198
+ self.intermediate_size = config.intermediate_size
199
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
200
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
201
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
202
+ self.act_fn = ACT2FN[config.hidden_act]
203
+
204
+ def forward(self, x):
205
+ if self.pretraining_tp > 1:
206
+ slice = self.intermediate_size // self.pretraining_tp
207
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
208
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
209
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
210
+
211
+ gate_proj = torch.cat([F.linear(x, gate_proj_slices[i]) for i in range(self.pretraining_tp)], dim=-1)
212
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.pretraining_tp)], dim=-1)
213
+
214
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
215
+ down_proj = [F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.pretraining_tp)]
216
+ down_proj = sum(down_proj)
217
+ else:
218
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
219
+
220
+ return down_proj
221
+
222
+
223
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
224
+ """
225
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
226
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
227
+ """
228
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
229
+ if n_rep == 1:
230
+ return hidden_states
231
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
232
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
233
+
234
+
235
+
236
+ LLAMA_START_DOCSTRING = r"""
237
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
238
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
239
+ etc.)
240
+
241
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
242
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
243
+ and behavior.
244
+
245
+ Parameters:
246
+ config ([`LlamaConfig`]):
247
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
248
+ load the weights associated with the model, only the configuration. Check out the
249
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
250
+ """
251
+
252
+
253
+ @add_start_docstrings(
254
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
255
+ LLAMA_START_DOCSTRING,
256
+ )
257
+ class LlamaPreTrainedModel(PreTrainedModel):
258
+ config_class = LlamaConfig
259
+ base_model_prefix = "model"
260
+ supports_gradient_checkpointing = True
261
+ _no_split_modules = ["LlamaDecoderLayer"]
262
+ _skip_keys_device_placement = "past_key_values"
263
+
264
+ def _init_weights(self, module):
265
+ std = self.config.initializer_range
266
+ if isinstance(module, nn.Linear):
267
+ module.weight.data.normal_(mean=0.0, std=std)
268
+ if module.bias is not None:
269
+ module.bias.data.zero_()
270
+ elif isinstance(module, nn.Embedding):
271
+ module.weight.data.normal_(mean=0.0, std=std)
272
+ if module.padding_idx is not None:
273
+ module.weight.data[module.padding_idx].zero_()
274
+
275
+ def _set_gradient_checkpointing(self, module, value=False):
276
+ if isinstance(module, LlamaModel):
277
+ module.gradient_checkpointing = value
278
+
279
+
280
+ LLAMA_INPUTS_DOCSTRING = r"""
281
+ Args:
282
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
283
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
284
+ it.
285
+
286
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
287
+ [`PreTrainedTokenizer.__call__`] for details.
288
+
289
+ [What are input IDs?](../glossary#input-ids)
290
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
291
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
292
+
293
+ - 1 for tokens that are **not masked**,
294
+ - 0 for tokens that are **masked**.
295
+
296
+ [What are attention masks?](../glossary#attention-mask)
297
+
298
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
299
+ [`PreTrainedTokenizer.__call__`] for details.
300
+
301
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
302
+ `past_key_values`).
303
+
304
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
305
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
306
+ information on the default strategy.
307
+
308
+ - 1 indicates the head is **not masked**,
309
+ - 0 indicates the head is **masked**.
310
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
311
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
312
+ config.n_positions - 1]`.
313
+
314
+ [What are position IDs?](../glossary#position-ids)
315
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
316
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
317
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
318
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
319
+
320
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
321
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
322
+
323
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
324
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
325
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
326
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
327
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
328
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
329
+ model's internal embedding lookup matrix.
330
+ use_cache (`bool`, *optional*):
331
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
332
+ `past_key_values`).
333
+ output_attentions (`bool`, *optional*):
334
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
335
+ tensors for more detail.
336
+ output_hidden_states (`bool`, *optional*):
337
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
338
+ more detail.
339
+ return_dict (`bool`, *optional*):
340
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
341
+ """
342
+
343
+
344
+ @add_start_docstrings(
345
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
346
+ LLAMA_START_DOCSTRING,
347
+ )
348
+ class LlamaModel(LlamaPreTrainedModel):
349
+ """
350
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
351
+
352
+ Args:
353
+ config: LlamaConfig
354
+ """
355
+
356
+ def __init__(self, config: LlamaConfig):
357
+ super().__init__(config)
358
+ self.padding_idx = config.pad_token_id
359
+ self.vocab_size = config.vocab_size
360
+
361
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
362
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
363
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
364
+
365
+ self.gradient_checkpointing = False
366
+ # Initialize weights and apply final processing
367
+ self.post_init()
368
+
369
+ def get_input_embeddings(self):
370
+ return self.embed_tokens
371
+
372
+ def set_input_embeddings(self, value):
373
+ self.embed_tokens = value
374
+
375
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
376
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
377
+ # create causal mask
378
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
379
+ combined_attention_mask = None
380
+ if input_shape[-1] > 1:
381
+ combined_attention_mask = _make_causal_mask(
382
+ input_shape,
383
+ inputs_embeds.dtype,
384
+ device=inputs_embeds.device,
385
+ past_key_values_length=past_key_values_length,
386
+ )
387
+
388
+ if attention_mask is not None:
389
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
390
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
391
+ inputs_embeds.device
392
+ )
393
+ combined_attention_mask = (
394
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
395
+ )
396
+
397
+ return combined_attention_mask
398
+
399
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
400
+ # copy from mplug-owl2 (https://github.com/X-PLUG/mPLUG-Owl/tree/main/mPLUG-Owl2)
401
+ def forward(
402
+ self,
403
+ input_ids: torch.LongTensor = None,
404
+ modality_indicators: torch.Tensor = None,
405
+ attention_mask: Optional[torch.Tensor] = None,
406
+ position_ids: Optional[torch.LongTensor] = None,
407
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
408
+ inputs_embeds: Optional[torch.FloatTensor] = None,
409
+ use_cache: Optional[bool] = None,
410
+ output_attentions: Optional[bool] = None,
411
+ output_hidden_states: Optional[bool] = None,
412
+ return_dict: Optional[bool] = None,
413
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
414
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
415
+ output_hidden_states = (
416
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
417
+ )
418
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
419
+
420
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
421
+
422
+ # retrieve input_ids and inputs_embeds
423
+ if input_ids is not None and inputs_embeds is not None:
424
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
425
+ elif input_ids is not None:
426
+ batch_size, seq_length = input_ids.shape
427
+ elif inputs_embeds is not None:
428
+ batch_size, seq_length, _ = inputs_embeds.shape
429
+ else:
430
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
431
+
432
+ seq_length_with_past = seq_length
433
+ past_key_values_length = 0
434
+
435
+ if past_key_values is not None:
436
+ past_key_values_length = past_key_values[0][0].shape[2]
437
+ seq_length_with_past = seq_length_with_past + past_key_values_length
438
+
439
+ if position_ids is None:
440
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
441
+ position_ids = torch.arange(
442
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
443
+ )
444
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
445
+ else:
446
+ position_ids = position_ids.view(-1, seq_length).long()
447
+
448
+ if inputs_embeds is None:
449
+ inputs_embeds = self.embed_tokens(input_ids)
450
+ # embed positions
451
+ if attention_mask is None:
452
+ attention_mask = torch.ones(
453
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
454
+ )
455
+ attention_mask = self._prepare_decoder_attention_mask(
456
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
457
+ )
458
+
459
+ hidden_states = inputs_embeds
460
+
461
+ if self.gradient_checkpointing and self.training:
462
+ if use_cache:
463
+ logger.warning_once(
464
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
465
+ )
466
+ use_cache = False
467
+
468
+ # decoder layers
469
+ all_hidden_states = () if output_hidden_states else None
470
+ all_self_attns = () if output_attentions else None
471
+ next_decoder_cache = () if use_cache else None
472
+
473
+ for idx, decoder_layer in enumerate(self.layers):
474
+ if output_hidden_states:
475
+ all_hidden_states += (hidden_states,)
476
+
477
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
478
+
479
+ if self.gradient_checkpointing and self.training:
480
+
481
+ def create_custom_forward(module):
482
+ def custom_forward(*inputs):
483
+ # None for past_key_value
484
+ return module(*inputs, past_key_value, output_attentions)
485
+
486
+ return custom_forward
487
+
488
+ layer_outputs = torch.utils.checkpoint.checkpoint(
489
+ create_custom_forward(decoder_layer),
490
+ hidden_states,
491
+ modality_indicators,
492
+ attention_mask,
493
+ position_ids,
494
+ )
495
+ else:
496
+ layer_outputs = decoder_layer(
497
+ hidden_states,
498
+ modality_indicators=modality_indicators,
499
+ attention_mask=attention_mask,
500
+ position_ids=position_ids,
501
+ past_key_value=past_key_value,
502
+ output_attentions=output_attentions,
503
+ use_cache=use_cache,
504
+ )
505
+
506
+ hidden_states = layer_outputs[0]
507
+
508
+ if use_cache:
509
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
510
+
511
+ if output_attentions:
512
+ all_self_attns += (layer_outputs[1],)
513
+
514
+ hidden_states = self.norm(hidden_states)
515
+
516
+ # add hidden states from the last decoder layer
517
+ if output_hidden_states:
518
+ all_hidden_states += (hidden_states,)
519
+
520
+ next_cache = next_decoder_cache if use_cache else None
521
+ if not return_dict:
522
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
523
+ return BaseModelOutputWithPast(
524
+ last_hidden_state=hidden_states,
525
+ past_key_values=next_cache,
526
+ hidden_states=all_hidden_states,
527
+ attentions=all_self_attns,
528
+ )
529
+
530
+
531
+ class LlamaForCausalLM(LlamaPreTrainedModel):
532
+ _tied_weights_keys = ["lm_head.weight"]
533
+
534
+ def __init__(self, config):
535
+ super().__init__(config)
536
+ self.model = LlamaModel(config)
537
+ self.pretraining_tp = config.pretraining_tp
538
+ self.vocab_size = config.vocab_size
539
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
540
+
541
+ # Initialize weights and apply final processing
542
+ self.post_init()
543
+
544
+ def get_input_embeddings(self):
545
+ return self.model.embed_tokens
546
+
547
+ def set_input_embeddings(self, value):
548
+ self.model.embed_tokens = value
549
+
550
+ def get_output_embeddings(self):
551
+ return self.lm_head
552
+
553
+ def set_output_embeddings(self, new_embeddings):
554
+ self.lm_head = new_embeddings
555
+
556
+ def set_decoder(self, decoder):
557
+ self.model = decoder
558
+
559
+ def get_decoder(self):
560
+ return self.model
561
+
562
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
563
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
564
+ # copy from mplug-owl2 (https://github.com/X-PLUG/mPLUG-Owl/tree/main/mPLUG-Owl2)
565
+ def forward(
566
+ self,
567
+ input_ids: torch.LongTensor = None,
568
+ modality_indicators: torch.Tensor = None,
569
+ attention_mask: Optional[torch.Tensor] = None,
570
+ position_ids: Optional[torch.LongTensor] = None,
571
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
572
+ inputs_embeds: Optional[torch.FloatTensor] = None,
573
+ labels: Optional[torch.LongTensor] = None,
574
+ use_cache: Optional[bool] = None,
575
+ output_attentions: Optional[bool] = None,
576
+ output_hidden_states: Optional[bool] = None,
577
+ return_dict: Optional[bool] = None,
578
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
579
+ r"""
580
+ Args:
581
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
582
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
583
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
584
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
585
+
586
+ Returns:
587
+
588
+ Example:
589
+
590
+ ```python
591
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
592
+
593
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
594
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
595
+
596
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
597
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
598
+
599
+ >>> # Generate
600
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
601
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
602
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
603
+ ```"""
604
+
605
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
606
+ output_hidden_states = (
607
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
608
+ )
609
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
610
+
611
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
612
+ outputs = self.model(
613
+ input_ids=input_ids,
614
+ modality_indicators=modality_indicators,
615
+ attention_mask=attention_mask,
616
+ position_ids=position_ids,
617
+ past_key_values=past_key_values,
618
+ inputs_embeds=inputs_embeds,
619
+ use_cache=use_cache,
620
+ output_attentions=output_attentions,
621
+ output_hidden_states=output_hidden_states,
622
+ return_dict=return_dict,
623
+ )
624
+
625
+ hidden_states = outputs[0]
626
+ if self.config.pretraining_tp > 1:
627
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
628
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
629
+ logits = torch.cat(logits, dim=-1)
630
+ else:
631
+ logits = self.lm_head(hidden_states)
632
+ logits = logits.float()
633
+
634
+ loss = None
635
+ if labels is not None:
636
+ # Shift so that tokens < n predict n
637
+ shift_logits = logits[..., :-1, :].contiguous()
638
+ shift_labels = labels[..., 1:].contiguous()
639
+ # Flatten the tokens
640
+ loss_fct = CrossEntropyLoss()
641
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
642
+ shift_labels = shift_labels.view(-1)
643
+ # Enable model parallelism
644
+ shift_labels = shift_labels.to(shift_logits.device)
645
+ loss = loss_fct(shift_logits, shift_labels)
646
+
647
+ if not return_dict:
648
+ output = (logits,) + outputs[1:]
649
+ return (loss,) + output if loss is not None else output
650
+
651
+ return CausalLMOutputWithPast(
652
+ loss=loss,
653
+ logits=logits,
654
+ past_key_values=outputs.past_key_values,
655
+ hidden_states=outputs.hidden_states,
656
+ attentions=outputs.attentions,
657
+ )
658
+
659
+ def prepare_inputs_for_generation(
660
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
661
+ ):
662
+ if past_key_values:
663
+ input_ids = input_ids[:, -1:]
664
+
665
+ position_ids = kwargs.get("position_ids", None)
666
+ if attention_mask is not None and position_ids is None:
667
+ # create position_ids on the fly for batch generation
668
+ position_ids = attention_mask.long().cumsum(-1) - 1
669
+ position_ids.masked_fill_(attention_mask == 0, 1)
670
+ if past_key_values:
671
+ position_ids = position_ids[:, -1].unsqueeze(-1)
672
+
673
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
674
+ if inputs_embeds is not None and past_key_values is None:
675
+ model_inputs = {"inputs_embeds": inputs_embeds}
676
+ else:
677
+ model_inputs = {"input_ids": input_ids}
678
+
679
+ model_inputs.update(
680
+ {
681
+ "position_ids": position_ids,
682
+ "past_key_values": past_key_values,
683
+ "use_cache": kwargs.get("use_cache"),
684
+ "attention_mask": attention_mask,
685
+ }
686
+ )
687
+ return model_inputs
688
+
689
+ @staticmethod
690
+ def _reorder_cache(past_key_values, beam_idx):
691
+ reordered_past = ()
692
+ for layer_past in past_key_values:
693
+ reordered_past += (
694
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
695
+ )
696
+ return reordered_past
697
+
698
+
699
+ @add_start_docstrings(
700
+ """
701
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
702
+
703
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
704
+ (e.g. GPT-2) do.
705
+
706
+ Since it does classification on the last token, it requires to know the position of the last token. If a
707
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
708
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
709
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
710
+ each row of the batch).
711
+ """,
712
+ LLAMA_START_DOCSTRING,
713
+ )
714
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
715
+ def __init__(self, config):
716
+ super().__init__(config)
717
+ self.num_labels = config.num_labels
718
+ self.model = LlamaModel(config)
719
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
720
+
721
+ # Initialize weights and apply final processing
722
+ self.post_init()
723
+
724
+ def get_input_embeddings(self):
725
+ return self.model.embed_tokens
726
+
727
+ def set_input_embeddings(self, value):
728
+ self.model.embed_tokens = value
729
+
730
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
731
+ def forward(
732
+ self,
733
+ input_ids: torch.LongTensor = None,
734
+ attention_mask: Optional[torch.Tensor] = None,
735
+ position_ids: Optional[torch.LongTensor] = None,
736
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
737
+ inputs_embeds: Optional[torch.FloatTensor] = None,
738
+ labels: Optional[torch.LongTensor] = None,
739
+ use_cache: Optional[bool] = None,
740
+ output_attentions: Optional[bool] = None,
741
+ output_hidden_states: Optional[bool] = None,
742
+ return_dict: Optional[bool] = None,
743
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
744
+ r"""
745
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
746
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
747
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
748
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
749
+ """
750
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
751
+
752
+ transformer_outputs = self.model(
753
+ input_ids,
754
+ attention_mask=attention_mask,
755
+ position_ids=position_ids,
756
+ past_key_values=past_key_values,
757
+ inputs_embeds=inputs_embeds,
758
+ use_cache=use_cache,
759
+ output_attentions=output_attentions,
760
+ output_hidden_states=output_hidden_states,
761
+ return_dict=return_dict,
762
+ )
763
+ hidden_states = transformer_outputs[0]
764
+ logits = self.score(hidden_states)
765
+
766
+ if input_ids is not None:
767
+ batch_size = input_ids.shape[0]
768
+ else:
769
+ batch_size = inputs_embeds.shape[0]
770
+
771
+ if self.config.pad_token_id is None and batch_size != 1:
772
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
773
+ if self.config.pad_token_id is None:
774
+ sequence_lengths = -1
775
+ else:
776
+ if input_ids is not None:
777
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
778
+ else:
779
+ sequence_lengths = -1
780
+
781
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
782
+
783
+ loss = None
784
+ if labels is not None:
785
+ labels = labels.to(logits.device)
786
+ if self.config.problem_type is None:
787
+ if self.num_labels == 1:
788
+ self.config.problem_type = "regression"
789
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
790
+ self.config.problem_type = "single_label_classification"
791
+ else:
792
+ self.config.problem_type = "multi_label_classification"
793
+
794
+ if self.config.problem_type == "regression":
795
+ loss_fct = MSELoss()
796
+ if self.num_labels == 1:
797
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
798
+ else:
799
+ loss = loss_fct(pooled_logits, labels)
800
+ elif self.config.problem_type == "single_label_classification":
801
+ loss_fct = CrossEntropyLoss()
802
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
803
+ elif self.config.problem_type == "multi_label_classification":
804
+ loss_fct = BCEWithLogitsLoss()
805
+ loss = loss_fct(pooled_logits, labels)
806
+ if not return_dict:
807
+ output = (pooled_logits,) + transformer_outputs[1:]
808
+ return ((loss,) + output) if loss is not None else output
809
+
810
+ return SequenceClassifierOutputWithPast(
811
+ loss=loss,
812
+ logits=pooled_logits,
813
+ past_key_values=transformer_outputs.past_key_values,
814
+ hidden_states=transformer_outputs.hidden_states,
815
+ attentions=transformer_outputs.attentions,
816
+ )
817
+
818
+ # copy from mplug-owl2 (https://github.com/X-PLUG/mPLUG-Owl/tree/main/mPLUG-Owl2)
819
+ class MultiwayNetwork(nn.Module):
820
+
821
+ def __init__(self, module_provider, num_multiway=2):
822
+ super(MultiwayNetwork, self).__init__()
823
+
824
+ self.multiway = torch.nn.ModuleList([module_provider() for _ in range(num_multiway)])
825
+
826
+ def forward(self, hidden_states, multiway_indices):
827
+
828
+ if len(self.multiway) == 1:
829
+ return self.multiway[0](hidden_states)
830
+
831
+ output_hidden_states = torch.empty_like(hidden_states)
832
+
833
+ for idx, subway in enumerate(self.multiway):
834
+ local_indices = multiway_indices.eq(idx).nonzero(as_tuple=True)
835
+ hidden = hidden_states[local_indices].unsqueeze(1).contiguous()
836
+ if hidden.numel():
837
+ output = subway(hidden)
838
+ if isinstance(output, tuple):
839
+ output = output[0]
840
+ output = output.squeeze(1)
841
+ output_hidden_states[local_indices] = output
842
+
843
+ return output_hidden_states.contiguous()
844
+
845
+ # copy from mplug-owl2 (https://github.com/X-PLUG/mPLUG-Owl/tree/main/mPLUG-Owl2)
846
+ class LlamaAttention(nn.Module):
847
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
848
+
849
+ def __init__(self, config: LlamaConfig):
850
+ super().__init__()
851
+ self.config = config
852
+ self.hidden_size = config.hidden_size
853
+ self.num_heads = config.num_attention_heads
854
+ self.head_dim = self.hidden_size // self.num_heads
855
+ self.num_key_value_heads = config.num_key_value_heads
856
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
857
+ self.max_position_embeddings = config.max_position_embeddings
858
+ self.rope_theta = config.rope_theta
859
+
860
+ if (self.head_dim * self.num_heads) != self.hidden_size:
861
+ raise ValueError(
862
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
863
+ f" and `num_heads`: {self.num_heads})."
864
+ )
865
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
866
+ self.k_proj = MultiwayNetwork(module_provider=partial(
867
+ nn.Linear, in_features=self.hidden_size, out_features=self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
868
+ )
869
+ self.v_proj = MultiwayNetwork(module_provider=partial(
870
+ nn.Linear, in_features=self.hidden_size, out_features=self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
871
+ )
872
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
873
+ self._init_rope()
874
+
875
+ def _init_rope(self):
876
+ if self.config.rope_scaling is None:
877
+ self.rotary_emb = LlamaRotaryEmbedding(
878
+ self.head_dim,
879
+ max_position_embeddings=self.max_position_embeddings,
880
+ base=self.rope_theta,
881
+ )
882
+ else:
883
+ scaling_type = self.config.rope_scaling["type"]
884
+ scaling_factor = self.config.rope_scaling["factor"]
885
+ if scaling_type == "linear":
886
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
887
+ self.head_dim,
888
+ max_position_embeddings=self.max_position_embeddings,
889
+ scaling_factor=scaling_factor,
890
+ base=self.rope_theta,
891
+ )
892
+ elif scaling_type == "dynamic":
893
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
894
+ self.head_dim,
895
+ max_position_embeddings=self.max_position_embeddings,
896
+ scaling_factor=scaling_factor,
897
+ base=self.rope_theta,
898
+ )
899
+ else:
900
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
901
+
902
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
903
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
904
+
905
+ def forward(
906
+ self,
907
+ hidden_states: torch.Tensor,
908
+ modality_indicators: torch.Tensor,
909
+ attention_mask: Optional[torch.Tensor] = None,
910
+ position_ids: Optional[torch.LongTensor] = None,
911
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
912
+ output_attentions: bool = False,
913
+ use_cache: bool = False,
914
+ padding_mask: Optional[torch.LongTensor] = None,
915
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
916
+ bsz, q_len, _ = hidden_states.size()
917
+
918
+ query_states = self.q_proj(hidden_states, )
919
+ key_states = self.k_proj(hidden_states, modality_indicators)
920
+ value_states = self.v_proj(hidden_states, modality_indicators)
921
+
922
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
923
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
924
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
925
+
926
+ kv_seq_len = key_states.shape[-2]
927
+ if past_key_value is not None:
928
+ kv_seq_len += past_key_value[0].shape[-2]
929
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
930
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
931
+
932
+ if past_key_value is not None:
933
+ # reuse k, v, self_attention
934
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
935
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
936
+
937
+ past_key_value = (key_states, value_states) if use_cache else None
938
+
939
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
940
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
941
+
942
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
943
+
944
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
945
+ raise ValueError(
946
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
947
+ f" {attn_weights.size()}"
948
+ )
949
+
950
+ if attention_mask is not None:
951
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
952
+ raise ValueError(
953
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
954
+ )
955
+ attn_weights = attn_weights + attention_mask
956
+
957
+ # upcast attention to fp32
958
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
959
+ attn_output = torch.matmul(attn_weights, value_states)
960
+
961
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
962
+ raise ValueError(
963
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
964
+ f" {attn_output.size()}"
965
+ )
966
+
967
+ attn_output = attn_output.transpose(1, 2).contiguous()
968
+
969
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
970
+
971
+ attn_output = self.o_proj(attn_output)
972
+
973
+ if not output_attentions:
974
+ attn_weights = None
975
+
976
+ return attn_output, attn_weights, past_key_value
977
+
978
+
979
+ # copy from mplug-owl2 (https://github.com/X-PLUG/mPLUG-Owl/tree/main/mPLUG-Owl2)
980
+ class LlamaDecoderLayer(nn.Module):
981
+ def __init__(self, config: LlamaConfig):
982
+ super().__init__()
983
+ self.hidden_size = config.hidden_size
984
+ self.self_attn = LlamaAttention(config=config)
985
+ self.mlp = LlamaMLP(config)
986
+ self.input_layernorm = MultiwayNetwork(module_provider=partial(
987
+ LlamaRMSNorm, hidden_size=config.hidden_size, eps=config.rms_norm_eps
988
+ ))
989
+ self.post_attention_layernorm = MultiwayNetwork(module_provider=partial(
990
+ LlamaRMSNorm, hidden_size=config.hidden_size, eps=config.rms_norm_eps
991
+ ))
992
+
993
+ def forward(
994
+ self,
995
+ hidden_states: torch.Tensor,
996
+ modality_indicators: torch.Tensor = None,
997
+ attention_mask: Optional[torch.Tensor] = None,
998
+ position_ids: Optional[torch.LongTensor] = None,
999
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1000
+ output_attentions: Optional[bool] = False,
1001
+ use_cache: Optional[bool] = False,
1002
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1003
+ """
1004
+ Args:
1005
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1006
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
1007
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
1008
+ output_attentions (`bool`, *optional*):
1009
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1010
+ returned tensors for more detail.
1011
+ use_cache (`bool`, *optional*):
1012
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1013
+ (see `past_key_values`).
1014
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1015
+ """
1016
+
1017
+ residual = hidden_states
1018
+
1019
+ hidden_states = self.input_layernorm(hidden_states, modality_indicators)
1020
+
1021
+ # Self Attention
1022
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1023
+ hidden_states=hidden_states,
1024
+ modality_indicators=modality_indicators,
1025
+ attention_mask=attention_mask,
1026
+ position_ids=position_ids,
1027
+ past_key_value=past_key_value,
1028
+ output_attentions=output_attentions,
1029
+ use_cache=use_cache,
1030
+ )
1031
+ hidden_states = residual + hidden_states
1032
+
1033
+ # Fully Connected
1034
+ residual = hidden_states
1035
+ hidden_states = self.post_attention_layernorm(hidden_states, modality_indicators)
1036
+ hidden_states = self.mlp(hidden_states)
1037
+ hidden_states = residual + hidden_states
1038
+
1039
+ outputs = (hidden_states,)
1040
+
1041
+ if output_attentions:
1042
+ outputs += (self_attn_weights,)
1043
+
1044
+ if use_cache:
1045
+ outputs += (present_key_value,)
1046
+
1047
+ return outputs
1048
+
modeling_mplug_docowl.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu & Qinghao Ye (Modified from LLaVA)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from abc import ABC, abstractmethod
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ from torch.nn import CrossEntropyLoss
21
+
22
+ from transformers import AutoConfig, AutoModelForCausalLM
23
+ from .modeling_llama2_mam import LlamaConfig, LlamaModel, LlamaForCausalLM
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+
26
+ from .configuration_mplug_docowl import (MPLUGDocOwlConfig, MplugOwlVisionConfig, MplugDocOwlHReducerConfig, MplugDocOwlHRDocCompressorConfig)
27
+ from .visual_encoder import MplugOwlVisionModel, MplugDocOwlHReducerModel
28
+ from .visual_compressor import MplugDocOwlHRDocCompressor
29
+ from .processor import DocProcessor
30
+
31
+ from .constants import IMAGE_TOKEN_INDEX, IGNORE_INDEX
32
+ from icecream import ic
33
+
34
+ from transformers import StoppingCriteria, TextStreamer
35
+
36
+ class KeywordsStoppingCriteria(StoppingCriteria):
37
+ def __init__(self, keywords, tokenizer, input_ids):
38
+ self.keywords = keywords
39
+ self.keyword_ids = []
40
+ self.max_keyword_len = 0
41
+ for keyword in keywords:
42
+ cur_keyword_ids = tokenizer(keyword).input_ids
43
+ if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
44
+ cur_keyword_ids = cur_keyword_ids[1:]
45
+ if len(cur_keyword_ids) > self.max_keyword_len:
46
+ self.max_keyword_len = len(cur_keyword_ids)
47
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
48
+ self.tokenizer = tokenizer
49
+ self.start_len = input_ids.shape[1]
50
+
51
+ def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
52
+ assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
53
+ offset = min(output_ids.shape[1] - self.start_len, self.max_keyword_len)
54
+ self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
55
+ for keyword_id in self.keyword_ids:
56
+ if (output_ids[0, -keyword_id.shape[0]:] == keyword_id).all():
57
+ return True
58
+ outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
59
+ for keyword in self.keywords:
60
+ if keyword in outputs:
61
+ return True
62
+ return False
63
+
64
+ class MPLUGDocOwlMetaModel:
65
+ _no_split_modules = ["MplugOwlVisionModel", "MplugDocOwlHReducerModel", "MplugDocOwlHRDocCompressor"]
66
+ def __init__(self, config):
67
+ super(MPLUGDocOwlMetaModel, self).__init__(config)
68
+ self.vision_model = MplugOwlVisionModel(
69
+ MplugOwlVisionConfig(**config.visual_config["visual_model"])
70
+ )
71
+ v_img_row_tokens = int((config.visual_config["visual_model"]['image_size']/config.visual_config["visual_model"]['patch_size']))
72
+ v_img_col_tokens = v_img_row_tokens
73
+
74
+ self.vision2text = MplugDocOwlHReducerModel(
75
+ MplugDocOwlHReducerConfig(**config.visual_config["visual_hreducer"]), config.hidden_size
76
+ )
77
+
78
+ horizontal_reduce = int(config.visual_config["visual_hreducer"]['conv_shape'].split('x')[1])
79
+ v2t_img_col_tokens = int(v_img_row_tokens / horizontal_reduce)
80
+
81
+ self.hr_compressor = MplugDocOwlHRDocCompressor(
82
+ MplugDocOwlHRDocCompressorConfig(**config.visual_config["visual_hrcompressor"]),
83
+ config.hidden_size,
84
+ v2t_img_col_tokens
85
+ )
86
+
87
+ def get_vision_tower(self):
88
+ vision_model = getattr(self, 'vision_model', None)
89
+ if type(vision_model) is list:
90
+ vision_model = vision_model[0]
91
+ return vision_model
92
+
93
+ def get_vision2text(self):
94
+ vision2text = getattr(self, 'vision2text', None)
95
+ if type(vision2text) is list:
96
+ vision2text = vision2text[0]
97
+ return vision2text
98
+
99
+ def get_hrcompressor(self):
100
+ hrcompressor = getattr(self, 'hr_compressor', None)
101
+ if type(hrcompressor) is list:
102
+ hrcompressor = hrcompressor[0]
103
+ return hrcompressor
104
+
105
+ class MPLUGDocOwlMetaForCausalLM(ABC):
106
+ @abstractmethod
107
+ def get_model(self):
108
+ pass
109
+
110
+ def encode_images(self, images, patch_positions):
111
+ image_features = self.get_model().vision_model(images).last_hidden_state
112
+ image_features = self.get_model().vision2text(encoder_hidden_states=image_features)
113
+ image_features = self.get_model().hr_compressor(hidden_states=image_features, patch_positions=patch_positions)
114
+ return image_features
115
+
116
+ def prepare_inputs_labels_for_multimodal(
117
+ self, input_ids, attention_mask, past_key_values, labels, images, patch_positions
118
+ ):
119
+ # ic(images.shape, patch_positions.shape)
120
+ if images is None or input_ids.shape[1] == 1:
121
+ if past_key_values is not None and images is not None and input_ids.shape[1] == 1:
122
+ attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device)
123
+ multiway_indices = torch.zeros_like(input_ids).long().to(self.device)
124
+ return input_ids, multiway_indices, attention_mask, past_key_values, None, labels
125
+
126
+ if type(images) is list or images.ndim == 5:
127
+ concat_images = torch.cat([image for image in images], dim=0)
128
+ image_features = self.encode_images(concat_images, patch_positions)
129
+ split_sizes = [image.shape[0] for image in images]
130
+ image_features = torch.split(image_features, split_sizes, dim=0)
131
+ image_features = [x.flatten(0, 1) for x in image_features]
132
+ else:
133
+ image_features = self.encode_images(images, patch_positions) # Sum(Crop Image Number) x L x d
134
+
135
+ new_input_embeds = []
136
+ new_modality_indicators = []
137
+ new_labels = [] if labels is not None else None
138
+ cur_image_idx = 0
139
+ for batch_idx, cur_input_ids in enumerate(input_ids):
140
+ if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0:
141
+ # multimodal LLM, but the current sample is not multimodal
142
+ # FIXME: this is a hacky fix, for deepspeed zero3 to work
143
+ half_len = cur_input_ids.shape[0] // 2
144
+ cur_image_features = image_features[cur_image_idx]
145
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids[:half_len])
146
+ cur_input_embeds_2 = self.get_model().embed_tokens(cur_input_ids[half_len:])
147
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0], cur_input_embeds_2], dim=0)
148
+ new_input_embeds.append(cur_input_embeds)
149
+
150
+ cur_modality_indicators = torch.zeros(len(cur_input_embeds)).long().to(self.device)
151
+ new_modality_indicators.append(cur_modality_indicators)
152
+ if labels is not None:
153
+ new_labels.append(labels[batch_idx])
154
+ cur_image_idx += 1
155
+ continue
156
+ image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
157
+ cur_new_input_embeds = []
158
+ cur_modality_indicators = []
159
+ if labels is not None:
160
+ cur_labels = labels[batch_idx]
161
+ cur_new_labels = []
162
+ assert cur_labels.shape == cur_input_ids.shape
163
+ while image_token_indices.numel() > 0:
164
+ cur_image_features = image_features[cur_image_idx]
165
+ image_token_start = image_token_indices[0]
166
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start]))
167
+ cur_new_input_embeds.append(cur_image_features)
168
+
169
+ # Add modality indicator
170
+ assert image_token_start == len(cur_input_ids[:image_token_start])
171
+ cur_modality_indicators.append(torch.zeros(len(cur_input_ids[:image_token_start])).long())
172
+ cur_modality_indicators.append(torch.ones(len(cur_image_features)).long())
173
+
174
+ if labels is not None:
175
+ cur_new_labels.append(cur_labels[:image_token_start])
176
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
177
+ cur_labels = cur_labels[image_token_start+1:]
178
+ cur_image_idx += 1
179
+ cur_input_ids = cur_input_ids[image_token_start+1:]
180
+ image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
181
+ if cur_input_ids.numel() > 0:
182
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids))
183
+ cur_modality_indicators.append(torch.zeros(len(cur_input_ids)).long())
184
+ if labels is not None:
185
+ cur_new_labels.append(cur_labels)
186
+ cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds]
187
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0)
188
+ new_input_embeds.append(cur_new_input_embeds)
189
+
190
+ # Modality
191
+ cur_modality_indicators = [x.to(device=self.device) for x in cur_modality_indicators]
192
+ cur_modality_indicators = torch.cat(cur_modality_indicators, dim=0)
193
+ new_modality_indicators.append(cur_modality_indicators)
194
+
195
+
196
+ if labels is not None:
197
+ cur_new_labels = torch.cat(cur_new_labels, dim=0)
198
+ new_labels.append(cur_new_labels)
199
+
200
+ if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds):
201
+ max_len = max(x.shape[0] for x in new_input_embeds)
202
+
203
+ # Embedding
204
+ new_input_embeds_align = []
205
+ for cur_new_embed in new_input_embeds:
206
+ cur_new_embed = torch.cat((cur_new_embed, torch.zeros((max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0)
207
+ new_input_embeds_align.append(cur_new_embed)
208
+ new_input_embeds = torch.stack(new_input_embeds_align, dim=0)
209
+
210
+ # Modality
211
+ new_modality_indicators_align = []
212
+ for cur_modality_indicator in new_modality_indicators:
213
+ cur_new_embed = torch.cat((cur_modality_indicator, torch.zeros(max_len - cur_modality_indicator.shape[0], dtype=cur_modality_indicator.dtype, device=cur_modality_indicator.device)), dim=0)
214
+ new_modality_indicators_align.append(cur_new_embed)
215
+ new_modality_indicators = torch.stack(new_modality_indicators_align, dim=0)
216
+
217
+ # Label
218
+ if labels is not None:
219
+ new_labels_align = []
220
+ _new_labels = new_labels
221
+ for cur_new_label in new_labels:
222
+ cur_new_label = torch.cat((cur_new_label, torch.full((max_len - cur_new_label.shape[0],), IGNORE_INDEX, dtype=cur_new_label.dtype, device=cur_new_label.device)), dim=0)
223
+ new_labels_align.append(cur_new_label)
224
+ new_labels = torch.stack(new_labels_align, dim=0)
225
+
226
+ # Attention Mask
227
+ if attention_mask is not None:
228
+ new_attention_mask = []
229
+ for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(attention_mask, _new_labels, new_labels):
230
+ new_attn_mask_pad_left = torch.full((cur_new_labels.shape[0] - labels.shape[1],), True, dtype=attention_mask.dtype, device=attention_mask.device)
231
+ new_attn_mask_pad_right = torch.full((cur_new_labels_align.shape[0] - cur_new_labels.shape[0],), False, dtype=attention_mask.dtype, device=attention_mask.device)
232
+ cur_new_attention_mask = torch.cat((new_attn_mask_pad_left, cur_attention_mask, new_attn_mask_pad_right), dim=0)
233
+ new_attention_mask.append(cur_new_attention_mask)
234
+ attention_mask = torch.stack(new_attention_mask, dim=0)
235
+ assert attention_mask.shape == new_labels.shape
236
+ else:
237
+ new_input_embeds = torch.stack(new_input_embeds, dim=0)
238
+ new_modality_indicators = torch.stack(new_modality_indicators, dim=0)
239
+ if labels is not None:
240
+ new_labels = torch.stack(new_labels, dim=0)
241
+
242
+ if attention_mask is not None:
243
+ new_attn_mask_pad_left = torch.full((attention_mask.shape[0], new_input_embeds.shape[1] - input_ids.shape[1]), True, dtype=attention_mask.dtype, device=attention_mask.device)
244
+ attention_mask = torch.cat((new_attn_mask_pad_left, attention_mask), dim=1)
245
+ assert attention_mask.shape == new_input_embeds.shape[:2]
246
+ return None, new_modality_indicators, attention_mask, past_key_values, new_input_embeds, new_labels
247
+
248
+
249
+
250
+ class MPLUGDocOwlLlamaModel(MPLUGDocOwlMetaModel, LlamaModel):
251
+ config_class = MPLUGDocOwlConfig
252
+
253
+ def __init__(self, config: MPLUGDocOwlConfig):
254
+ super(MPLUGDocOwlLlamaModel, self).__init__(config)
255
+
256
+
257
+ class MPLUGDocOwl2(LlamaForCausalLM, MPLUGDocOwlMetaForCausalLM):
258
+ config_class = MPLUGDocOwlConfig
259
+
260
+ def __init__(self, config):
261
+ super(LlamaForCausalLM, self).__init__(config)
262
+ self.model = MPLUGDocOwlLlamaModel(config)
263
+
264
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
265
+
266
+ # Initialize weights and apply final processing
267
+ self.post_init()
268
+
269
+ def init_processor(self, tokenizer, basic_image_size, crop_anchors):
270
+ self.processor = DocProcessor(tokenizer=tokenizer, image_size=basic_image_size, anchors=crop_anchors)
271
+ return self.processor
272
+
273
+ def get_model(self):
274
+ return self.model
275
+
276
+ def forward(
277
+ self,
278
+ input_ids: torch.LongTensor = None,
279
+ # modality_indicators: torch.LongTensor = None,
280
+ attention_mask: Optional[torch.Tensor] = None,
281
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
282
+ inputs_embeds: Optional[torch.FloatTensor] = None,
283
+ labels: Optional[torch.LongTensor] = None,
284
+ use_cache: Optional[bool] = None,
285
+ output_attentions: Optional[bool] = None,
286
+ output_hidden_states: Optional[bool] = None,
287
+ images: Optional[torch.FloatTensor] = None,
288
+ patch_positions: Optional[torch.LongTensor] = None,
289
+ return_dict: Optional[bool] = None,
290
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
291
+
292
+ # print('modeling_mplug_docow2.py patch_positions:', patch_positions)
293
+
294
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
295
+ output_hidden_states = (
296
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
297
+ )
298
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
299
+ input_ids, modality_indicators, attention_mask, past_key_values, inputs_embeds, labels = \
300
+ self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images, patch_positions)
301
+ # ic(inputs_embeds.shape, labels.shape)
302
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
303
+ outputs = self.model(
304
+ input_ids=input_ids,
305
+ modality_indicators=modality_indicators,
306
+ attention_mask=attention_mask,
307
+ past_key_values=past_key_values,
308
+ inputs_embeds=inputs_embeds,
309
+ use_cache=use_cache,
310
+ output_attentions=output_attentions,
311
+ output_hidden_states=output_hidden_states,
312
+ return_dict=return_dict
313
+ )
314
+ # ic(outputs[0].shape)
315
+
316
+ hidden_states = outputs[0]
317
+ logits = self.lm_head(hidden_states)
318
+
319
+ loss = None
320
+ if labels is not None:
321
+ # Shift so that tokens < n predict n
322
+ shift_logits = logits[..., :-1, :].contiguous()
323
+ shift_labels = labels[..., 1:].contiguous()
324
+ # Flatten the tokens
325
+ loss_fct = CrossEntropyLoss()
326
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
327
+ shift_labels = shift_labels.view(-1)
328
+ # Enable model/pipeline parallelism
329
+ shift_labels = shift_labels.to(shift_logits.device)
330
+ loss = loss_fct(shift_logits, shift_labels)
331
+
332
+ # ic(loss.shape)
333
+
334
+ if not return_dict:
335
+ output = (logits,) + outputs[1:]
336
+ return (loss,) + output if loss is not None else output
337
+
338
+ return CausalLMOutputWithPast(
339
+ loss=loss,
340
+ logits=logits,
341
+ past_key_values=outputs.past_key_values,
342
+ hidden_states=outputs.hidden_states,
343
+ attentions=outputs.attentions,
344
+ )
345
+
346
+ def prepare_inputs_for_generation(
347
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
348
+ ):
349
+ if past_key_values:
350
+ input_ids = input_ids[:, -1:]
351
+
352
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
353
+ if inputs_embeds is not None and past_key_values is None:
354
+ model_inputs = {"inputs_embeds": inputs_embeds}
355
+ else:
356
+ model_inputs = {"input_ids": input_ids}
357
+
358
+ model_inputs.update(
359
+ {
360
+ "past_key_values": past_key_values,
361
+ "use_cache": kwargs.get("use_cache"),
362
+ "attention_mask": attention_mask,
363
+ "images": kwargs.get("images", None),
364
+ "patch_positions": kwargs.get("patch_positions", None),
365
+ }
366
+ )
367
+ return model_inputs
368
+
369
+ def chat(self, messages, images, tokenizer):
370
+ streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
371
+
372
+ image_tensor, patch_positions, input_ids = self.processor(images=images, messages=messages)
373
+
374
+ image_tensor = image_tensor.to(self.model.device, dtype=torch.float16)
375
+ patch_positions = patch_positions.to(self.model.device)
376
+ input_ids = input_ids.unsqueeze(0).to(self.model.device)
377
+
378
+ stopping_criteria = KeywordsStoppingCriteria(["</s>"], tokenizer, input_ids)
379
+
380
+ with torch.inference_mode():
381
+ output_ids = self.generate(
382
+ input_ids,
383
+ images=image_tensor,
384
+ patch_positions=patch_positions,
385
+ do_sample=False,
386
+ temperature=1.0,
387
+ max_new_tokens=512,
388
+ streamer=streamer,
389
+ use_cache=True,
390
+ stopping_criteria=[stopping_criteria])
391
+
392
+ outputs = tokenizer.decode(output_ids[0, input_ids.shape[1]:]).strip()
393
+
394
+ return outputs.replace('</s>', '')
395
+
396
+ AutoConfig.register("mplug_docowl", MPLUGDocOwlConfig)
397
+ AutoModelForCausalLM.register(MPLUGDocOwlConfig, MPLUGDocOwl2)
398
+
preprocessor_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": 448,
3
+ "do_center_crop": true,
4
+ "do_normalize": true,
5
+ "do_resize": true,
6
+ "feature_extractor_type": "CLIPFeatureExtractor",
7
+ "image_mean": [
8
+ 0.48145466,
9
+ 0.4578275,
10
+ 0.40821073
11
+ ],
12
+ "image_std": [
13
+ 0.26862954,
14
+ 0.26130258,
15
+ 0.27577711
16
+ ],
17
+ "resample": 3,
18
+ "size": 448
19
+ }
20
+
processor.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from einops import rearrange, repeat
2
+ import torch
3
+ from torchvision import transforms
4
+ from PIL import Image, ImageFile
5
+ import random
6
+ from torchvision.ops.boxes import box_area
7
+
8
+ from torchvision.transforms.transforms import InterpolationMode
9
+ from torchvision.transforms import functional as F
10
+ import numpy as np
11
+ from icecream import ic
12
+ import re
13
+
14
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
15
+ ImageFile.MAX_IMAGE_PIXELS = None
16
+ Image.MAX_IMAGE_PIXELS = None
17
+
18
+ from .constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
19
+
20
+ def box_iou(boxes1, area1, boxes2, eps=1e-5):
21
+ area2 = box_area(boxes2)
22
+
23
+ lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
24
+ rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]
25
+
26
+ wh = (rb - lt).clamp(min=0) # [N,M,2]
27
+ inter = wh[:, :, 0] * wh[:, :, 1] # [N,M]
28
+
29
+ union = area1[:, None] + area2 - inter
30
+
31
+ iou = inter / (union+eps)
32
+ return iou, union
33
+
34
+ def anchor_rank(anchors, anchors_areas, input_image_size, eps=1e-5):
35
+ # anchors x1 y1 x2 y2
36
+
37
+ # image_size: (h, w)
38
+ # xyxy
39
+ input_image_bbox = torch.tensor([0, 0, input_image_size[1], input_image_size[0]]).unsqueeze(0)
40
+
41
+ boxes1 = anchors
42
+ boxes2 = input_image_bbox
43
+ boxes3 = anchors.clone()
44
+ # y2
45
+ boxes3[:,3] = input_image_size[0]/input_image_size[1]*anchors[:,2] # 用于算分辨率无关的iou
46
+
47
+ area1 = anchors_areas
48
+
49
+ iou, _ = box_iou(boxes1, area1, boxes2)
50
+ iou = iou.squeeze(1)
51
+ shape_iou, _ = box_iou(boxes1, area1, boxes3)
52
+ shape_iou = shape_iou.diag()
53
+ # 优先匹配形状接近 再匹配分辨率接近
54
+ index = torch.argmax(shape_iou*100+iou,dim=0)
55
+ return index
56
+
57
+ class AnchorResize(torch.nn.Module):
58
+
59
+ def __init__(self, image_size, anchors, interpolation=InterpolationMode.BILINEAR, antialias=None):
60
+ super().__init__()
61
+ # xyxy
62
+ self.anchors = torch.tensor(
63
+ [[0, 0, _[1]*image_size[1], _[0]*image_size[0]]
64
+ for _ in anchors], requires_grad=False
65
+ )
66
+
67
+ self.anchor_areas = box_area(self.anchors)
68
+
69
+ self.interpolation = interpolation
70
+ self.antialias = antialias
71
+
72
+ def forward(self, img, skip_resize=False):
73
+ """
74
+ Args:
75
+ img (PIL Image or Tensor): Image to be scaled.
76
+
77
+ Returns:
78
+ PIL Image or Tensor: Rescaled image.
79
+ """
80
+ selected_anchor = anchor_rank(self.anchors, self.anchor_areas, (img.size[1], img.size[0]))
81
+ target_size = self.anchors[selected_anchor][2:].tolist() # w,h
82
+ if skip_resize:
83
+ # for debug
84
+ return selected_anchor
85
+ return F.resize(img, [target_size[1],target_size[0]], self.interpolation, max_size=None, antialias=self.antialias), selected_anchor
86
+
87
+ def __repr__(self) -> str:
88
+ detail = f"(size={self.image_size}, anchor={self.anchors}, interpolation={self.interpolation.value}, antialias={self.antialias})"
89
+ return f"{self.__class__.__name__}{detail}"
90
+
91
+
92
+ class DocProcessor():
93
+ def __init__(self, tokenizer=None, image_size=504, anchors='grid_12'):
94
+ self.media_token= "<|image|>"
95
+ # h,w
96
+ if isinstance(image_size, int):
97
+ image_size = (image_size, image_size)
98
+ self.image_size = image_size
99
+ # h,w
100
+ # anchors = grid_dict[anchors]
101
+ max_crop = int(anchors.split('_')[1])
102
+ anchors = [(j, int(i/j)) for i in range(1,max_crop+1) for j in range(1, i+1) if i%j==0]
103
+ self.anchors = [tuple(_) for _ in anchors]
104
+ self.anchor_max = max([max(_) for _ in self.anchors])
105
+ # xywh -> xyxy
106
+ self.resizer = AnchorResize(image_size=image_size, anchors=anchors, interpolation=InterpolationMode.BICUBIC)
107
+ self.old_resizer = transforms.Resize(image_size,interpolation=InterpolationMode.BICUBIC)
108
+ self.image_transform = transforms.Compose([
109
+ transforms.ToTensor(),
110
+ transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
111
+ ])
112
+ self.tokenizer = tokenizer
113
+
114
+ def _process_image(self, images):
115
+ new_images = []
116
+ new_patch_position = []
117
+ num_image_mult = []
118
+ for image in images:
119
+ nocut_image = self.image_transform(self.old_resizer(image)).unsqueeze(0)
120
+
121
+ image, selected_anchor = self.resizer(image)
122
+ image_input = self.image_transform(image) # h,w,3 -> 3,h,w
123
+ # rearrange(x,'B C (n1 h) (n2 w) -> (B n1 n2) C h w', n1=self.down_sample[0], n2=self.down_sample[1])
124
+ image_input = rearrange(image_input, 'C (num_h h) (num_w w) -> (num_h num_w) C h w', h=self.image_size[0], w=self.image_size[1])
125
+
126
+ image_input = torch.cat([nocut_image, image_input], dim=0)
127
+
128
+ anchor = self.anchors[selected_anchor] # w,h
129
+ patch_position = torch.cat([
130
+ repeat(torch.arange(anchor[0]), 'num_h -> num_h num_w 1', num_w=anchor[1]),
131
+ repeat(torch.arange(anchor[1]), 'num_w -> num_h num_w 1', num_h=anchor[0])],dim=2)
132
+ patch_position = rearrange(patch_position, 'num_h num_w p-> (num_h num_w) p', p=2) # num_patch, (ph,pw)
133
+
134
+ patch_position = torch.cat([torch.ones(1,2).long()*self.anchor_max, patch_position], dim=0)
135
+
136
+ new_images.append(image_input)
137
+ new_patch_position.append(patch_position)
138
+ num_image_mult.append(patch_position.shape[0])
139
+
140
+ new_images = torch.cat(new_images,dim=0)
141
+ new_patch_position = torch.cat(new_patch_position, dim=0)
142
+ return new_images, new_patch_position, num_image_mult
143
+
144
+ def __call__(self, images=None, messages=None):
145
+ assert images is not None
146
+ # print(images)
147
+
148
+ ## 1. process images
149
+ if not isinstance(images, list):
150
+ images = [images]
151
+ image_pils = []
152
+ for image in images:
153
+ if isinstance(image, str):
154
+ image = Image.open(image).convert('RGB')
155
+ else:
156
+
157
+ image = image.convert('RGB')
158
+ # ic(image.size)
159
+ image_pils.append(image)
160
+
161
+ image_data, patch_position, num_image_mult = self._process_image(image_pils)
162
+
163
+ ## 2. process text
164
+ # 2.1 add image ordinal token (e.g. <img 1>) before image placeholder <|image|>
165
+ image_index = 1 # start from 1
166
+ for m in messages:
167
+ try:
168
+ assert m['role'] in ['USER', 'ASSISTANT']
169
+ except Exception as e:
170
+ print("Unexpected role: "+m['role']+", only support 'USER' or 'ASSISTANT'")
171
+ exit(0)
172
+
173
+ if m['role'] == 'USER' and self.media_token in m.get('content', ''):
174
+ pattern = '|'.join(map(re.escape, [self.media_token]))
175
+ text_list = re.split(f'({pattern})', m['content'])
176
+ text = ''
177
+ for x in text_list:
178
+ if x == '<|image|>':
179
+ text += '<img '+str(image_index)+'><|image|>'
180
+ image_index += 1
181
+ else:
182
+ text += x
183
+ m['content'] = text
184
+
185
+ if messages[-1]['role'] == 'USER':
186
+ messages.append({'role':'ASSISTANT'})
187
+ else:
188
+ try:
189
+ assert messages[-1].get('content', '') == ''
190
+ except Exception as e:
191
+ print("Unexpected end message: "+str(messages[-1]), "only (role=='USER') or (role=='ASSISTANT' and content=='') are expected.")
192
+ exit(0)
193
+
194
+ # print('after adding img ordinal token: ', messages)
195
+ # 2.2 text tokenize
196
+ seps = [' ', '</s>']
197
+ prompt = ""
198
+ for i, m in enumerate(messages):
199
+ if 'content' in m:
200
+ prompt += m['role'] + ": " + m['content'] + seps[i % 2]
201
+ else:
202
+ prompt += m['role'] + ":"
203
+ ic(prompt)
204
+ assert self.media_token in prompt
205
+ input_ids = self.tokenizer_token(prompt)
206
+
207
+ return image_data, patch_position, input_ids
208
+
209
+
210
+ def tokenizer_token(self, prompt):
211
+ prompt_chunks = [self.tokenizer(chunk).input_ids if len(chunk) > 0 else [] for chunk in prompt.split(DEFAULT_IMAGE_TOKEN)]
212
+
213
+ def insert_separator(X, sep):
214
+ return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1]
215
+
216
+ input_ids = []
217
+ offset = 0
218
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == self.tokenizer.bos_token_id:
219
+ offset = 1
220
+ input_ids.append(prompt_chunks[0][0])
221
+
222
+ for x in insert_separator(prompt_chunks, [IMAGE_TOKEN_INDEX] * (offset + 1)):
223
+ input_ids.extend(x[offset:])
224
+
225
+ return torch.tensor(input_ids, dtype=torch.long)
226
+
special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "<unk>",
17
+ "unk_token": {
18
+ "content": "<unk>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<s>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "</s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "legacy": false,
22
+ "model_max_length": 4096,
23
+ "pad_token": null,
24
+ "padding_side": "right",
25
+ "sp_model_kwargs": {},
26
+ "tokenizer_class": "LlamaTokenizer",
27
+ "unk_token": {
28
+ "__type": "AddedToken",
29
+ "content": "<unk>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false
34
+ }
35
+ }
visual_compressor.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Any, Optional, Tuple, Union
3
+
4
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, BaseModelOutputWithPastAndCrossAttentions
5
+ from transformers.modeling_utils import PreTrainedModel
6
+ from transformers.pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
7
+
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.utils.checkpoint
12
+ from icecream import ic
13
+
14
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func as flash_attn_unpadded_func
15
+ from einops import rearrange
16
+
17
+
18
+ class MplugDocOwlVisualMLP(nn.Module):
19
+ def __init__(self, config):
20
+ super().__init__()
21
+ self.config = config
22
+ in_features = config.high_reso_cross_hid_size
23
+ self.act = nn.SiLU()
24
+
25
+ ffn_hidden_size = int(2 * 4 * in_features / 3)
26
+ multiple_of = 256
27
+ ffn_hidden_size = multiple_of * ((ffn_hidden_size + multiple_of - 1) // multiple_of)
28
+
29
+ self.w1 = nn.Linear(in_features, ffn_hidden_size)
30
+ self.w2 = nn.Linear(ffn_hidden_size, in_features)
31
+ self.w3 = nn.Linear(in_features, ffn_hidden_size)
32
+ self.ffn_ln = nn.LayerNorm(ffn_hidden_size, eps=config.layer_norm_eps)
33
+
34
+ torch.nn.init.zeros_(self.w1.bias.data)
35
+ torch.nn.init.zeros_(self.w2.bias.data)
36
+ torch.nn.init.zeros_(self.w3.bias.data)
37
+
38
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
39
+ hidden_states = self.act(self.w1(hidden_states)) * self.w3(hidden_states)
40
+ hidden_states = self.ffn_ln(hidden_states)
41
+ hidden_states = self.w2(hidden_states)
42
+ return hidden_states
43
+
44
+
45
+ class FlashCrossAttention(torch.nn.Module):
46
+ """Implement the scaled dot product attention with softmax.
47
+ Arguments
48
+ ---------
49
+ softmax_scale: The temperature to use for the softmax attention.
50
+ (default: 1/sqrt(d_keys) where d_keys is computed at
51
+ runtime)
52
+ attention_dropout: The dropout rate to apply to the attention
53
+ (default: 0.0)
54
+ """
55
+ def __init__(self, causal=False, softmax_scale=None, attention_dropout=0.0,
56
+ device=None, dtype=None):
57
+ super().__init__()
58
+
59
+ self.softmax_scale = softmax_scale
60
+ self.dropout_p = attention_dropout
61
+
62
+ def forward(self, q, k, v, **kwargs):
63
+ """Implements the multihead softmax attention.
64
+ Arguments
65
+ ---------
66
+ q, k, v: The tensor containing the query, key, and value. (B, S, H, D)
67
+
68
+ or
69
+
70
+ q: (Sum_q, H, D), k,v : (Sum_k, H, D),
71
+ must with batch_size, max_seqlen_q, max_seqlen_k, cu_seqlens_q, cu_seqlens_k in kwargs
72
+ """
73
+
74
+ assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q,k,v)))
75
+ assert all((i.is_cuda for i in (q,k,v)))
76
+
77
+
78
+ if q.dim() == 4:
79
+ batch_size, seqlen_q = q.shape[0], q.shape[1]
80
+ q = rearrange(q, 'b s ... -> (b s) ...')
81
+ cu_seqlens_q = torch.arange(0, (batch_size + 1) * seqlen_q, step=seqlen_q, dtype=torch.int32,
82
+ device=q.device)
83
+ else:
84
+ batch_size, seqlen_q = kwargs['batch_size'], kwargs['max_seqlen_q']
85
+ cu_seqlens_q = kwargs['cu_seqlens_q']
86
+
87
+ if k.dim() == 4:
88
+ seqlen_k = k.shape[1]
89
+ k, v = [rearrange(x, 'b s ... -> (b s) ...') for x in [k, v]]
90
+ cu_seqlens_k = torch.arange(0, (batch_size + 1) * seqlen_k, step=seqlen_k, dtype=torch.int32,
91
+ device=q.device)
92
+ else:
93
+ seqlen_k = kwargs['max_seqlen_k']
94
+ cu_seqlens_k = kwargs['cu_seqlens_k']
95
+
96
+ # q, k, v = [rearrange(x, 'b s ... -> (b s) ...') for x in [q, k, v]]
97
+ # self.dropout_p = 0
98
+
99
+ """print('FlashCrossAttention: q.shape:', q.shape)
100
+ print('FlashCrossAttention: k.shape:', k.shape)
101
+ print('FlashCrossAttention: v.shape:', v.shape)
102
+ print('FlashCrossAttention: cu_seqlens_q:', cu_seqlens_q)
103
+ print('FlashCrossAttention: cu_seqlens_k:', cu_seqlens_k)"""
104
+
105
+ # print('visual_compressor.py q.shape:', q.shape, ' k.shape:', k.shape, ' v.shape:', v.shape)
106
+ output = flash_attn_unpadded_func(
107
+ q, k, v, cu_seqlens_q, cu_seqlens_k, seqlen_q, seqlen_k,
108
+ self.dropout_p if self.training else 0.0,
109
+ softmax_scale=self.softmax_scale, causal=False
110
+ )
111
+
112
+ if q.dim() == 4: # keep the shape of output shape same as the input query
113
+ output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
114
+ return output
115
+
116
+
117
+ class MplugDocOwlVisualMultiHeadAttention(nn.Module):
118
+ def __init__(self, config):
119
+ super().__init__()
120
+ self.config = config
121
+ if config.high_reso_cross_hid_size % config.high_reso_cross_num_att_heads != 0:
122
+ raise ValueError(
123
+ "The hidden size (%d) is not a multiple of the number of attention heads (%d)"
124
+ % (config.high_reso_cross_hid_size, config.high_reso_cross_num_att_heads)
125
+ )
126
+ if config.high_reso_cross_hid_size // config.high_reso_cross_num_att_heads > 256:
127
+ raise ValueError(
128
+ "The hidden size of each head (%d) > 256 and is illegal for flash attention"
129
+ % (config.high_reso_cross_hid_size // config.high_reso_cross_num_att_heads)
130
+ )
131
+
132
+
133
+ self.num_attention_heads = config.high_reso_cross_num_att_heads
134
+ self.attention_head_size = int(config.high_reso_cross_hid_size / config.high_reso_cross_num_att_heads)
135
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
136
+
137
+ self.query = nn.Linear(config.high_reso_cross_hid_size, self.all_head_size)
138
+ self.key = nn.Linear(config.high_reso_cross_hid_size, self.all_head_size)
139
+ self.value = nn.Linear(config.high_reso_cross_hid_size, self.all_head_size)
140
+ self.core_attention_flash = FlashCrossAttention(attention_dropout=config.high_reso_cross_dropout)
141
+
142
+ # bias init
143
+ torch.nn.init.zeros_(self.query.bias.data)
144
+ torch.nn.init.zeros_(self.key.bias.data)
145
+ torch.nn.init.zeros_(self.value.bias.data)
146
+
147
+ def transpose_for_scores(self, x):
148
+ # [B, S, D] -> [B, S, H, D] or [Sum_S, D] -> [Sum_S, H, D]
149
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
150
+ x = x.view(*new_x_shape)
151
+ return x
152
+
153
+ def forward(
154
+ self,
155
+ hidden_states,
156
+ encoder_hidden_states=None,
157
+ **kwargs
158
+ ):
159
+ # assert not torch.isnan(hidden_states).any()
160
+ # assert not torch.isnan(encoder_hidden_states).any()
161
+
162
+ key = self.transpose_for_scores(self.key(encoder_hidden_states))
163
+ value = self.transpose_for_scores(self.value(encoder_hidden_states))
164
+ query = self.transpose_for_scores(self.query(hidden_states))
165
+ # print('visual_compressor.py key(after projection): ', key.shape, key)
166
+ # print('visual_compressor.py value(after projection): ', value.shape, value)
167
+ # print('visual_compressor.py query(after projection): ', query.shape, query)
168
+ # assert not torch.isnan(key).any()
169
+ # assert not torch.isnan(value).any()
170
+ # assert not torch.isnan(query).any()
171
+ outputs = self.core_attention_flash(q=query, k=key, v=value, **kwargs)
172
+ outputs = rearrange(outputs, 's h d -> s (h d)').contiguous()
173
+ # print('visual_compressor.py outputs(after cross_att): ', outputs.shape, outputs)
174
+ return outputs
175
+
176
+
177
+ class MplugDocOwlVisualCrossOutput(nn.Module):
178
+ def __init__(self, config):
179
+ super().__init__()
180
+ dim = config.high_reso_cross_hid_size
181
+ self.out_proj = nn.Linear(dim, dim, bias=True)
182
+ self.norm2 = nn.LayerNorm(dim)
183
+ self.mlp = MplugDocOwlVisualMLP(config)
184
+
185
+ # bias init
186
+ torch.nn.init.zeros_(self.out_proj.bias.data)
187
+
188
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
189
+ input_tensor = input_tensor + self.out_proj(hidden_states)
190
+ input_tensor = input_tensor + self.mlp(self.norm2(input_tensor))
191
+ return input_tensor
192
+
193
+
194
+ class MplugDocOwlVisualCrossAttentionLayer(nn.Module):
195
+ def __init__(self, config):
196
+ super().__init__()
197
+ self.attention = MplugDocOwlVisualMultiHeadAttention(config)
198
+ self.output = MplugDocOwlVisualCrossOutput(config)
199
+ self.norm1 = nn.LayerNorm(config.high_reso_cross_hid_size)
200
+ self.normk = nn.LayerNorm(config.high_reso_cross_hid_size)
201
+
202
+ def forward(
203
+ self,
204
+ hidden_states: torch.Tensor,
205
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
206
+ **kwargs
207
+ ) -> Tuple[torch.Tensor]:
208
+ # print('visual_compressor.py hidden_states: ', hidden_states.shape, hidden_states)
209
+ # print('visual_compressor.py encoder_hidden_states: ', encoder_hidden_states.shape, encoder_hidden_states)
210
+ # assert not torch.isnan(hidden_states).any()
211
+ # assert not torch.isnan(encoder_hidden_states).any()
212
+ hidden_states = self.norm1(hidden_states)
213
+ encoder_hidden_states = self.normk(encoder_hidden_states)
214
+ # print('visual_compressor.py hidden_states(after norm): ', hidden_states.shape, hidden_states)
215
+ # print('visual_compressor.py encoder_hidden_states(after norm): ', encoder_hidden_states.shape, encoder_hidden_states)
216
+ attention_output = self.attention(
217
+ hidden_states,
218
+ encoder_hidden_states,
219
+ **kwargs
220
+ )
221
+
222
+ outputs = self.output(attention_output, hidden_states)
223
+
224
+ return outputs
225
+
226
+
227
+ class MplugDocOwlVisualCrossAttentionEncoder(nn.Module):
228
+ def __init__(self, config):
229
+ super().__init__()
230
+ self.config = config
231
+ self.layer_num = config.layer
232
+ self.layers = nn.ModuleList(
233
+ [MplugDocOwlVisualCrossAttentionLayer(config) for layer_idx in range(self.layer_num)]
234
+ )
235
+ self.gradient_checkpointing = True
236
+
237
+ def forward(
238
+ self,
239
+ hidden_states: torch.Tensor,
240
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
241
+ **kwargs
242
+ ):
243
+ for i in range(self.layer_num):
244
+ layer_module = self.layers[i]
245
+ layer_outputs = layer_module(
246
+ hidden_states,
247
+ encoder_hidden_states,
248
+ **kwargs
249
+ )
250
+ hidden_states = layer_outputs
251
+
252
+ return hidden_states
253
+
254
+
255
+ def ensemble_crop_feats(crop_feats, patch_positions, col_feat_num):
256
+ """
257
+ ensemble vision feats from different crops to a feature map according the position of the raw image
258
+ crop_feats: [N_crop, Len_feat, D]
259
+ patch_positions: [N_crop, 2], 2 == (rowl_index, col_index)
260
+ col_feat_num: the feature num of a row in a crop image
261
+ """
262
+ assert crop_feats.size(0) == patch_positions.size(0)
263
+ row_feats = []
264
+ crop_row = torch.max(patch_positions[:,0])+1 #
265
+ crop_feats = rearrange(crop_feats, '(R C) L D -> R C L D', R=crop_row) # [N_crop_row, N_crop_col, Len_feat, D]
266
+ crop_feats = rearrange(crop_feats, 'R C (X Y) D-> R C X Y D', Y=col_feat_num) # [N_crop_row, N_crop_col, Len_row_feat, Len_col_feat, D]
267
+ # 1. concatenate same row feats across crops; 2. ensemble row feats to get 1 feature map
268
+ hw_feats = rearrange(crop_feats, 'R C X Y D-> (R X) (C Y) D') # [N_crop_row x Len_row_feat, N_crop_col x Len_col_feat, D]
269
+
270
+ return hw_feats
271
+
272
+ def group_window_feats(feats, window):
273
+ """
274
+ collect vision feats from a window (win_row, win_col) to 1 group
275
+ feats: [H, W, D]
276
+ window: (win_row, win_col)
277
+
278
+ return: [H/win_row, H/win_col, win_row x win_col, D]
279
+ """
280
+
281
+ group_feats = rearrange(feats, '(X R) (Y C) D -> (X Y) (R C) D', R=window[0], C=window[1]) # [H/win_row x H/win_col, win_row x win_col, D]
282
+ return group_feats
283
+
284
+
285
+ def distinguish_global_crop_features(hidden_states, patch_positions, reorganize_crop_feats=True, col_feat_num=None, group_feats_by_crop_shape=False, keep_row_col=False):
286
+ """
287
+ distinguish global and crop features with the help of patcg_positions
288
+ # hidden_states: [B, s+1, h]
289
+ # (B is the sum of cropped num across samples in a micro_batch, s is the visual tokens, +1 means the vit end token)
290
+ # patch_positions: [B, 2],
291
+ # 2 == (rowl_index, col_index), the first crop is (0,0), global img is (anchor_max, anchor_max)
292
+
293
+ col_feat_num is used when reorganize_crop_feats == True
294
+
295
+ outputs:
296
+ img_global_features: list of [Len_global_feat, D]
297
+ img_crop_features: list of [Len_global_feat, D]
298
+ """
299
+ hidden_states = hidden_states[:, :-1, :] # remove the last vit end token emb
300
+ # the first crop is (0,0)
301
+ first_crop_indices = (patch_positions.sum(dim=-1) == 0).nonzero().squeeze(1) # Num_img
302
+ # the global image is before the first crop
303
+ global_indices = first_crop_indices - 1 # Num_img
304
+ # print('vision2text_model.py patch_positions:', patch_positions)
305
+ # print('vision2text_model.py global_indices:', global_indices)
306
+ # collect cropped vision features of an identical image
307
+ batch_size = hidden_states.size(0)
308
+ img_global_features = []
309
+ img_crop_features = [] # store list of Num_crop (variable) x Len_feat (fixed)
310
+ img_crop_positions = [] # store list of Num_crop (variable) x 2
311
+ for i in range(len(global_indices)):
312
+ index = global_indices[i]
313
+ img_global_features.append(hidden_states[index])
314
+ if i == (len(global_indices)-1):
315
+ img_crop_features.append(hidden_states[index+1:])
316
+ img_crop_positions.append(patch_positions[index+1:])
317
+ else:
318
+ next_index = global_indices[i+1]
319
+ img_crop_features.append(hidden_states[index+1:next_index])
320
+ img_crop_positions.append(patch_positions[index+1:next_index])
321
+
322
+ if reorganize_crop_feats:
323
+ for i in range(len(img_crop_features)):
324
+ img_crop_features[i] = ensemble_crop_feats(img_crop_features[i], img_crop_positions[i], col_feat_num) # [H W D]
325
+ if group_feats_by_crop_shape: # collect vision feats from a window (crop_row, crop_col) to 1 group
326
+ crop_row = torch.max(img_crop_positions[i][:,0])+1 #
327
+ crop_col = torch.max(img_crop_positions[i][:,1])+1 #
328
+ img_crop_features[i] = group_window_feats(img_crop_features[i], window=(crop_row, crop_col)) # [H/crop_row x W/crop_col, crop_row x crop_row, D]
329
+ else:
330
+ # img_crop_features = [rearrange(x, 'H W D -> (H W) D') for x in img_crop_features]
331
+ if not keep_row_col:
332
+ img_crop_featuress[i] = rearrange(img_crop_featuress[i], 'H W D -> (H W) D')
333
+ else:
334
+ img_crop_features = [rearrange(x, 'N L D -> (N L) D') for x in img_crop_features]
335
+
336
+ return img_global_features, img_crop_features
337
+
338
+
339
+ class MplugDocOwlHRDocCompressor(PreTrainedModel):
340
+ """
341
+ After vision-to-text module, use low-resolution global features to select high-resolution crop features with cross-attention
342
+ the key/value from high-resolution crop features are contrained in a window size
343
+ positions of the features within the window in raw images are the same as the global query features
344
+ """
345
+ def __init__(self, config, output_hidden_size, v2t_img_col_tokens):
346
+ super().__init__(config)
347
+ self.use_flash_attn = True
348
+ assert self.use_flash_attn
349
+
350
+ self.v2t_img_col_tokens = v2t_img_col_tokens
351
+
352
+ self.compressor_crossatt = MplugDocOwlVisualCrossAttentionEncoder(config)
353
+
354
+ self.compressor_fc = torch.nn.Linear(output_hidden_size, output_hidden_size)
355
+
356
+ self.compressor_eos = torch.nn.Parameter(torch.randn(1, 1, output_hidden_size))
357
+
358
+
359
+ def forward(self, hidden_states, patch_positions=None):
360
+ # hidden_states: outputs of vision2textmodel: [Sum(crop), s+1, h]
361
+ # (Sum(crop) is the sum of cropped num across samples in a micro_batch, s is the visual tokens, +1 is the special vit_eos token added in H-Reducer)
362
+ # patch_positions: [Sum(crop), 2]
363
+
364
+ # print('visual_compressor.py HRDocCompressor hidden_states.shape:', hidden_states.shape)
365
+ # print('visual_compressor.py HRDocCompressor patch_positions.shape:', patch_positions.shape)
366
+
367
+ # N_img x [L_global (fixed), D], N_img x [L_global (fixed), Crop_row x Crop_Col (Variable), D]
368
+ img_global_features, img_crop_features = distinguish_global_crop_features(hidden_states,
369
+ patch_positions,
370
+ reorganize_crop_feats=True,
371
+ col_feat_num=self.v2t_img_col_tokens,
372
+ group_feats_by_crop_shape=True)
373
+
374
+ # cross-attention to accumulate high-resolution features
375
+ # if self.use_flash_attn: # flash_attn_varlen_func don't need to pad crop_features
376
+ img_global_features = torch.stack(img_global_features, dim=0).to(hidden_states.device) # Num_img x Len_global_feat x D
377
+ batch_size, global_feat_num, seqlen_q = img_global_features.shape[0], img_global_features.shape[1], 1
378
+ img_global_features = rearrange(img_global_features, 'b s ... -> (b s) ...')
379
+ cu_seqlens_q = torch.arange(0, batch_size*global_feat_num+1, step=1, dtype=torch.int32, device=img_global_features.device) # # (Num_img x Len_global_feat +1, )
380
+ cu_seqlens_k = [0]
381
+ max_seqlens_k = 0
382
+ for crop_feat in img_crop_features:
383
+ for i in range(crop_feat.shape[0]):
384
+ cu_seqlens_k.append(cu_seqlens_k[-1]+crop_feat.shape[1]) # same k within a image shares the seq len
385
+ max_seqlens_k = max(max_seqlens_k, crop_feat.size(1))
386
+
387
+ cu_seqlens_k = torch.tensor(cu_seqlens_k, dtype=torch.int32).to(hidden_states.device) # (Num_img x Len_global_feat+1, )
388
+ # cu_seqlens_k = torch.arange(0, (batch_size + 1) * max_seqlens_k, step=max_seqlens_k, dtype=torch.int32, device=img_global_features.device) # # (Num_img+1, )
389
+
390
+ img_crop_features = torch.cat([rearrange(x, 'N L D -> (N L) D') for x in img_crop_features], dim=0).to(hidden_states.device) # Sum(L_hr) x D
391
+ flash_kwargs = {
392
+ 'batch_size': batch_size*global_feat_num, # each feat in global feats use different keys
393
+ 'max_seqlen_q': seqlen_q, # key are unique for each query
394
+ 'max_seqlen_k': max_seqlens_k,
395
+ 'cu_seqlens_q': cu_seqlens_q, # the seq len of each q
396
+ 'cu_seqlens_k': cu_seqlens_k # the seq len of each k
397
+ }
398
+ # print('visual_compressor.py HRDocCompressor img_global_features.shape:', img_global_features.shape, img_global_features)
399
+ # print('visual_compressor.py HRDocCompressor img_crop_features.shape:', img_crop_features.shape, img_crop_features)
400
+ """print('visual_compressor.py HRDocCompressor cu_seqlens_q, cu_seqlens_q.shape:', cu_seqlens_q, cu_seqlens_q.shape)
401
+ print('visual_compressor.py HRDocCompressor cu_seqlens_k, cu_seqlens_k.shape:', cu_seqlens_k, cu_seqlens_k.shape)"""
402
+ # assert not torch.isnan(img_global_features).any()
403
+ # assert not torch.isnan(img_crop_features).any()
404
+ for x_name, x in self.compressor_crossatt.named_parameters():
405
+ try:
406
+ assert not torch.isnan(x).any()
407
+ # print('visual_compressor.py ', x_name, x.shape, x)
408
+ except Exception as e:
409
+ print(e)
410
+ print('visual_compressor.py nan', x_name, x.shape, x)
411
+ hidden_states = self.compressor_crossatt(
412
+ img_global_features.contiguous(), # Sum(L_global) x D
413
+ img_crop_features.contiguous(), # Sum(L_hr) x D
414
+ **flash_kwargs
415
+ ) # Sum(L_global) x D
416
+ hidden_states = rearrange(hidden_states, '(B S) D -> S B D', B=batch_size) # L_global x N_img x D
417
+
418
+ hidden_states = self.compressor_fc(hidden_states) # L_global x N_img x D
419
+
420
+ hidden_states = hidden_states.transpose(0, 1).contiguous() # N_img x L_global x D
421
+ # print('visual_compressor.py hidden_states:', hidden_states.shape)
422
+
423
+ hidden_states = torch.cat([hidden_states, self.compressor_eos.repeat(hidden_states.shape[0], 1, 1)], dim=1) # N_img x (L_global+1) x D
424
+ # print('visual_compressor.py HRDocCompressor hidden_states.shape:', hidden_states.shape)
425
+
426
+ return hidden_states
visual_encoder.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Any, Optional, Tuple, Union
3
+
4
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, BaseModelOutputWithPastAndCrossAttentions
5
+ from transformers.modeling_utils import PreTrainedModel
6
+ from transformers.pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
7
+
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.utils.checkpoint
12
+ from icecream import ic
13
+ import einops
14
+ from einops import rearrange
15
+
16
+ def get_abs_pos(abs_pos, tgt_size):
17
+ # abs_pos: L, C
18
+ # tgt_size: M
19
+ # return: M, C
20
+ src_size = int(math.sqrt(abs_pos.size(0)))
21
+ tgt_size = int(math.sqrt(tgt_size))
22
+ dtype = abs_pos.dtype
23
+
24
+ if src_size != tgt_size:
25
+ return F.interpolate(
26
+ abs_pos.float().reshape(1, src_size, src_size, -1).permute(0, 3, 1, 2),
27
+ size=(tgt_size, tgt_size),
28
+ mode="bicubic",
29
+ align_corners=False,
30
+ ).permute(0, 2, 3, 1).flatten(0, 2).to(dtype=dtype)
31
+ else:
32
+ return abs_pos
33
+
34
+ # https://github.com/facebookresearch/mae/blob/efb2a8062c206524e35e47d04501ed4f544c0ae8/util/pos_embed.py#L20
35
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
36
+ """
37
+ grid_size: int of the grid height and width
38
+ return:
39
+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
40
+ """
41
+ grid_h = np.arange(grid_size, dtype=np.float32)
42
+ grid_w = np.arange(grid_size, dtype=np.float32)
43
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
44
+ grid = np.stack(grid, axis=0)
45
+
46
+ grid = grid.reshape([2, 1, grid_size, grid_size])
47
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
48
+ if cls_token:
49
+ pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
50
+ return pos_embed
51
+
52
+
53
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
54
+ assert embed_dim % 2 == 0
55
+
56
+ # use half of dimensions to encode grid_h
57
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
58
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
59
+
60
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
61
+ return emb
62
+
63
+
64
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
65
+ """
66
+ embed_dim: output dimension for each position
67
+ pos: a list of positions to be encoded: size (M,)
68
+ out: (M, D)
69
+ """
70
+ assert embed_dim % 2 == 0
71
+ omega = np.arange(embed_dim // 2, dtype=np.float32)
72
+ omega /= embed_dim / 2.
73
+ omega = 1. / 10000**omega # (D/2,)
74
+
75
+ pos = pos.reshape(-1) # (M,)
76
+ out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
77
+
78
+ emb_sin = np.sin(out) # (M, D/2)
79
+ emb_cos = np.cos(out) # (M, D/2)
80
+
81
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
82
+ return emb
83
+
84
+
85
+
86
+ class MplugOwlVisionEmbeddings(nn.Module):
87
+ def __init__(self, config):
88
+ super().__init__()
89
+ self.config = config
90
+ self.hidden_size = config.hidden_size
91
+ self.image_size = config.image_size
92
+ self.patch_size = config.patch_size
93
+
94
+ self.cls_token = nn.Parameter(torch.randn(1, 1, self.hidden_size))
95
+
96
+ self.patch_embed = nn.Conv2d(
97
+ in_channels=3,
98
+ out_channels=self.hidden_size,
99
+ kernel_size=self.patch_size,
100
+ stride=self.patch_size,
101
+ bias=False,
102
+ )
103
+
104
+ self.num_patches = (self.image_size // self.patch_size) ** 2
105
+
106
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_patches + 1, self.hidden_size))
107
+
108
+ self.pre_layernorm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
109
+
110
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
111
+ batch_size = pixel_values.size(0)
112
+ image_embeds = self.patch_embed(pixel_values)
113
+ image_embeds = image_embeds.flatten(2).transpose(1, 2)
114
+
115
+ class_embeds = self.cls_token.expand(batch_size, 1, -1).to(image_embeds.dtype)
116
+ embeddings = torch.cat([class_embeds, image_embeds], dim=1)
117
+ embeddings = embeddings + self.position_embedding[:, : embeddings.size(1)].to(image_embeds.dtype)
118
+ embeddings = self.pre_layernorm(embeddings)
119
+ return embeddings
120
+
121
+
122
+
123
+ class MplugOwlVisionAttention(nn.Module):
124
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
125
+
126
+ def __init__(self, config):
127
+ super().__init__()
128
+ self.config = config
129
+ self.hidden_size = config.hidden_size
130
+ self.num_heads = config.num_attention_heads
131
+ self.head_dim = self.hidden_size // self.num_heads
132
+ if self.head_dim * self.num_heads != self.hidden_size:
133
+ raise ValueError(
134
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
135
+ f" {self.num_heads})."
136
+ )
137
+ self.scale = self.head_dim**-0.5
138
+ self.dropout = nn.Dropout(config.attention_dropout)
139
+
140
+ self.query_key_value = nn.Linear(self.hidden_size, 3 * self.hidden_size)
141
+ self.dense = nn.Linear(self.hidden_size, self.hidden_size)
142
+
143
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
144
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
145
+
146
+ def forward(
147
+ self,
148
+ hidden_states: torch.Tensor,
149
+ head_mask: Optional[torch.Tensor] = None,
150
+ output_attentions: Optional[bool] = False,
151
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
152
+ """Input shape: Batch x Time x Channel"""
153
+
154
+ bsz, seq_len, embed_dim = hidden_states.size()
155
+
156
+ mixed_qkv = self.query_key_value(hidden_states)
157
+
158
+ mixed_qkv = mixed_qkv.reshape(bsz, seq_len, self.num_heads, 3, embed_dim // self.num_heads).permute(
159
+ 3, 0, 2, 1, 4
160
+ ) # [3, b, np, sq, hn]
161
+ query_states, key_states, value_states = (
162
+ mixed_qkv[0],
163
+ mixed_qkv[1],
164
+ mixed_qkv[2],
165
+ )
166
+ # if self.config.use_flash_attn and flash_attn_func is not None:
167
+ if False:
168
+ # [b*sq, np, hn]
169
+ query_states = query_states.permute(0, 2, 1, 3).contiguous()
170
+ query_states = query_states.view(query_states.size(0) * query_states.size(1), query_states.size(2), -1)
171
+
172
+ key_states = key_states.permute(0, 2, 1, 3).contiguous()
173
+ key_states = key_states.view(key_states.size(0) * key_states.size(1), key_states.size(2), -1)
174
+
175
+ value_states = value_states.permute(0, 2, 1, 3).contiguous()
176
+ value_states = value_states.view(value_states.size(0) * value_states.size(1), value_states.size(2), -1)
177
+
178
+ cu_seqlens = torch.arange(
179
+ 0, (bsz + 1) * seq_len, step=seq_len, dtype=torch.int32, device=query_states.device
180
+ )
181
+
182
+ context_layer = flash_attn_func(
183
+ query_states,
184
+ key_states,
185
+ value_states,
186
+ cu_seqlens,
187
+ cu_seqlens,
188
+ seq_len,
189
+ seq_len,
190
+ self.dropout if self.training else 0.0,
191
+ softmax_scale=self.scale,
192
+ causal=False,
193
+ return_attn_probs=False,
194
+ )
195
+ # [b*sq, np, hn] => [b, sq, np, hn]
196
+ context_layer = context_layer.view(bsz, seq_len, context_layer.size(1), context_layer.size(2))
197
+ else:
198
+ # Take the dot product between "query" and "key" to get the raw attention scores.
199
+ attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2))
200
+
201
+ attention_scores = attention_scores * self.scale
202
+
203
+ # Normalize the attention scores to probabilities.
204
+ attention_probs = torch.softmax(attention_scores, dim=-1)
205
+
206
+ # This is actually dropping out entire tokens to attend to, which might
207
+ # seem a bit unusual, but is taken from the original Transformer paper.
208
+ attention_probs = self.dropout(attention_probs)
209
+
210
+ # Mask heads if we want to
211
+ if head_mask is not None:
212
+ attention_probs = attention_probs * head_mask
213
+
214
+ context_layer = torch.matmul(attention_probs, value_states).permute(0, 2, 1, 3)
215
+
216
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size,)
217
+ context_layer = context_layer.reshape(new_context_layer_shape)
218
+
219
+ output = self.dense(context_layer)
220
+
221
+ outputs = (output, attention_probs) if output_attentions else (output, None)
222
+
223
+ return outputs
224
+
225
+
226
+ class QuickGELU(nn.Module):
227
+ def forward(self, x: torch.Tensor):
228
+ return x * torch.sigmoid(1.702 * x)
229
+
230
+
231
+ class MplugOwlMLP(nn.Module):
232
+ def __init__(self, config):
233
+ super().__init__()
234
+ self.config = config
235
+ self.activation_fn = QuickGELU()
236
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
237
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
238
+
239
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
240
+ hidden_states = self.fc1(hidden_states)
241
+ hidden_states = self.activation_fn(hidden_states)
242
+ hidden_states = self.fc2(hidden_states)
243
+ return hidden_states
244
+
245
+
246
+ class MplugOwlVisionEncoderLayer(nn.Module):
247
+ def __init__(self, config):
248
+ super().__init__()
249
+ self.hidden_size = config.hidden_size
250
+ self.self_attn = MplugOwlVisionAttention(config)
251
+ self.input_layernorm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
252
+ self.mlp = MplugOwlMLP(config)
253
+ self.post_attention_layernorm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
254
+
255
+ def forward(
256
+ self,
257
+ hidden_states: torch.Tensor,
258
+ attention_mask: torch.Tensor,
259
+ output_attentions: Optional[bool] = False,
260
+ ) -> Tuple[torch.FloatTensor]:
261
+ """
262
+ Args:
263
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
264
+ attention_mask (`torch.FloatTensor`): attention mask of size
265
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
266
+ `(config.encoder_attention_heads,)`.
267
+ output_attentions (`bool`, *optional*):
268
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
269
+ returned tensors for more detail.
270
+ """
271
+ residual = hidden_states
272
+
273
+ hidden_states = self.input_layernorm(hidden_states)
274
+ hidden_states, attn_weights = self.self_attn(
275
+ hidden_states=hidden_states,
276
+ head_mask=attention_mask,
277
+ output_attentions=output_attentions,
278
+ )
279
+ hidden_states = hidden_states + residual
280
+ residual = hidden_states
281
+ hidden_states = self.post_attention_layernorm(hidden_states)
282
+ hidden_states = self.mlp(hidden_states)
283
+
284
+ hidden_states = hidden_states + residual
285
+
286
+ outputs = (hidden_states,)
287
+
288
+ if output_attentions:
289
+ outputs += (attn_weights,)
290
+
291
+ return outputs
292
+
293
+
294
+ class MplugOwlVisionEncoder(nn.Module):
295
+ """
296
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
297
+ [`MplugOwlVisionEncoderLayer`].
298
+
299
+ Args:
300
+ config (`MplugOwlVisionConfig`):
301
+ The corresponding vision configuration for the `MplugOwlEncoder`.
302
+ """
303
+
304
+ def __init__(self, config):
305
+ super().__init__()
306
+ self.config = config
307
+ self.layers = nn.ModuleList([MplugOwlVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)])
308
+ self.gradient_checkpointing = True
309
+
310
+ def forward(
311
+ self,
312
+ inputs_embeds,
313
+ attention_mask: Optional[torch.Tensor] = None,
314
+ output_attentions: Optional[bool] = None,
315
+ output_hidden_states: Optional[bool] = None,
316
+ return_dict: Optional[bool] = None,
317
+ ) -> Union[Tuple, BaseModelOutput]:
318
+ r"""
319
+ Args:
320
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
321
+ Embedded representation of the inputs. Should be float, not int tokens.
322
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
323
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
324
+
325
+ - 1 for tokens that are **not masked**,
326
+ - 0 for tokens that are **masked**.
327
+
328
+ [What are attention masks?](../glossary#attention-mask)
329
+ output_attentions (`bool`, *optional*):
330
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
331
+ returned tensors for more detail.
332
+ output_hidden_states (`bool`, *optional*):
333
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
334
+ for more detail.
335
+ return_dict (`bool`, *optional*):
336
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
337
+ """
338
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
339
+ output_hidden_states = (
340
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
341
+ )
342
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
343
+
344
+ encoder_states = () if output_hidden_states else None
345
+ all_attentions = () if output_attentions else None
346
+
347
+ hidden_states = inputs_embeds
348
+ for idx, encoder_layer in enumerate(self.layers):
349
+ if output_hidden_states:
350
+ encoder_states = encoder_states + (hidden_states,)
351
+ if self.gradient_checkpointing and self.training:
352
+
353
+ def create_custom_forward(module):
354
+ def custom_forward(*inputs):
355
+ return module(*inputs, output_attentions)
356
+
357
+ return custom_forward
358
+
359
+ layer_outputs = torch.utils.checkpoint.checkpoint(
360
+ create_custom_forward(encoder_layer),
361
+ hidden_states,
362
+ attention_mask,
363
+ )
364
+ else:
365
+ layer_outputs = encoder_layer(
366
+ hidden_states,
367
+ attention_mask,
368
+ output_attentions=output_attentions,
369
+ )
370
+
371
+ hidden_states = layer_outputs[0]
372
+
373
+ if output_attentions:
374
+ all_attentions = all_attentions + (layer_outputs[1],)
375
+
376
+ if output_hidden_states:
377
+ encoder_states = encoder_states + (hidden_states,)
378
+
379
+ if not return_dict:
380
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
381
+ return BaseModelOutput(
382
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
383
+ )
384
+
385
+
386
+ class MplugOwlVisionModel(PreTrainedModel):
387
+ main_input_name = "pixel_values"
388
+
389
+ def __init__(self, config):
390
+ super().__init__(config)
391
+ self.config = config
392
+ self.hidden_size = config.hidden_size
393
+
394
+ self.embeddings = MplugOwlVisionEmbeddings(config)
395
+ self.encoder = MplugOwlVisionEncoder(config)
396
+ self.post_layernorm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
397
+
398
+ self.post_init()
399
+
400
+
401
+ def forward(
402
+ self,
403
+ pixel_values: Optional[torch.FloatTensor] = None,
404
+ output_attentions: Optional[bool] = None,
405
+ output_hidden_states: Optional[bool] = None,
406
+ return_dict: Optional[bool] = None,
407
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
408
+ r"""
409
+ Returns:
410
+
411
+ """
412
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
413
+ output_hidden_states = (
414
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
415
+ )
416
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
417
+
418
+ if pixel_values is None:
419
+ raise ValueError("You have to specify pixel_values")
420
+
421
+ hidden_states = self.embeddings(pixel_values)
422
+
423
+ encoder_outputs = self.encoder(
424
+ inputs_embeds=hidden_states,
425
+ output_attentions=output_attentions,
426
+ output_hidden_states=output_hidden_states,
427
+ return_dict=return_dict,
428
+ )
429
+
430
+ last_hidden_state = encoder_outputs[0]
431
+ last_hidden_state = self.post_layernorm(last_hidden_state)
432
+
433
+ pooled_output = last_hidden_state[:, 0, :]
434
+ pooled_output = self.post_layernorm(pooled_output)
435
+
436
+ if not return_dict:
437
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
438
+
439
+ return BaseModelOutputWithPooling(
440
+ last_hidden_state=last_hidden_state,
441
+ pooler_output=pooled_output,
442
+ hidden_states=encoder_outputs.hidden_states,
443
+ attentions=encoder_outputs.attentions,
444
+ )
445
+
446
+ def get_input_embeddings(self):
447
+ return self.embeddings
448
+
449
+
450
+ class MplugDocOwlHReducerModel(PreTrainedModel):
451
+ def __init__(self, config, language_hidden_size):
452
+ super().__init__(config)
453
+ self.config = config
454
+ self.ln_q = torch.nn.LayerNorm(self.config.hidden_size, eps=1e-6)
455
+ self.conv_shape = (int(self.config.conv_shape.split('x')[0]), int(self.config.conv_shape.split('x')[1])) #
456
+ self.conv_patch=self.conv_shape[0]*self.conv_shape[1]
457
+ ## feature interaction with a conv layer
458
+ self.reducer_before = torch.nn.Sequential(
459
+ nn.Conv2d(self.config.hidden_size, self.conv_patch*self.config.hidden_size, kernel_size=self.conv_shape, stride=self.conv_shape, bias=True),
460
+ nn.GELU()
461
+ )
462
+ ## reduce visual feature length with a conv layer
463
+ self.reducer = nn.Conv2d(self.config.hidden_size, self.config.hidden_size, kernel_size=self.conv_shape, stride=self.conv_shape, bias=True)
464
+ ## align visual features with language embedding with fc
465
+ self.visual_fc = torch.nn.Linear(self.config.hidden_size, language_hidden_size)
466
+ self.vit_eos = torch.nn.Parameter(torch.randn(1, 1, language_hidden_size))
467
+
468
+ self.post_init()
469
+
470
+ def forward(
471
+ self,
472
+ encoder_hidden_states=None
473
+ ):
474
+ r"""
475
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, `optional`):
476
+ batch_size is the number of all images (global+crop) in a batch
477
+ Sequence of hidden-states at the output of the last layer of the encoder.
478
+ """
479
+ encoder_hidden_states = encoder_hidden_states[:,1:,:] # remove the first cls token
480
+ B, L, C = encoder_hidden_states.shape # B, 1024=(448/14)^2, 1024
481
+
482
+ ## feature interaction with a conv layer
483
+ encoder_hidden_states = rearrange(encoder_hidden_states, 'B (H W) D -> B D H W', H=int(math.sqrt(L)))
484
+ hidden_states = self.reducer_before(encoder_hidden_states) # B 4D H W/4
485
+ ## reduce seq length with a conv layer
486
+ """hidden_states = hidden_states.flatten(2).transpose(1, 2) # B 4D H W/4 -> B 4D H*W/4 -> B H*W/4 4D
487
+ hidden_states = rearrange(hidden_states, 'B L (X D) -> B (L X) D', X=self.conv_patch) # B (H W) D
488
+ hidden_states = rearrange(hidden_states, 'B (H W) D -> B D H W', H=int(math.sqrt(L))) # B D H W """
489
+ hidden_states = rearrange(hidden_states, 'B (X D) H W -> B D H (W X)', X=self.conv_patch) # B 4D H W/4 -> B D H W
490
+ sequence_output = self.reducer(hidden_states) # B,C,H,W -> B,C,H/conv_shape[1],W/(conv_shape[1])
491
+ sequence_output = sequence_output.flatten(2).transpose(1, 2) # B,C,H/conv_shape[1],W/(conv_shape[1]) -> B,C,L/conv_patch -> B,L/conv_patch,C
492
+ sequence_output = sequence_output.transpose(0, 1).contiguous() # L/conv_patch, B, C
493
+ ## align visual features with language embedding with fc
494
+ sequence_output = self.visual_fc(sequence_output) # L/conv_patch, B, h
495
+ sequence_output = sequence_output.transpose(0, 1).contiguous() # B, s/4, h
496
+ sequence_output = torch.cat([sequence_output, self.vit_eos.repeat(B, 1, 1)], dim=1)
497
+
498
+ return sequence_output
499
+
500
+
501
+