Text Generation
Transformers
Safetensors
imp_qwen2
conversational
custom_code
Oyoy1235 commited on
Commit
cb298cd
1 Parent(s): 382bd97

update model

Browse files
README.md CHANGED
@@ -1,3 +1,93 @@
1
  ---
2
  license: apache-2.0
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+ pipeline_tag: text-generation
4
+ datasets:
5
+ - liuhaotian/LLaVA-Pretrain
6
+ - liuhaotian/LLaVA-Instruct-150K
7
  ---
8
+ # 😈 Imp
9
+
10
+ > A very small man can cast a very large shadow.
11
+ >
12
+ >           ——*George R.R. Martin, A Clash of Kings*
13
+
14
+
15
+ \[Technical report (coming soon)\]  [[Demo](https://xmbot.net/imp/)\]  [[Github](https://github.com/MILVLG/imp)\]
16
+
17
+ ## Introduction
18
+
19
+ The Imp project aims to provide a family of a strong multimodal `small` language models (MSLMs). Our `Imp-v1.5-2B-Qwen1.5` is a strong MSLM with only **2B** parameters, which is build upon a small yet powerful SLM [Qwen1.5-1.8B-Chat ](https://huggingface.co/Qwen/Qwen1.5-1.8B-Chat)(1.8B) and a powerful visual encoder [SigLIP ](https://huggingface.co/google/siglip-so400m-patch14-384)(0.4B), and trained on the [LLaVA-v1.5](https://github.com/haotian-liu/LLaVA) training set.
20
+
21
+ As shown in the Table below, `Imp-v1.5-2B-Qwen1.5` significantly outperforms the counterparts of similar model sizes, and even achieves slightly better performance than the strong LLaVA-7B model on various multimodal benchmarks.
22
+
23
+ We release our model weights and provide an example below to run our model . Detailed technical report and corresponding training/evaluation code will be released soon on our [GitHub repo](https://github.com/MILVLG/imp). We will persistently improve our model and release the next versions to further improve model performance :)
24
+
25
+
26
+ ## How to use
27
+
28
+
29
+ **Install dependencies**
30
+ ```bash
31
+ pip install transformers # latest version is ok, but we recommend v4.31.0
32
+ pip install -q pillow accelerate einops
33
+ ```
34
+
35
+ You can use the following code for model inference. The format of text instruction is similar to [LLaVA](https://github.com/haotian-liu/LLaVA). A Colab page to run this example is provided [here](https://colab.research.google.com/drive/1EBYky6xIPjnlPppo2gZaiNK6gEsjXgom?usp=drive_link#scrollTo=2-VpU6QzWCVZ). Note that the example can only be run on GPUs currently.
36
+
37
+ ```Python
38
+ import torch
39
+ from transformers import AutoModelForCausalLM, AutoTokenizer
40
+ from PIL import Image
41
+
42
+ torch.set_default_device("cuda")
43
+
44
+ #Create model
45
+ model = AutoModelForCausalLM.from_pretrained(
46
+ "MILVLG/Imp-v1.5-2B-Qwen1.5",
47
+ torch_dtype=torch.float16,
48
+ device_map="auto",
49
+ trust_remote_code=True)
50
+ tokenizer = AutoTokenizer.from_pretrained("MILVLG/Imp-v1.5-2B-Qwen1.5", trust_remote_code=True)
51
+
52
+ #Set inputs
53
+ text = "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. USER: <image>\nWhat are the colors of the bus in the image? ASSISTANT:"
54
+ image = Image.open("images/bus.jpg")
55
+
56
+ input_ids = tokenizer(text, return_tensors='pt').input_ids
57
+ image_tensor = model.image_preprocess(image)
58
+
59
+ #Generate the answer
60
+ output_ids = model.generate(
61
+ input_ids,
62
+ max_new_tokens=100,
63
+ images=image_tensor,
64
+ use_cache=True)[0]
65
+ print(tokenizer.decode(output_ids[input_ids.shape[1]:], skip_special_tokens=True).strip())
66
+ ```
67
+
68
+ ## Model evaluation
69
+ We conduct evaluation on 9 commonly-used benchmarks, including 5 academic VQA benchmarks and 4 popular MLLM benchmarks, to compare our Imp model with LLaVA (7B) and existing MSLMs of similar model sizes.
70
+
71
+ | Models | Size | VQAv2 | GQA | SQA(IMG) | TextVQA | POPE | MME(P) | MMB |MMBCN |MM-Vet|
72
+ |:--------:|:-----:|:----:|:-------------:|:--------:|:-----:|:----:|:-------:|:-------:|:-------:|:-------:|
73
+ | [LLaVA-v1.5-lora](https://huggingface.co/liuhaotian/llava-v1.5-7b) | 7B |79.10 | 63.00| 68.40 |58.20| 86.40 | 1476.9 | 66.10 |- |30.2|
74
+ | **Imp-v1.5-2B-Qwen1.5** | 3B | **81.18** | **63.54** | **72.78**| **59.84** | **88.87**| **1446.4** | **72.94**| 46.65 |**43.3**|
75
+
76
+ ## License
77
+ This project is licensed under the Apache License 2.0 - see the [LICENSE](https://www.apache.org/licenses/LICENSE-2.0) file for details.
78
+
79
+ ## About us
80
+ This project is maintained by the [MILVLG](https://github.com/MILVLG)@Hangzhou Dianzi University (HDU) led by Prof. Zhou Yu and Jun Yu, and is mainly developed by Zhenwei Shao and Xuecheng Ouyang. We hope our model may serve as a strong baseline to inspire future research on MSLM, as well as its derivative applications on mobile devices and robots.
81
+
82
+ ## Citation
83
+
84
+ If you use our model or refer our work in your studies, please cite:
85
+
86
+ ```bibtex
87
+ @misc{imp2024,
88
+ author = {Shao, Zhenwei and Ouyang, Xuecheng and Yu, Zhou and Yu, Jun},
89
+ title = {Imp: An Emprical Study of Multimodal Small Language Models},
90
+ year = {2024},
91
+ url = {https://huggingface.co/MILVLG/imp-v1-3b}
92
+ }
93
+ ```
added_tokens.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "<|endoftext|>": 151643,
3
+ "<|im_end|>": 151645,
4
+ "<|im_start|>": 151644
5
+ }
config.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "MILVLG/imp-qwen-v1-2b",
3
+ "architectures": [
4
+ "ImpQwen2ForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_imp_qwen.ImpQwen2Config",
9
+ "AutoModelForCausalLM": "modeling_imp_qwen.ImpQwen2ForCausalLM"
10
+ },
11
+ "bos_token_id": 151643,
12
+ "eos_token_id": 151645,
13
+ "freeze_mm_mlp_adapter": false,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 2048,
16
+ "image_aspect_ratio": "square",
17
+ "image_token": "<image>",
18
+ "image_token_index": 151646,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 5504,
21
+ "max_position_embeddings": 32768,
22
+ "max_window_layers": 21,
23
+ "mm_hidden_size": 1152,
24
+ "mm_projector_lr": 2e-05,
25
+ "mm_projector_type": "mlp2x_gelu",
26
+ "mm_use_im_patch_token": false,
27
+ "mm_use_im_start_end": false,
28
+ "mm_vision_select_feature": "patch",
29
+ "mm_vision_select_layer": -2,
30
+ "mm_vision_tower": "google/siglip-so400m-patch14-384",
31
+ "model_type": "imp_qwen2",
32
+ "num_attention_heads": 16,
33
+ "num_hidden_layers": 24,
34
+ "num_key_value_heads": 16,
35
+ "rms_norm_eps": 1e-06,
36
+ "rope_theta": 1000000.0,
37
+ "sliding_window": 32768,
38
+ "tie_word_embeddings": false,
39
+ "tokenizer_model_max_length": 2560,
40
+ "tokenizer_padding_side": "right",
41
+ "torch_dtype": "float16",
42
+ "transformers_version": "4.36.0",
43
+ "tune_mm_mlp_adapter": false,
44
+ "use_cache": true,
45
+ "use_mm_proj": true,
46
+ "use_sliding_window": false,
47
+ "vocab_size": 151936
48
+ }
configuration_imp_qwen.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import math
3
+ from typing import Optional, Union
4
+
5
+ from transformers import PretrainedConfig
6
+ from transformers.utils import logging
7
+
8
+ logger = logging.get_logger(__name__)
9
+
10
+ QWEN2_PRETRAINED_CONFIG_ARCHIVE_MAP = {
11
+ "Qwen/Qwen2-7B-beta": "https://huggingface.co/Qwen/Qwen2-7B-beta/resolve/main/config.json",
12
+ }
13
+
14
+
15
+ class Qwen2Config(PretrainedConfig):
16
+ r"""
17
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
18
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
19
+ with the defaults will yield a similar configuration to that of
20
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
21
+
22
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
23
+ documentation from [`PretrainedConfig`] for more information.
24
+
25
+
26
+ Args:
27
+ vocab_size (`int`, *optional*, defaults to 151936):
28
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
29
+ `inputs_ids` passed when calling [`Qwen2Model`]
30
+ hidden_size (`int`, *optional*, defaults to 4096):
31
+ Dimension of the hidden representations.
32
+ intermediate_size (`int`, *optional*, defaults to 22016):
33
+ Dimension of the MLP representations.
34
+ num_hidden_layers (`int`, *optional*, defaults to 32):
35
+ Number of hidden layers in the Transformer encoder.
36
+ num_attention_heads (`int`, *optional*, defaults to 32):
37
+ Number of attention heads for each attention layer in the Transformer encoder.
38
+ num_key_value_heads (`int`, *optional*, defaults to 32):
39
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
40
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
41
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
42
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
43
+ by meanpooling all the original heads within that group. For more details checkout [this
44
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
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 32768):
48
+ The maximum sequence length that this model might ever be used with.
49
+ initializer_range (`float`, *optional*, defaults to 0.02):
50
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
51
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
52
+ The epsilon used by the rms normalization layers.
53
+ use_cache (`bool`, *optional*, defaults to `True`):
54
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
55
+ relevant if `config.is_decoder=True`.
56
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
57
+ Whether the model's input and output word embeddings should be tied.
58
+ rope_theta (`float`, *optional*, defaults to 10000.0):
59
+ The base period of the RoPE embeddings.
60
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
61
+ Whether to use sliding window attention.
62
+ sliding_window (`int`, *optional*, defaults to 4096):
63
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
64
+ max_window_layers (`int`, *optional*, defaults to 28):
65
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
66
+ attention_dropout (`float`, *optional*, defaults to 0.0):
67
+ The dropout ratio for the attention probabilities.
68
+
69
+ ```python
70
+ >>> from transformers import Qwen2Model, Qwen2Config
71
+
72
+ >>> # Initializing a Qwen2 style configuration
73
+ >>> configuration = Qwen2Config()
74
+
75
+ >>> # Initializing a model from the Qwen2-7B style configuration
76
+ >>> model = Qwen2Model(configuration)
77
+
78
+ >>> # Accessing the model configuration
79
+ >>> configuration = model.config
80
+ ```"""
81
+
82
+ model_type = "qwen2"
83
+ keys_to_ignore_at_inference = ["past_key_values"]
84
+
85
+ def __init__(
86
+ self,
87
+ vocab_size=151936,
88
+ hidden_size=4096,
89
+ intermediate_size=22016,
90
+ num_hidden_layers=32,
91
+ num_attention_heads=32,
92
+ num_key_value_heads=32,
93
+ hidden_act="silu",
94
+ max_position_embeddings=32768,
95
+ initializer_range=0.02,
96
+ rms_norm_eps=1e-6,
97
+ use_cache=True,
98
+ tie_word_embeddings=False,
99
+ rope_theta=10000.0,
100
+ use_sliding_window=False,
101
+ sliding_window=4096,
102
+ max_window_layers=28,
103
+ attention_dropout=0.0,
104
+ **kwargs,
105
+ ):
106
+ self.vocab_size = vocab_size
107
+ self.max_position_embeddings = max_position_embeddings
108
+ self.hidden_size = hidden_size
109
+ self.intermediate_size = intermediate_size
110
+ self.num_hidden_layers = num_hidden_layers
111
+ self.num_attention_heads = num_attention_heads
112
+ self.use_sliding_window = use_sliding_window
113
+ self.sliding_window = sliding_window
114
+ self.max_window_layers = max_window_layers
115
+
116
+ # for backward compatibility
117
+ if num_key_value_heads is None:
118
+ num_key_value_heads = num_attention_heads
119
+
120
+ self.num_key_value_heads = num_key_value_heads
121
+ self.hidden_act = hidden_act
122
+ self.initializer_range = initializer_range
123
+ self.rms_norm_eps = rms_norm_eps
124
+ self.use_cache = use_cache
125
+ self.rope_theta = rope_theta
126
+ self.attention_dropout = attention_dropout
127
+
128
+ super().__init__(
129
+ tie_word_embeddings=tie_word_embeddings,
130
+ **kwargs,
131
+ )
132
+
133
+
134
+ class SiglipVisionConfig(PretrainedConfig):
135
+
136
+ model_type = "siglip_vision_model"
137
+
138
+ def __init__(
139
+ self,
140
+ hidden_size=768,
141
+ intermediate_size=3072,
142
+ num_hidden_layers=12,
143
+ num_attention_heads=12,
144
+ num_channels=3,
145
+ image_size=224,
146
+ patch_size=16,
147
+ hidden_act="gelu_pytorch_tanh",
148
+ layer_norm_eps=1e-6,
149
+ attention_dropout=0.0,
150
+ **kwargs,
151
+ ):
152
+ super().__init__(**kwargs)
153
+
154
+ self.hidden_size = hidden_size
155
+ self.intermediate_size = intermediate_size
156
+ self.num_hidden_layers = num_hidden_layers
157
+ self.num_attention_heads = num_attention_heads
158
+ self.num_channels = num_channels
159
+ self.patch_size = patch_size
160
+ self.image_size = image_size
161
+ self.attention_dropout = attention_dropout
162
+ self.layer_norm_eps = layer_norm_eps
163
+ self.hidden_act = hidden_act
164
+
165
+ @classmethod
166
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
167
+ cls._set_token_in_kwargs(kwargs)
168
+
169
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
170
+
171
+ # get the vision config dict if we are loading from SiglipConfig
172
+ if config_dict.get("model_type") == "siglip":
173
+ config_dict = config_dict["vision_config"]
174
+
175
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
176
+ logger.warning(
177
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
178
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
179
+ )
180
+
181
+ return cls.from_dict(config_dict, **kwargs)
182
+
183
+ class ImpQwen2Config(Qwen2Config):
184
+ model_type = "imp_qwen2"
185
+
186
+ def __init__(self, **kwargs):
187
+ super().__init__(**kwargs)
188
+ self.image_token_index = getattr(self, "image_token_index", 50296)
189
+ self.image_token = getattr(self, "image_token", "<image>")
190
+
191
+ if not hasattr(self, "vision_tower_config") and hasattr(self, "mm_vision_tower"):
192
+ vision_tower_config = SiglipVisionConfig.from_pretrained(self.mm_vision_tower)
193
+ self.vision_tower_config = vision_tower_config.to_diff_dict()
194
+
195
+ @property
196
+ def vision_tower_cfg(self):
197
+ cfg = SiglipVisionConfig.from_dict(self.vision_tower_config)
198
+ # imp-v1 only supports `patch` feature for now w/o cls token
199
+ # cfg.mm_vision_select_feature = self.mm_vision_select_feature
200
+ cfg.mm_vision_select_layer = self.mm_vision_select_layer
201
+ cfg.mm_vision_tower = self.mm_vision_tower
202
+ return cfg
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "eos_token_id": [
4
+ 151645,
5
+ 151643
6
+ ],
7
+ "max_new_tokens": 128,
8
+ "pad_token_id": 151645,
9
+ "transformers_version": "4.36.0"
10
+ }
images/1.jpg ADDED
images/bird.jpg ADDED
images/bus.jpg ADDED
images/car.jpg ADDED
images/example1.png ADDED
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c9c1338630a4744421932156c88c3163ecad76e033325e2e4cb7ffd9e70a76b7
3
+ size 1004614672
model-00002-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb3e8b5ad6fd22cbb34f6cd826f3dd8f74ca56ea1aa588640511a222e008f34e
3
+ size 1012094024
model-00003-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1fbdd7955039dcd0c747d8c8a5786f91996bf1f8de9b1d8f3753d83a702cb40
3
+ size 1012094104
model-00004-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b2e2a5cfe5c95e606d05222294fbbc0c9d529bfef90452b479c236720a0a6f4d
3
+ size 831228328
model-00005-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c21c4014fd36ca937a4571b8c43ba063671ed99fcd2f7e4328bdde345dfd6dad
3
+ size 622329984
model.safetensors.index.json ADDED
@@ -0,0 +1,721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 4482263616
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00005-of-00005.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00005.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00005.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
13
+ "model.layers.0.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
14
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
15
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
16
+ "model.layers.0.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
17
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
18
+ "model.layers.0.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
19
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
20
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00005.safetensors",
21
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
22
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
23
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
24
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
25
+ "model.layers.1.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
26
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
27
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
28
+ "model.layers.1.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
29
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
30
+ "model.layers.1.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
31
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
32
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00005.safetensors",
33
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
34
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
35
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
36
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
37
+ "model.layers.10.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
38
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
39
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
40
+ "model.layers.10.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
41
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
42
+ "model.layers.10.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
43
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
44
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00005.safetensors",
45
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
46
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
47
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
48
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
49
+ "model.layers.11.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
50
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
51
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
52
+ "model.layers.11.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
53
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
54
+ "model.layers.11.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
55
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
56
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00005.safetensors",
57
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
58
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
59
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
60
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
61
+ "model.layers.12.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
62
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
63
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
64
+ "model.layers.12.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
65
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
66
+ "model.layers.12.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
67
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
68
+ "model.layers.13.input_layernorm.weight": "model-00003-of-00005.safetensors",
69
+ "model.layers.13.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
70
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
71
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
72
+ "model.layers.13.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
73
+ "model.layers.13.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
74
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
75
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
76
+ "model.layers.13.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
77
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
78
+ "model.layers.13.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
79
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
80
+ "model.layers.14.input_layernorm.weight": "model-00003-of-00005.safetensors",
81
+ "model.layers.14.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
82
+ "model.layers.14.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
83
+ "model.layers.14.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
84
+ "model.layers.14.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
85
+ "model.layers.14.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
86
+ "model.layers.14.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
87
+ "model.layers.14.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
88
+ "model.layers.14.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
89
+ "model.layers.14.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
90
+ "model.layers.14.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
91
+ "model.layers.14.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
92
+ "model.layers.15.input_layernorm.weight": "model-00003-of-00005.safetensors",
93
+ "model.layers.15.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
94
+ "model.layers.15.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
95
+ "model.layers.15.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
96
+ "model.layers.15.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
97
+ "model.layers.15.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
98
+ "model.layers.15.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
99
+ "model.layers.15.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
100
+ "model.layers.15.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
101
+ "model.layers.15.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
102
+ "model.layers.15.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
103
+ "model.layers.15.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
104
+ "model.layers.16.input_layernorm.weight": "model-00003-of-00005.safetensors",
105
+ "model.layers.16.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
106
+ "model.layers.16.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
107
+ "model.layers.16.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
108
+ "model.layers.16.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
109
+ "model.layers.16.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
110
+ "model.layers.16.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
111
+ "model.layers.16.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
112
+ "model.layers.16.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
113
+ "model.layers.16.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
114
+ "model.layers.16.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
115
+ "model.layers.16.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
116
+ "model.layers.17.input_layernorm.weight": "model-00003-of-00005.safetensors",
117
+ "model.layers.17.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
118
+ "model.layers.17.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
119
+ "model.layers.17.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
120
+ "model.layers.17.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
121
+ "model.layers.17.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
122
+ "model.layers.17.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
123
+ "model.layers.17.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
124
+ "model.layers.17.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
125
+ "model.layers.17.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
126
+ "model.layers.17.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
127
+ "model.layers.17.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
128
+ "model.layers.18.input_layernorm.weight": "model-00003-of-00005.safetensors",
129
+ "model.layers.18.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
130
+ "model.layers.18.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
131
+ "model.layers.18.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
132
+ "model.layers.18.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
133
+ "model.layers.18.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
134
+ "model.layers.18.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
135
+ "model.layers.18.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
136
+ "model.layers.18.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
137
+ "model.layers.18.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
138
+ "model.layers.18.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
139
+ "model.layers.18.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
140
+ "model.layers.19.input_layernorm.weight": "model-00003-of-00005.safetensors",
141
+ "model.layers.19.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
142
+ "model.layers.19.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
143
+ "model.layers.19.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
144
+ "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
145
+ "model.layers.19.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
146
+ "model.layers.19.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
147
+ "model.layers.19.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
148
+ "model.layers.19.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
149
+ "model.layers.19.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
150
+ "model.layers.19.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
151
+ "model.layers.19.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
152
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00005.safetensors",
153
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
154
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
155
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
156
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
157
+ "model.layers.2.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
158
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
159
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
160
+ "model.layers.2.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
161
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
162
+ "model.layers.2.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
163
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
164
+ "model.layers.20.input_layernorm.weight": "model-00003-of-00005.safetensors",
165
+ "model.layers.20.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
166
+ "model.layers.20.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
167
+ "model.layers.20.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
168
+ "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
169
+ "model.layers.20.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
170
+ "model.layers.20.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
171
+ "model.layers.20.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
172
+ "model.layers.20.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
173
+ "model.layers.20.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
174
+ "model.layers.20.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
175
+ "model.layers.20.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
176
+ "model.layers.21.input_layernorm.weight": "model-00003-of-00005.safetensors",
177
+ "model.layers.21.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
178
+ "model.layers.21.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
179
+ "model.layers.21.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
180
+ "model.layers.21.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
181
+ "model.layers.21.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
182
+ "model.layers.21.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
183
+ "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
184
+ "model.layers.21.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
185
+ "model.layers.21.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
186
+ "model.layers.21.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
187
+ "model.layers.21.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
188
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00005.safetensors",
189
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
190
+ "model.layers.22.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
191
+ "model.layers.22.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
192
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
193
+ "model.layers.22.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
194
+ "model.layers.22.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
195
+ "model.layers.22.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
196
+ "model.layers.22.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
197
+ "model.layers.22.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
198
+ "model.layers.22.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
199
+ "model.layers.22.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
200
+ "model.layers.23.input_layernorm.weight": "model-00004-of-00005.safetensors",
201
+ "model.layers.23.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
202
+ "model.layers.23.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
203
+ "model.layers.23.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
204
+ "model.layers.23.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
205
+ "model.layers.23.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
206
+ "model.layers.23.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
207
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
208
+ "model.layers.23.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
209
+ "model.layers.23.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
210
+ "model.layers.23.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
211
+ "model.layers.23.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
212
+ "model.layers.3.input_layernorm.weight": "model-00002-of-00005.safetensors",
213
+ "model.layers.3.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
214
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
215
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
216
+ "model.layers.3.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
217
+ "model.layers.3.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
218
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
219
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
220
+ "model.layers.3.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
221
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
222
+ "model.layers.3.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
223
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
224
+ "model.layers.4.input_layernorm.weight": "model-00002-of-00005.safetensors",
225
+ "model.layers.4.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
226
+ "model.layers.4.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
227
+ "model.layers.4.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
228
+ "model.layers.4.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
229
+ "model.layers.4.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
230
+ "model.layers.4.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
231
+ "model.layers.4.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
232
+ "model.layers.4.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
233
+ "model.layers.4.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
234
+ "model.layers.4.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
235
+ "model.layers.4.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
236
+ "model.layers.5.input_layernorm.weight": "model-00002-of-00005.safetensors",
237
+ "model.layers.5.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
238
+ "model.layers.5.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
239
+ "model.layers.5.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
240
+ "model.layers.5.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
241
+ "model.layers.5.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
242
+ "model.layers.5.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
243
+ "model.layers.5.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
244
+ "model.layers.5.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
245
+ "model.layers.5.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
246
+ "model.layers.5.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
247
+ "model.layers.5.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
248
+ "model.layers.6.input_layernorm.weight": "model-00002-of-00005.safetensors",
249
+ "model.layers.6.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
250
+ "model.layers.6.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
251
+ "model.layers.6.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
252
+ "model.layers.6.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
253
+ "model.layers.6.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
254
+ "model.layers.6.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
255
+ "model.layers.6.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
256
+ "model.layers.6.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
257
+ "model.layers.6.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
258
+ "model.layers.6.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
259
+ "model.layers.6.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
260
+ "model.layers.7.input_layernorm.weight": "model-00002-of-00005.safetensors",
261
+ "model.layers.7.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
262
+ "model.layers.7.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
263
+ "model.layers.7.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
264
+ "model.layers.7.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
265
+ "model.layers.7.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
266
+ "model.layers.7.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
267
+ "model.layers.7.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
268
+ "model.layers.7.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
269
+ "model.layers.7.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
270
+ "model.layers.7.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
271
+ "model.layers.7.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
272
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00005.safetensors",
273
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
274
+ "model.layers.8.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
275
+ "model.layers.8.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
276
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
277
+ "model.layers.8.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
278
+ "model.layers.8.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
279
+ "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
280
+ "model.layers.8.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
281
+ "model.layers.8.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
282
+ "model.layers.8.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
283
+ "model.layers.8.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
284
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00005.safetensors",
285
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
286
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
287
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
288
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
289
+ "model.layers.9.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
290
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
291
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
292
+ "model.layers.9.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
293
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
294
+ "model.layers.9.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
295
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
296
+ "model.mm_projector.0.bias": "model-00004-of-00005.safetensors",
297
+ "model.mm_projector.0.weight": "model-00004-of-00005.safetensors",
298
+ "model.mm_projector.2.bias": "model-00004-of-00005.safetensors",
299
+ "model.mm_projector.2.weight": "model-00004-of-00005.safetensors",
300
+ "model.norm.weight": "model-00004-of-00005.safetensors",
301
+ "model.vision_tower.vision_tower.vision_model.embeddings.patch_embedding.bias": "model-00004-of-00005.safetensors",
302
+ "model.vision_tower.vision_tower.vision_model.embeddings.patch_embedding.weight": "model-00004-of-00005.safetensors",
303
+ "model.vision_tower.vision_tower.vision_model.embeddings.position_embedding.weight": "model-00004-of-00005.safetensors",
304
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.layer_norm1.bias": "model-00004-of-00005.safetensors",
305
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.layer_norm1.weight": "model-00004-of-00005.safetensors",
306
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.layer_norm2.bias": "model-00004-of-00005.safetensors",
307
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.layer_norm2.weight": "model-00004-of-00005.safetensors",
308
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.mlp.fc1.bias": "model-00004-of-00005.safetensors",
309
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.mlp.fc1.weight": "model-00004-of-00005.safetensors",
310
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.mlp.fc2.bias": "model-00004-of-00005.safetensors",
311
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.mlp.fc2.weight": "model-00004-of-00005.safetensors",
312
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
313
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
314
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
315
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
316
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
317
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
318
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
319
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.0.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
320
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.layer_norm1.bias": "model-00004-of-00005.safetensors",
321
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.layer_norm1.weight": "model-00004-of-00005.safetensors",
322
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.layer_norm2.bias": "model-00004-of-00005.safetensors",
323
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.layer_norm2.weight": "model-00004-of-00005.safetensors",
324
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.mlp.fc1.bias": "model-00004-of-00005.safetensors",
325
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.mlp.fc1.weight": "model-00004-of-00005.safetensors",
326
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.mlp.fc2.bias": "model-00004-of-00005.safetensors",
327
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.mlp.fc2.weight": "model-00004-of-00005.safetensors",
328
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
329
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
330
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
331
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
332
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
333
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
334
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
335
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.1.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
336
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.layer_norm1.bias": "model-00004-of-00005.safetensors",
337
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.layer_norm1.weight": "model-00004-of-00005.safetensors",
338
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.layer_norm2.bias": "model-00004-of-00005.safetensors",
339
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.layer_norm2.weight": "model-00004-of-00005.safetensors",
340
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.mlp.fc1.bias": "model-00004-of-00005.safetensors",
341
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.mlp.fc1.weight": "model-00004-of-00005.safetensors",
342
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.mlp.fc2.bias": "model-00004-of-00005.safetensors",
343
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.mlp.fc2.weight": "model-00004-of-00005.safetensors",
344
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
345
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
346
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
347
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
348
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
349
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
350
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
351
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.10.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
352
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.layer_norm1.bias": "model-00004-of-00005.safetensors",
353
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.layer_norm1.weight": "model-00004-of-00005.safetensors",
354
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.layer_norm2.bias": "model-00004-of-00005.safetensors",
355
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.layer_norm2.weight": "model-00004-of-00005.safetensors",
356
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.mlp.fc1.bias": "model-00004-of-00005.safetensors",
357
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.mlp.fc1.weight": "model-00004-of-00005.safetensors",
358
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.mlp.fc2.bias": "model-00004-of-00005.safetensors",
359
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.mlp.fc2.weight": "model-00004-of-00005.safetensors",
360
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
361
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
362
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
363
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
364
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
365
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
366
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
367
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.11.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
368
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.layer_norm1.bias": "model-00004-of-00005.safetensors",
369
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.layer_norm1.weight": "model-00004-of-00005.safetensors",
370
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.layer_norm2.bias": "model-00004-of-00005.safetensors",
371
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.layer_norm2.weight": "model-00004-of-00005.safetensors",
372
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.mlp.fc1.bias": "model-00004-of-00005.safetensors",
373
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.mlp.fc1.weight": "model-00004-of-00005.safetensors",
374
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.mlp.fc2.bias": "model-00004-of-00005.safetensors",
375
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.mlp.fc2.weight": "model-00004-of-00005.safetensors",
376
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
377
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
378
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
379
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
380
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
381
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
382
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
383
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.12.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
384
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.layer_norm1.bias": "model-00004-of-00005.safetensors",
385
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.layer_norm1.weight": "model-00004-of-00005.safetensors",
386
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.layer_norm2.bias": "model-00004-of-00005.safetensors",
387
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.layer_norm2.weight": "model-00004-of-00005.safetensors",
388
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.mlp.fc1.bias": "model-00004-of-00005.safetensors",
389
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.mlp.fc1.weight": "model-00004-of-00005.safetensors",
390
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.mlp.fc2.bias": "model-00004-of-00005.safetensors",
391
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.mlp.fc2.weight": "model-00004-of-00005.safetensors",
392
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
393
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
394
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
395
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
396
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
397
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
398
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
399
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.13.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
400
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.layer_norm1.bias": "model-00004-of-00005.safetensors",
401
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.layer_norm1.weight": "model-00004-of-00005.safetensors",
402
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.layer_norm2.bias": "model-00004-of-00005.safetensors",
403
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.layer_norm2.weight": "model-00004-of-00005.safetensors",
404
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.mlp.fc1.bias": "model-00004-of-00005.safetensors",
405
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.mlp.fc1.weight": "model-00004-of-00005.safetensors",
406
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.mlp.fc2.bias": "model-00004-of-00005.safetensors",
407
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.mlp.fc2.weight": "model-00004-of-00005.safetensors",
408
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
409
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
410
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
411
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
412
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
413
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
414
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
415
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.14.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
416
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.layer_norm1.bias": "model-00004-of-00005.safetensors",
417
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.layer_norm1.weight": "model-00004-of-00005.safetensors",
418
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.layer_norm2.bias": "model-00004-of-00005.safetensors",
419
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.layer_norm2.weight": "model-00004-of-00005.safetensors",
420
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.mlp.fc1.bias": "model-00004-of-00005.safetensors",
421
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.mlp.fc1.weight": "model-00004-of-00005.safetensors",
422
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.mlp.fc2.bias": "model-00004-of-00005.safetensors",
423
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.mlp.fc2.weight": "model-00004-of-00005.safetensors",
424
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
425
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
426
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
427
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
428
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
429
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
430
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
431
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.15.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
432
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.layer_norm1.bias": "model-00004-of-00005.safetensors",
433
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.layer_norm1.weight": "model-00004-of-00005.safetensors",
434
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.layer_norm2.bias": "model-00004-of-00005.safetensors",
435
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.layer_norm2.weight": "model-00004-of-00005.safetensors",
436
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.mlp.fc1.bias": "model-00004-of-00005.safetensors",
437
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.mlp.fc1.weight": "model-00004-of-00005.safetensors",
438
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.mlp.fc2.bias": "model-00004-of-00005.safetensors",
439
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.mlp.fc2.weight": "model-00004-of-00005.safetensors",
440
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
441
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
442
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
443
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
444
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
445
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
446
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
447
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.16.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
448
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.layer_norm1.bias": "model-00004-of-00005.safetensors",
449
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.layer_norm1.weight": "model-00004-of-00005.safetensors",
450
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.layer_norm2.bias": "model-00004-of-00005.safetensors",
451
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.layer_norm2.weight": "model-00004-of-00005.safetensors",
452
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.mlp.fc1.bias": "model-00004-of-00005.safetensors",
453
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.mlp.fc1.weight": "model-00004-of-00005.safetensors",
454
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.mlp.fc2.bias": "model-00004-of-00005.safetensors",
455
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.mlp.fc2.weight": "model-00004-of-00005.safetensors",
456
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
457
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
458
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
459
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
460
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
461
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
462
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
463
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.17.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
464
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.layer_norm1.bias": "model-00004-of-00005.safetensors",
465
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.layer_norm1.weight": "model-00004-of-00005.safetensors",
466
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.layer_norm2.bias": "model-00004-of-00005.safetensors",
467
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.layer_norm2.weight": "model-00004-of-00005.safetensors",
468
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.mlp.fc1.bias": "model-00004-of-00005.safetensors",
469
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.mlp.fc1.weight": "model-00004-of-00005.safetensors",
470
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.mlp.fc2.bias": "model-00004-of-00005.safetensors",
471
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.mlp.fc2.weight": "model-00004-of-00005.safetensors",
472
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
473
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
474
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
475
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
476
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
477
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
478
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
479
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.18.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
480
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.layer_norm1.bias": "model-00004-of-00005.safetensors",
481
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.layer_norm1.weight": "model-00004-of-00005.safetensors",
482
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.layer_norm2.bias": "model-00004-of-00005.safetensors",
483
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.layer_norm2.weight": "model-00004-of-00005.safetensors",
484
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.mlp.fc1.bias": "model-00004-of-00005.safetensors",
485
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.mlp.fc1.weight": "model-00004-of-00005.safetensors",
486
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.mlp.fc2.bias": "model-00004-of-00005.safetensors",
487
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.mlp.fc2.weight": "model-00004-of-00005.safetensors",
488
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
489
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
490
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
491
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
492
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
493
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
494
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
495
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.19.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
496
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.layer_norm1.bias": "model-00004-of-00005.safetensors",
497
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.layer_norm1.weight": "model-00004-of-00005.safetensors",
498
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.layer_norm2.bias": "model-00004-of-00005.safetensors",
499
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.layer_norm2.weight": "model-00004-of-00005.safetensors",
500
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.mlp.fc1.bias": "model-00004-of-00005.safetensors",
501
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.mlp.fc1.weight": "model-00004-of-00005.safetensors",
502
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.mlp.fc2.bias": "model-00004-of-00005.safetensors",
503
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.mlp.fc2.weight": "model-00004-of-00005.safetensors",
504
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
505
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
506
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
507
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
508
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
509
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
510
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
511
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.2.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
512
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.layer_norm1.bias": "model-00004-of-00005.safetensors",
513
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.layer_norm1.weight": "model-00004-of-00005.safetensors",
514
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.layer_norm2.bias": "model-00004-of-00005.safetensors",
515
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.layer_norm2.weight": "model-00004-of-00005.safetensors",
516
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.mlp.fc1.bias": "model-00004-of-00005.safetensors",
517
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.mlp.fc1.weight": "model-00004-of-00005.safetensors",
518
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.mlp.fc2.bias": "model-00004-of-00005.safetensors",
519
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.mlp.fc2.weight": "model-00004-of-00005.safetensors",
520
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
521
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
522
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
523
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
524
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
525
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
526
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
527
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.20.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
528
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.layer_norm1.bias": "model-00004-of-00005.safetensors",
529
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.layer_norm1.weight": "model-00004-of-00005.safetensors",
530
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.layer_norm2.bias": "model-00004-of-00005.safetensors",
531
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.layer_norm2.weight": "model-00004-of-00005.safetensors",
532
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.mlp.fc1.bias": "model-00004-of-00005.safetensors",
533
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.mlp.fc1.weight": "model-00004-of-00005.safetensors",
534
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.mlp.fc2.bias": "model-00004-of-00005.safetensors",
535
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.mlp.fc2.weight": "model-00004-of-00005.safetensors",
536
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
537
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
538
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
539
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
540
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
541
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
542
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
543
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.21.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
544
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.layer_norm1.bias": "model-00004-of-00005.safetensors",
545
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.layer_norm1.weight": "model-00004-of-00005.safetensors",
546
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.layer_norm2.bias": "model-00004-of-00005.safetensors",
547
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.layer_norm2.weight": "model-00004-of-00005.safetensors",
548
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.mlp.fc1.bias": "model-00004-of-00005.safetensors",
549
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.mlp.fc1.weight": "model-00004-of-00005.safetensors",
550
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.mlp.fc2.bias": "model-00004-of-00005.safetensors",
551
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.mlp.fc2.weight": "model-00004-of-00005.safetensors",
552
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
553
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
554
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
555
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
556
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
557
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
558
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
559
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.22.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
560
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.layer_norm1.bias": "model-00004-of-00005.safetensors",
561
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.layer_norm1.weight": "model-00004-of-00005.safetensors",
562
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.layer_norm2.bias": "model-00004-of-00005.safetensors",
563
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.layer_norm2.weight": "model-00004-of-00005.safetensors",
564
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.mlp.fc1.bias": "model-00004-of-00005.safetensors",
565
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.mlp.fc1.weight": "model-00004-of-00005.safetensors",
566
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.mlp.fc2.bias": "model-00004-of-00005.safetensors",
567
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.mlp.fc2.weight": "model-00004-of-00005.safetensors",
568
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
569
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
570
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
571
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
572
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
573
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
574
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
575
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.23.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
576
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.layer_norm1.bias": "model-00004-of-00005.safetensors",
577
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.layer_norm1.weight": "model-00004-of-00005.safetensors",
578
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.layer_norm2.bias": "model-00004-of-00005.safetensors",
579
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.layer_norm2.weight": "model-00004-of-00005.safetensors",
580
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.mlp.fc1.bias": "model-00004-of-00005.safetensors",
581
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.mlp.fc1.weight": "model-00004-of-00005.safetensors",
582
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.mlp.fc2.bias": "model-00004-of-00005.safetensors",
583
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.mlp.fc2.weight": "model-00004-of-00005.safetensors",
584
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
585
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
586
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
587
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
588
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
589
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
590
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
591
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.24.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
592
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.layer_norm1.bias": "model-00004-of-00005.safetensors",
593
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.layer_norm1.weight": "model-00004-of-00005.safetensors",
594
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.layer_norm2.bias": "model-00004-of-00005.safetensors",
595
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.layer_norm2.weight": "model-00004-of-00005.safetensors",
596
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.mlp.fc1.bias": "model-00004-of-00005.safetensors",
597
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.mlp.fc1.weight": "model-00004-of-00005.safetensors",
598
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.mlp.fc2.bias": "model-00004-of-00005.safetensors",
599
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.mlp.fc2.weight": "model-00004-of-00005.safetensors",
600
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
601
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
602
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
603
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
604
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
605
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
606
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
607
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.25.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
608
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.layer_norm1.bias": "model-00004-of-00005.safetensors",
609
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.layer_norm1.weight": "model-00004-of-00005.safetensors",
610
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.layer_norm2.bias": "model-00004-of-00005.safetensors",
611
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.layer_norm2.weight": "model-00004-of-00005.safetensors",
612
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.mlp.fc1.bias": "model-00004-of-00005.safetensors",
613
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.mlp.fc1.weight": "model-00004-of-00005.safetensors",
614
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.mlp.fc2.bias": "model-00004-of-00005.safetensors",
615
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.mlp.fc2.weight": "model-00004-of-00005.safetensors",
616
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
617
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
618
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
619
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
620
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
621
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
622
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
623
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.3.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
624
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.layer_norm1.bias": "model-00004-of-00005.safetensors",
625
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.layer_norm1.weight": "model-00004-of-00005.safetensors",
626
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.layer_norm2.bias": "model-00004-of-00005.safetensors",
627
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.layer_norm2.weight": "model-00004-of-00005.safetensors",
628
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.mlp.fc1.bias": "model-00004-of-00005.safetensors",
629
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.mlp.fc1.weight": "model-00004-of-00005.safetensors",
630
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.mlp.fc2.bias": "model-00004-of-00005.safetensors",
631
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.mlp.fc2.weight": "model-00004-of-00005.safetensors",
632
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
633
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
634
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
635
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
636
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
637
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
638
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
639
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.4.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
640
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.layer_norm1.bias": "model-00004-of-00005.safetensors",
641
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.layer_norm1.weight": "model-00004-of-00005.safetensors",
642
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.layer_norm2.bias": "model-00004-of-00005.safetensors",
643
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.layer_norm2.weight": "model-00004-of-00005.safetensors",
644
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.mlp.fc1.bias": "model-00004-of-00005.safetensors",
645
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.mlp.fc1.weight": "model-00004-of-00005.safetensors",
646
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.mlp.fc2.bias": "model-00004-of-00005.safetensors",
647
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.mlp.fc2.weight": "model-00004-of-00005.safetensors",
648
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
649
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
650
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
651
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
652
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
653
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
654
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
655
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.5.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
656
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.layer_norm1.bias": "model-00004-of-00005.safetensors",
657
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.layer_norm1.weight": "model-00004-of-00005.safetensors",
658
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.layer_norm2.bias": "model-00004-of-00005.safetensors",
659
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.layer_norm2.weight": "model-00004-of-00005.safetensors",
660
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.mlp.fc1.bias": "model-00004-of-00005.safetensors",
661
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.mlp.fc1.weight": "model-00004-of-00005.safetensors",
662
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.mlp.fc2.bias": "model-00004-of-00005.safetensors",
663
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.mlp.fc2.weight": "model-00004-of-00005.safetensors",
664
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
665
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
666
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
667
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
668
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
669
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
670
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
671
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.6.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
672
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.layer_norm1.bias": "model-00004-of-00005.safetensors",
673
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.layer_norm1.weight": "model-00004-of-00005.safetensors",
674
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.layer_norm2.bias": "model-00004-of-00005.safetensors",
675
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.layer_norm2.weight": "model-00004-of-00005.safetensors",
676
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.mlp.fc1.bias": "model-00004-of-00005.safetensors",
677
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.mlp.fc1.weight": "model-00004-of-00005.safetensors",
678
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.mlp.fc2.bias": "model-00004-of-00005.safetensors",
679
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.mlp.fc2.weight": "model-00004-of-00005.safetensors",
680
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
681
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
682
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
683
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
684
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
685
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
686
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
687
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.7.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
688
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.layer_norm1.bias": "model-00004-of-00005.safetensors",
689
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.layer_norm1.weight": "model-00004-of-00005.safetensors",
690
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.layer_norm2.bias": "model-00004-of-00005.safetensors",
691
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.layer_norm2.weight": "model-00004-of-00005.safetensors",
692
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.mlp.fc1.bias": "model-00004-of-00005.safetensors",
693
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.mlp.fc1.weight": "model-00004-of-00005.safetensors",
694
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.mlp.fc2.bias": "model-00004-of-00005.safetensors",
695
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.mlp.fc2.weight": "model-00004-of-00005.safetensors",
696
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
697
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
698
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
699
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
700
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
701
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
702
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
703
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.8.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
704
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.layer_norm1.bias": "model-00004-of-00005.safetensors",
705
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.layer_norm1.weight": "model-00004-of-00005.safetensors",
706
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.layer_norm2.bias": "model-00004-of-00005.safetensors",
707
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.layer_norm2.weight": "model-00004-of-00005.safetensors",
708
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.mlp.fc1.bias": "model-00004-of-00005.safetensors",
709
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.mlp.fc1.weight": "model-00004-of-00005.safetensors",
710
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.mlp.fc2.bias": "model-00004-of-00005.safetensors",
711
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.mlp.fc2.weight": "model-00004-of-00005.safetensors",
712
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
713
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
714
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.out_proj.bias": "model-00004-of-00005.safetensors",
715
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.out_proj.weight": "model-00004-of-00005.safetensors",
716
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
717
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
718
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
719
+ "model.vision_tower.vision_tower.vision_model.encoder.layers.9.self_attn.v_proj.weight": "model-00004-of-00005.safetensors"
720
+ }
721
+ }
modeling_imp_qwen.py ADDED
@@ -0,0 +1,1725 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+
3
+ # from transformers import PretrainedConfig, PreTrainedModel
4
+ """ PyTorch Qwen2 model."""
5
+ import inspect
6
+ import math
7
+ import warnings
8
+ from typing import List, Optional, Tuple, Union
9
+
10
+ import os
11
+ import re
12
+ import torch
13
+ import torch.nn.functional as F
14
+ import torch.utils.checkpoint
15
+ from torch import nn
16
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
17
+ from transformers import AutoConfig, AutoModelForCausalLM
18
+
19
+ from transformers.activations import ACT2FN
20
+ from transformers.cache_utils import Cache, DynamicCache
21
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
22
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
23
+ from transformers.modeling_utils import PreTrainedModel
24
+ from transformers.utils import (
25
+ add_start_docstrings,
26
+ add_start_docstrings_to_model_forward,
27
+ is_flash_attn_2_available,
28
+ is_flash_attn_greater_or_equal_2_10,
29
+ logging,
30
+ replace_return_docstrings,
31
+ )
32
+ from .configuration_imp_qwen import Qwen2Config,ImpQwen2Config
33
+ from .vision_encoder import VisionTower
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
40
+ _CONFIG_FOR_DOC = "Qwen2Config"
41
+
42
+ QWEN2_PRETRAINED_MODEL_ARCHIVE_LIST = [
43
+ "Qwen/Qwen2-7B-beta",
44
+ # See all Qwen2 models at https://huggingface.co/models?filter=qwen2
45
+ ]
46
+
47
+
48
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
49
+ def _get_unpad_data(attention_mask):
50
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
51
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
52
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
53
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
54
+ return (
55
+ indices,
56
+ cu_seqlens,
57
+ max_seqlen_in_batch,
58
+ )
59
+
60
+
61
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
62
+ class Qwen2RMSNorm(nn.Module):
63
+ def __init__(self, hidden_size, eps=1e-6):
64
+ """
65
+ Qwen2RMSNorm is equivalent to T5LayerNorm
66
+ """
67
+ super().__init__()
68
+ self.weight = nn.Parameter(torch.ones(hidden_size))
69
+ self.variance_epsilon = eps
70
+
71
+ def forward(self, hidden_states):
72
+ input_dtype = hidden_states.dtype
73
+ hidden_states = hidden_states.to(torch.float32)
74
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
75
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
76
+ return self.weight * hidden_states.to(input_dtype)
77
+
78
+
79
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Qwen2
80
+ class Qwen2RotaryEmbedding(nn.Module):
81
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
82
+ super().__init__()
83
+
84
+ self.dim = dim
85
+ self.max_position_embeddings = max_position_embeddings
86
+ self.base = base
87
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
88
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
89
+
90
+ # Build here to make `torch.jit.trace` work.
91
+ self._set_cos_sin_cache(
92
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
93
+ )
94
+
95
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
96
+ self.max_seq_len_cached = seq_len
97
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
98
+
99
+ freqs = torch.outer(t, self.inv_freq)
100
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
101
+ emb = torch.cat((freqs, freqs), dim=-1)
102
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
103
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
104
+
105
+ def forward(self, x, seq_len=None):
106
+ # x: [bs, num_attention_heads, seq_len, head_size]
107
+ if seq_len > self.max_seq_len_cached:
108
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
109
+
110
+ return (
111
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
112
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
113
+ )
114
+
115
+
116
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
117
+ def rotate_half(x):
118
+ """Rotates half the hidden dims of the input."""
119
+ x1 = x[..., : x.shape[-1] // 2]
120
+ x2 = x[..., x.shape[-1] // 2 :]
121
+ return torch.cat((-x2, x1), dim=-1)
122
+
123
+
124
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
125
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
126
+ """Applies Rotary Position Embedding to the query and key tensors.
127
+
128
+ Args:
129
+ q (`torch.Tensor`): The query tensor.
130
+ k (`torch.Tensor`): The key tensor.
131
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
132
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
133
+ position_ids (`torch.Tensor`):
134
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
135
+ used to pass offsetted position ids when working with a KV-cache.
136
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
137
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
138
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
139
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
140
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
141
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
142
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
143
+ Returns:
144
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
145
+ """
146
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
147
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
148
+ q_embed = (q * cos) + (rotate_half(q) * sin)
149
+ k_embed = (k * cos) + (rotate_half(k) * sin)
150
+ return q_embed, k_embed
151
+
152
+
153
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
154
+ class Qwen2MLP(nn.Module):
155
+ def __init__(self, config):
156
+ super().__init__()
157
+ self.config = config
158
+ self.hidden_size = config.hidden_size
159
+ self.intermediate_size = config.intermediate_size
160
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
161
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
162
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
163
+ self.act_fn = ACT2FN[config.hidden_act]
164
+
165
+ def forward(self, x):
166
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
167
+
168
+
169
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
170
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
171
+ """
172
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
173
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
174
+ """
175
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
176
+ if n_rep == 1:
177
+ return hidden_states
178
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
179
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
180
+
181
+
182
+ class Qwen2Attention(nn.Module):
183
+ """
184
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
185
+ and "Generating Long Sequences with Sparse Transformers".
186
+ """
187
+
188
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
189
+ super().__init__()
190
+ self.config = config
191
+ self.layer_idx = layer_idx
192
+ if layer_idx is None:
193
+ logger.warning_once(
194
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
195
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
196
+ "when creating this class."
197
+ )
198
+
199
+ self.hidden_size = config.hidden_size
200
+ self.num_heads = config.num_attention_heads
201
+ self.head_dim = self.hidden_size // self.num_heads
202
+ self.num_key_value_heads = config.num_key_value_heads
203
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
204
+ self.max_position_embeddings = config.max_position_embeddings
205
+ self.rope_theta = config.rope_theta
206
+ self.is_causal = True
207
+ self.attention_dropout = config.attention_dropout
208
+
209
+ if (self.head_dim * self.num_heads) != self.hidden_size:
210
+ raise ValueError(
211
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
212
+ f" and `num_heads`: {self.num_heads})."
213
+ )
214
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
215
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
216
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
217
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
218
+
219
+ self.rotary_emb = Qwen2RotaryEmbedding(
220
+ self.head_dim,
221
+ max_position_embeddings=self.max_position_embeddings,
222
+ base=self.rope_theta,
223
+ )
224
+
225
+ def forward(
226
+ self,
227
+ hidden_states: torch.Tensor,
228
+ attention_mask: Optional[torch.Tensor] = None,
229
+ position_ids: Optional[torch.LongTensor] = None,
230
+ past_key_value: Optional[Cache] = None,
231
+ output_attentions: bool = False,
232
+ use_cache: bool = False,
233
+ **kwargs,
234
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
235
+ if "padding_mask" in kwargs:
236
+ warnings.warn(
237
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
238
+ )
239
+ bsz, q_len, _ = hidden_states.size()
240
+
241
+ query_states = self.q_proj(hidden_states)
242
+ key_states = self.k_proj(hidden_states)
243
+ value_states = self.v_proj(hidden_states)
244
+
245
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
246
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
247
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
248
+
249
+ kv_seq_len = key_states.shape[-2]
250
+ if past_key_value is not None:
251
+ if self.layer_idx is None:
252
+ raise ValueError(
253
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
254
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
255
+ "with a layer index."
256
+ )
257
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
258
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
259
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
260
+
261
+ if past_key_value is not None:
262
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
263
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
264
+
265
+ # repeat k/v heads if n_kv_heads < n_heads
266
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
267
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
268
+
269
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
270
+
271
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
272
+ raise ValueError(
273
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
274
+ f" {attn_weights.size()}"
275
+ )
276
+
277
+ if attention_mask is not None:
278
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
279
+ raise ValueError(
280
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
281
+ )
282
+
283
+ attn_weights = attn_weights + attention_mask
284
+
285
+ # upcast attention to fp32
286
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
287
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
288
+ attn_output = torch.matmul(attn_weights, value_states)
289
+
290
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
291
+ raise ValueError(
292
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
293
+ f" {attn_output.size()}"
294
+ )
295
+
296
+ attn_output = attn_output.transpose(1, 2).contiguous()
297
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
298
+
299
+ attn_output = self.o_proj(attn_output)
300
+
301
+ if not output_attentions:
302
+ attn_weights = None
303
+
304
+ return attn_output, attn_weights, past_key_value
305
+
306
+
307
+ class Qwen2FlashAttention2(Qwen2Attention):
308
+ """
309
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
310
+ as the weights of the module stays untouched. The only required change would be on the forward pass
311
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
312
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
313
+ config.max_window_layers layers.
314
+ """
315
+
316
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
317
+ def __init__(self, *args, **kwargs):
318
+ super().__init__(*args, **kwargs)
319
+
320
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
321
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
322
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
323
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
324
+
325
+ def forward(
326
+ self,
327
+ hidden_states: torch.Tensor,
328
+ attention_mask: Optional[torch.Tensor] = None,
329
+ position_ids: Optional[torch.LongTensor] = None,
330
+ past_key_value: Optional[Cache] = None,
331
+ output_attentions: bool = False,
332
+ use_cache: bool = False,
333
+ **kwargs,
334
+ ):
335
+ if "padding_mask" in kwargs:
336
+ warnings.warn(
337
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
338
+ )
339
+
340
+ # overwrite attention_mask with padding_mask
341
+ attention_mask = kwargs.pop("padding_mask")
342
+ bsz, q_len, _ = hidden_states.size()
343
+
344
+ query_states = self.q_proj(hidden_states)
345
+ key_states = self.k_proj(hidden_states)
346
+ value_states = self.v_proj(hidden_states)
347
+
348
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
349
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
350
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
351
+
352
+ kv_seq_len = key_states.shape[-2]
353
+ if past_key_value is not None:
354
+ if self.layer_idx is None:
355
+ raise ValueError(
356
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
357
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
358
+ "with a layer index."
359
+ )
360
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
361
+
362
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
363
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
364
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
365
+
366
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
367
+
368
+ use_sliding_windows = (
369
+ _flash_supports_window_size
370
+ and getattr(self.config, "sliding_window", None) is not None
371
+ and kv_seq_len > self.config.sliding_window
372
+ and self.config.use_sliding_window
373
+ )
374
+
375
+ if not _flash_supports_window_size:
376
+ logger.warning_once(
377
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
378
+ " make sure to upgrade flash-attn library."
379
+ )
380
+
381
+ if past_key_value is not None:
382
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
383
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
384
+ if (
385
+ getattr(self.config, "sliding_window", None) is not None
386
+ and kv_seq_len > self.config.sliding_window
387
+ and cache_has_contents
388
+ ):
389
+ slicing_tokens = 1 - self.config.sliding_window
390
+
391
+ past_key = past_key_value[self.layer_idx][0]
392
+ past_value = past_key_value[self.layer_idx][1]
393
+
394
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
395
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
396
+
397
+ if past_key.shape[-2] != self.config.sliding_window - 1:
398
+ raise ValueError(
399
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
400
+ f" {past_key.shape}"
401
+ )
402
+
403
+ if attention_mask is not None:
404
+ attention_mask = attention_mask[:, slicing_tokens:]
405
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
406
+
407
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
408
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
409
+
410
+ # repeat k/v heads if n_kv_heads < n_heads
411
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
412
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
413
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
414
+
415
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
416
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
417
+ # cast them back in float16 just to be sure everything works as expected.
418
+ input_dtype = query_states.dtype
419
+ if input_dtype == torch.float32:
420
+ if torch.is_autocast_enabled():
421
+ target_dtype = torch.get_autocast_gpu_dtype()
422
+ # Handle the case where the model is quantized
423
+ elif hasattr(self.config, "_pre_quantization_dtype"):
424
+ target_dtype = self.config._pre_quantization_dtype
425
+ else:
426
+ target_dtype = self.q_proj.weight.dtype
427
+
428
+ logger.warning_once(
429
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
430
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
431
+ f" {target_dtype}."
432
+ )
433
+
434
+ query_states = query_states.to(target_dtype)
435
+ key_states = key_states.to(target_dtype)
436
+ value_states = value_states.to(target_dtype)
437
+
438
+ # Reashape to the expected shape for Flash Attention
439
+ query_states = query_states.transpose(1, 2)
440
+ key_states = key_states.transpose(1, 2)
441
+ value_states = value_states.transpose(1, 2)
442
+
443
+ attn_output = self._flash_attention_forward(
444
+ query_states,
445
+ key_states,
446
+ value_states,
447
+ attention_mask,
448
+ q_len,
449
+ dropout=dropout_rate,
450
+ use_sliding_windows=use_sliding_windows,
451
+ )
452
+
453
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
454
+ attn_output = self.o_proj(attn_output)
455
+
456
+ if not output_attentions:
457
+ attn_weights = None
458
+
459
+ return attn_output, attn_weights, past_key_value
460
+
461
+ def _flash_attention_forward(
462
+ self,
463
+ query_states,
464
+ key_states,
465
+ value_states,
466
+ attention_mask,
467
+ query_length,
468
+ dropout=0.0,
469
+ softmax_scale=None,
470
+ use_sliding_windows=False,
471
+ ):
472
+ """
473
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
474
+ first unpad the input, then computes the attention scores and pad the final attention scores.
475
+
476
+ Args:
477
+ query_states (`torch.Tensor`):
478
+ Input query states to be passed to Flash Attention API
479
+ key_states (`torch.Tensor`):
480
+ Input key states to be passed to Flash Attention API
481
+ value_states (`torch.Tensor`):
482
+ Input value states to be passed to Flash Attention API
483
+ attention_mask (`torch.Tensor`):
484
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
485
+ position of padding tokens and 1 for the position of non-padding tokens.
486
+ dropout (`int`, *optional*):
487
+ Attention dropout
488
+ softmax_scale (`float`, *optional*):
489
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
490
+ use_sliding_windows (`bool`, *optional*):
491
+ Whether to activate sliding window attention.
492
+ """
493
+ if not self._flash_attn_uses_top_left_mask:
494
+ causal = self.is_causal
495
+ else:
496
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
497
+ causal = self.is_causal and query_length != 1
498
+
499
+ # Decide whether to use SWA or not by layer index.
500
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
501
+ use_sliding_windows = False
502
+
503
+ # Contains at least one padding token in the sequence
504
+ if attention_mask is not None:
505
+ batch_size = query_states.shape[0]
506
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
507
+ query_states, key_states, value_states, attention_mask, query_length
508
+ )
509
+
510
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
511
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
512
+
513
+ if not use_sliding_windows:
514
+ attn_output_unpad = flash_attn_varlen_func(
515
+ query_states,
516
+ key_states,
517
+ value_states,
518
+ cu_seqlens_q=cu_seqlens_q,
519
+ cu_seqlens_k=cu_seqlens_k,
520
+ max_seqlen_q=max_seqlen_in_batch_q,
521
+ max_seqlen_k=max_seqlen_in_batch_k,
522
+ dropout_p=dropout,
523
+ softmax_scale=softmax_scale,
524
+ causal=causal,
525
+ )
526
+ else:
527
+ attn_output_unpad = flash_attn_varlen_func(
528
+ query_states,
529
+ key_states,
530
+ value_states,
531
+ cu_seqlens_q=cu_seqlens_q,
532
+ cu_seqlens_k=cu_seqlens_k,
533
+ max_seqlen_q=max_seqlen_in_batch_q,
534
+ max_seqlen_k=max_seqlen_in_batch_k,
535
+ dropout_p=dropout,
536
+ softmax_scale=softmax_scale,
537
+ causal=causal,
538
+ window_size=(self.config.sliding_window, self.config.sliding_window),
539
+ )
540
+
541
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
542
+ else:
543
+ if not use_sliding_windows:
544
+ attn_output = flash_attn_func(
545
+ query_states,
546
+ key_states,
547
+ value_states,
548
+ dropout,
549
+ softmax_scale=softmax_scale,
550
+ causal=causal,
551
+ )
552
+ else:
553
+ attn_output = flash_attn_func(
554
+ query_states,
555
+ key_states,
556
+ value_states,
557
+ dropout,
558
+ softmax_scale=softmax_scale,
559
+ causal=causal,
560
+ window_size=(self.config.sliding_window, self.config.sliding_window),
561
+ )
562
+
563
+ return attn_output
564
+
565
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
566
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
567
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
568
+
569
+ # On the first iteration we need to properly re-create the padding mask
570
+ # by slicing it on the proper place
571
+ if kv_seq_len != attention_mask.shape[-1]:
572
+ attention_mask_num_tokens = attention_mask.shape[-1]
573
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
574
+
575
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
576
+
577
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
578
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
579
+
580
+ if query_length == kv_seq_len:
581
+ query_layer = index_first_axis(
582
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
583
+ )
584
+ cu_seqlens_q = cu_seqlens_k
585
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
586
+ indices_q = indices_k
587
+ elif query_length == 1:
588
+ max_seqlen_in_batch_q = 1
589
+ cu_seqlens_q = torch.arange(
590
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
591
+ ) # There is a memcpy here, that is very bad.
592
+ indices_q = cu_seqlens_q[:-1]
593
+ query_layer = query_layer.squeeze(1)
594
+ else:
595
+ # The -q_len: slice assumes left padding.
596
+ attention_mask = attention_mask[:, -query_length:]
597
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
598
+
599
+ return (
600
+ query_layer,
601
+ key_layer,
602
+ value_layer,
603
+ indices_q,
604
+ (cu_seqlens_q, cu_seqlens_k),
605
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
606
+ )
607
+
608
+
609
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Qwen2
610
+ class Qwen2SdpaAttention(Qwen2Attention):
611
+ """
612
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
613
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
614
+ SDPA API.
615
+ """
616
+
617
+ # Adapted from Qwen2Attention.forward
618
+ def forward(
619
+ self,
620
+ hidden_states: torch.Tensor,
621
+ attention_mask: Optional[torch.Tensor] = None,
622
+ position_ids: Optional[torch.LongTensor] = None,
623
+ past_key_value: Optional[Cache] = None,
624
+ output_attentions: bool = False,
625
+ use_cache: bool = False,
626
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
627
+ if output_attentions:
628
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
629
+ logger.warning_once(
630
+ "Qwen2Model is using Qwen2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
631
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
632
+ )
633
+ return super().forward(
634
+ hidden_states=hidden_states,
635
+ attention_mask=attention_mask,
636
+ position_ids=position_ids,
637
+ past_key_value=past_key_value,
638
+ output_attentions=output_attentions,
639
+ use_cache=use_cache,
640
+ )
641
+
642
+ bsz, q_len, _ = hidden_states.size()
643
+
644
+ query_states = self.q_proj(hidden_states)
645
+ key_states = self.k_proj(hidden_states)
646
+ value_states = self.v_proj(hidden_states)
647
+
648
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
649
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
650
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
651
+
652
+ kv_seq_len = key_states.shape[-2]
653
+ if past_key_value is not None:
654
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
655
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
656
+
657
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
658
+
659
+ if past_key_value is not None:
660
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
661
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
662
+
663
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
664
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
665
+
666
+ if attention_mask is not None:
667
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
668
+ raise ValueError(
669
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
670
+ )
671
+
672
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
673
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
674
+ if query_states.device.type == "cuda" and attention_mask is not None:
675
+ query_states = query_states.contiguous()
676
+ key_states = key_states.contiguous()
677
+ value_states = value_states.contiguous()
678
+
679
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
680
+ query_states,
681
+ key_states,
682
+ value_states,
683
+ attn_mask=attention_mask,
684
+ dropout_p=self.attention_dropout if self.training else 0.0,
685
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
686
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
687
+ )
688
+
689
+ attn_output = attn_output.transpose(1, 2).contiguous()
690
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
691
+
692
+ attn_output = self.o_proj(attn_output)
693
+
694
+ return attn_output, None, past_key_value
695
+
696
+
697
+ QWEN2_ATTENTION_CLASSES = {
698
+ "eager": Qwen2Attention,
699
+ "flash_attention_2": Qwen2FlashAttention2,
700
+ "sdpa": Qwen2SdpaAttention,
701
+ }
702
+
703
+
704
+ class Qwen2DecoderLayer(nn.Module):
705
+ def __init__(self, config: Qwen2Config, layer_idx: int):
706
+ super().__init__()
707
+ self.hidden_size = config.hidden_size
708
+
709
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
710
+ logger.warning_once(
711
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
712
+ "unexpected results may be encountered."
713
+ )
714
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
715
+
716
+ self.mlp = Qwen2MLP(config)
717
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
718
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
719
+
720
+ def forward(
721
+ self,
722
+ hidden_states: torch.Tensor,
723
+ attention_mask: Optional[torch.Tensor] = None,
724
+ position_ids: Optional[torch.LongTensor] = None,
725
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
726
+ output_attentions: Optional[bool] = False,
727
+ use_cache: Optional[bool] = False,
728
+ **kwargs,
729
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
730
+ if "padding_mask" in kwargs:
731
+ warnings.warn(
732
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
733
+ "Please make sure use `attention_mask` instead.`"
734
+ )
735
+ """
736
+ Args:
737
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
738
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
739
+ `(batch, sequence_length)` where padding elements are indicated by 0.
740
+ output_attentions (`bool`, *optional*):
741
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
742
+ returned tensors for more detail.
743
+ use_cache (`bool`, *optional*):
744
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
745
+ (see `past_key_values`).
746
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
747
+ """
748
+
749
+ residual = hidden_states
750
+
751
+ hidden_states = self.input_layernorm(hidden_states)
752
+
753
+ # Self Attention
754
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
755
+ hidden_states=hidden_states,
756
+ attention_mask=attention_mask,
757
+ position_ids=position_ids,
758
+ past_key_value=past_key_value,
759
+ output_attentions=output_attentions,
760
+ use_cache=use_cache,
761
+ )
762
+ hidden_states = residual + hidden_states
763
+
764
+ # Fully Connected
765
+ residual = hidden_states
766
+ hidden_states = self.post_attention_layernorm(hidden_states)
767
+ hidden_states = self.mlp(hidden_states)
768
+ hidden_states = residual + hidden_states
769
+
770
+ outputs = (hidden_states,)
771
+
772
+ if output_attentions:
773
+ outputs += (self_attn_weights,)
774
+
775
+ if use_cache:
776
+ outputs += (present_key_value,)
777
+
778
+ return outputs
779
+
780
+
781
+ QWEN2_START_DOCSTRING = r"""
782
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
783
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
784
+ etc.)
785
+
786
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
787
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
788
+ and behavior.
789
+
790
+ Parameters:
791
+ config ([`Qwen2Config`]):
792
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
793
+ load the weights associated with the model, only the configuration. Check out the
794
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
795
+ """
796
+
797
+
798
+ @add_start_docstrings(
799
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
800
+ QWEN2_START_DOCSTRING,
801
+ )
802
+ class Qwen2PreTrainedModel(PreTrainedModel):
803
+ config_class = Qwen2Config
804
+ base_model_prefix = "model"
805
+ supports_gradient_checkpointing = True
806
+ _no_split_modules = ["Qwen2DecoderLayer"]
807
+ _skip_keys_device_placement = "past_key_values"
808
+ _supports_flash_attn_2 = True
809
+ _supports_sdpa = True
810
+ _supports_cache_class = True
811
+
812
+ def _init_weights(self, module):
813
+ std = self.config.initializer_range
814
+ if isinstance(module, nn.Linear):
815
+ module.weight.data.normal_(mean=0.0, std=std)
816
+ if module.bias is not None:
817
+ module.bias.data.zero_()
818
+ elif isinstance(module, nn.Embedding):
819
+ module.weight.data.normal_(mean=0.0, std=std)
820
+ if module.padding_idx is not None:
821
+ module.weight.data[module.padding_idx].zero_()
822
+
823
+ def _set_gradient_checkpointing(self, module, value=False):
824
+ if isinstance(module, Qwen2Model):
825
+ module.gradient_checkpointing = value
826
+
827
+
828
+ QWEN2_INPUTS_DOCSTRING = r"""
829
+ Args:
830
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
831
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
832
+ it.
833
+
834
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
835
+ [`PreTrainedTokenizer.__call__`] for details.
836
+
837
+ [What are input IDs?](../glossary#input-ids)
838
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
839
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
840
+
841
+ - 1 for tokens that are **not masked**,
842
+ - 0 for tokens that are **masked**.
843
+
844
+ [What are attention masks?](../glossary#attention-mask)
845
+
846
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
847
+ [`PreTrainedTokenizer.__call__`] for details.
848
+
849
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
850
+ `past_key_values`).
851
+
852
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
853
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
854
+ information on the default strategy.
855
+
856
+ - 1 indicates the head is **not masked**,
857
+ - 0 indicates the head is **masked**.
858
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
859
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
860
+ config.n_positions - 1]`.
861
+
862
+ [What are position IDs?](../glossary#position-ids)
863
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
864
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
865
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
866
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
867
+
868
+ Two formats are allowed:
869
+ - a [`~cache_utils.Cache`] instance;
870
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
871
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
872
+ cache format.
873
+
874
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
875
+ legacy cache format will be returned.
876
+
877
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
878
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
879
+ of shape `(batch_size, sequence_length)`.
880
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
881
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
882
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
883
+ model's internal embedding lookup matrix.
884
+ use_cache (`bool`, *optional*):
885
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
886
+ `past_key_values`).
887
+ output_attentions (`bool`, *optional*):
888
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
889
+ tensors for more detail.
890
+ output_hidden_states (`bool`, *optional*):
891
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
892
+ more detail.
893
+ return_dict (`bool`, *optional*):
894
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
895
+ """
896
+
897
+ @add_start_docstrings(
898
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
899
+ QWEN2_START_DOCSTRING,
900
+ )
901
+ class Qwen2Model(Qwen2PreTrainedModel):
902
+ """
903
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
904
+
905
+ Args:
906
+ config: Qwen2Config
907
+ """
908
+
909
+ def __init__(self, config: Qwen2Config):
910
+ super().__init__(config)
911
+ self.padding_idx = config.pad_token_id
912
+ self.vocab_size = config.vocab_size
913
+
914
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
915
+ self.layers = nn.ModuleList(
916
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
917
+ )
918
+ self._attn_implementation = config._attn_implementation
919
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
920
+
921
+ self.gradient_checkpointing = False
922
+ # Initialize weights and apply final processing
923
+ self.post_init()
924
+
925
+ def get_input_embeddings(self):
926
+ return self.embed_tokens
927
+
928
+ def set_input_embeddings(self, value):
929
+ self.embed_tokens = value
930
+
931
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
932
+ def forward(
933
+ self,
934
+ input_ids: torch.LongTensor = None,
935
+ attention_mask: Optional[torch.Tensor] = None,
936
+ position_ids: Optional[torch.LongTensor] = None,
937
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
938
+ inputs_embeds: Optional[torch.FloatTensor] = None,
939
+ use_cache: Optional[bool] = None,
940
+ output_attentions: Optional[bool] = None,
941
+ output_hidden_states: Optional[bool] = None,
942
+ return_dict: Optional[bool] = None,
943
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
944
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
945
+ output_hidden_states = (
946
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
947
+ )
948
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
949
+
950
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
951
+
952
+ # retrieve input_ids and inputs_embeds
953
+ if input_ids is not None and inputs_embeds is not None:
954
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
955
+ elif input_ids is not None:
956
+ batch_size, seq_length = input_ids.shape
957
+ elif inputs_embeds is not None:
958
+ batch_size, seq_length, _ = inputs_embeds.shape
959
+ else:
960
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
961
+
962
+ if self.gradient_checkpointing and self.training:
963
+ if use_cache:
964
+ logger.warning_once(
965
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
966
+ )
967
+ use_cache = False
968
+
969
+ past_key_values_length = 0
970
+
971
+ if use_cache:
972
+ use_legacy_cache = not isinstance(past_key_values, Cache)
973
+ if use_legacy_cache:
974
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
975
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
976
+
977
+ if position_ids is None:
978
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
979
+ position_ids = torch.arange(
980
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
981
+ )
982
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
983
+ else:
984
+ position_ids = position_ids.view(-1, seq_length).long()
985
+
986
+ if inputs_embeds is None:
987
+ inputs_embeds = self.embed_tokens(input_ids)
988
+
989
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
990
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
991
+ if is_padding_right:
992
+ raise ValueError(
993
+ "You are attempting to perform batched generation with padding_side='right'"
994
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
995
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
996
+ )
997
+
998
+ if self._attn_implementation == "flash_attention_2":
999
+ # 2d mask is passed through the layers
1000
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1001
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1002
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1003
+ # the manual implementation that requires a 4D causal mask in all cases.
1004
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1005
+ attention_mask,
1006
+ (batch_size, seq_length),
1007
+ inputs_embeds,
1008
+ past_key_values_length,
1009
+ )
1010
+ else:
1011
+ attention_mask = _prepare_4d_causal_attention_mask(
1012
+ attention_mask,
1013
+ (batch_size, seq_length),
1014
+ inputs_embeds,
1015
+ past_key_values_length,
1016
+ sliding_window=self.config.sliding_window,
1017
+ )
1018
+
1019
+ hidden_states = inputs_embeds
1020
+
1021
+ # decoder layers
1022
+ all_hidden_states = () if output_hidden_states else None
1023
+ all_self_attns = () if output_attentions else None
1024
+ next_decoder_cache = None
1025
+
1026
+ for decoder_layer in self.layers:
1027
+ if output_hidden_states:
1028
+ all_hidden_states += (hidden_states,)
1029
+
1030
+ if self.gradient_checkpointing and self.training:
1031
+ # layer_outputs = self._gradient_checkpointing_func(
1032
+ # decoder_layer.__call__,
1033
+ # hidden_states,
1034
+ # attention_mask,
1035
+ # position_ids,
1036
+ # past_key_values,
1037
+ # output_attentions,
1038
+ # use_cache,
1039
+ # )
1040
+ def create_custom_forward(module):
1041
+ def custom_forward(*inputs):
1042
+ # None for past_key_value
1043
+ return module(*inputs)
1044
+
1045
+ return custom_forward
1046
+
1047
+ layer_outputs = torch.utils.checkpoint.checkpoint(
1048
+ create_custom_forward(decoder_layer),
1049
+ hidden_states,
1050
+ attention_mask,
1051
+ position_ids,
1052
+ past_key_values,
1053
+ output_attentions,
1054
+ use_cache,
1055
+ )
1056
+ else:
1057
+ layer_outputs = decoder_layer(
1058
+ hidden_states,
1059
+ attention_mask=attention_mask,
1060
+ position_ids=position_ids,
1061
+ past_key_value=past_key_values,
1062
+ output_attentions=output_attentions,
1063
+ use_cache=use_cache,
1064
+ )
1065
+
1066
+ hidden_states = layer_outputs[0]
1067
+
1068
+ if use_cache:
1069
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1070
+
1071
+ if output_attentions:
1072
+ all_self_attns += (layer_outputs[1],)
1073
+
1074
+ hidden_states = self.norm(hidden_states)
1075
+
1076
+ # add hidden states from the last decoder layer
1077
+ if output_hidden_states:
1078
+ all_hidden_states += (hidden_states,)
1079
+
1080
+ next_cache = None
1081
+ if use_cache:
1082
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1083
+
1084
+ if not return_dict:
1085
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1086
+ return BaseModelOutputWithPast(
1087
+ last_hidden_state=hidden_states,
1088
+ past_key_values=next_cache,
1089
+ hidden_states=all_hidden_states,
1090
+ attentions=all_self_attns,
1091
+ )
1092
+
1093
+
1094
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel):
1095
+ _tied_weights_keys = ["lm_head.weight"]
1096
+
1097
+ def __init__(self, config):
1098
+ super().__init__(config)
1099
+ self.model = Qwen2Model(config)
1100
+ self.vocab_size = config.vocab_size
1101
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1102
+ self.gradient_checkpointing = False
1103
+
1104
+ # Initialize weights and apply final processing
1105
+ self.post_init()
1106
+
1107
+ def get_input_embeddings(self):
1108
+ return self.model.embed_tokens
1109
+
1110
+ def set_input_embeddings(self, value):
1111
+ self.model.embed_tokens = value
1112
+
1113
+ def get_output_embeddings(self):
1114
+ return self.lm_head
1115
+
1116
+ def set_output_embeddings(self, new_embeddings):
1117
+ self.lm_head = new_embeddings
1118
+
1119
+ def set_decoder(self, decoder):
1120
+ self.model = decoder
1121
+
1122
+ def get_decoder(self):
1123
+ return self.model
1124
+
1125
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1126
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1127
+ def forward(
1128
+ self,
1129
+ input_ids: torch.LongTensor = None,
1130
+ attention_mask: Optional[torch.Tensor] = None,
1131
+ position_ids: Optional[torch.LongTensor] = None,
1132
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1133
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1134
+ labels: Optional[torch.LongTensor] = None,
1135
+ use_cache: Optional[bool] = None,
1136
+ output_attentions: Optional[bool] = None,
1137
+ output_hidden_states: Optional[bool] = None,
1138
+ return_dict: Optional[bool] = None,
1139
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1140
+ r"""
1141
+ Args:
1142
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1143
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1144
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1145
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1146
+
1147
+ Returns:
1148
+
1149
+ Example:
1150
+
1151
+ ```python
1152
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1153
+
1154
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1155
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1156
+
1157
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1158
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1159
+
1160
+ >>> # Generate
1161
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1162
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1163
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1164
+ ```"""
1165
+
1166
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1167
+ output_hidden_states = (
1168
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1169
+ )
1170
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1171
+
1172
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1173
+ outputs = self.model(
1174
+ input_ids=input_ids,
1175
+ attention_mask=attention_mask,
1176
+ position_ids=position_ids,
1177
+ past_key_values=past_key_values,
1178
+ inputs_embeds=inputs_embeds,
1179
+ use_cache=use_cache,
1180
+ output_attentions=output_attentions,
1181
+ output_hidden_states=output_hidden_states,
1182
+ return_dict=return_dict,
1183
+ )
1184
+
1185
+ hidden_states = outputs[0]
1186
+ if self.gradient_checkpointing and self.training:
1187
+ def create_custom_forward(module):
1188
+ def custom_forward(*inputs):
1189
+ # None for past_key_value
1190
+ return module(*inputs)
1191
+ return custom_forward
1192
+
1193
+ logits = torch.utils.checkpoint.checkpoint(
1194
+ create_custom_forward(self.lm_head),
1195
+ hidden_states
1196
+ )
1197
+ else:
1198
+ logits = self.lm_head(hidden_states)
1199
+ # logits = logits.float()
1200
+
1201
+ loss = None
1202
+ if labels is not None:
1203
+ # Shift so that tokens < n predict n
1204
+ shift_logits = logits[..., :-1, :].contiguous()
1205
+ shift_labels = labels[..., 1:].contiguous()
1206
+ # Flatten the tokens
1207
+ loss_fct = CrossEntropyLoss()
1208
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1209
+ shift_labels = shift_labels.view(-1)
1210
+ # Enable model parallelism
1211
+ shift_labels = shift_labels.to(shift_logits.device)
1212
+ if self.gradient_checkpointing and self.training:
1213
+ def create_custom_forward(module):
1214
+ def custom_forward(*inputs):
1215
+ # inputs = (inputs[0].float(), *inputs[1:])
1216
+ return module(*inputs)
1217
+
1218
+ return custom_forward
1219
+ loss = torch.utils.checkpoint.checkpoint(
1220
+ create_custom_forward(loss_fct),
1221
+ shift_logits,
1222
+ shift_labels
1223
+ )
1224
+ else:
1225
+ loss = loss_fct(shift_logits, shift_labels)
1226
+ # loss = loss_fct(shift_logits, shift_labels)
1227
+
1228
+ if not return_dict:
1229
+ output = (logits,) + outputs[1:]
1230
+ return (loss,) + output if loss is not None else output
1231
+
1232
+ return CausalLMOutputWithPast(
1233
+ loss=loss,
1234
+ logits=logits,
1235
+ past_key_values=outputs.past_key_values,
1236
+ hidden_states=outputs.hidden_states,
1237
+ attentions=outputs.attentions,
1238
+ )
1239
+
1240
+ def prepare_inputs_for_generation(
1241
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1242
+ ):
1243
+ # Omit tokens covered by past_key_values
1244
+ if past_key_values is not None:
1245
+ if isinstance(past_key_values, Cache):
1246
+ cache_length = past_key_values.get_seq_length()
1247
+ past_length = past_key_values.seen_tokens
1248
+ max_cache_length = past_key_values.get_max_length()
1249
+ else:
1250
+ cache_length = past_length = past_key_values[0][0].shape[2]
1251
+ max_cache_length = None
1252
+
1253
+ # Keep only the unprocessed tokens:
1254
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1255
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1256
+ # input)
1257
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1258
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1259
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1260
+ # input_ids based on the past_length.
1261
+ elif past_length < input_ids.shape[1]:
1262
+ input_ids = input_ids[:, past_length:]
1263
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1264
+
1265
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1266
+ if (
1267
+ max_cache_length is not None
1268
+ and attention_mask is not None
1269
+ and cache_length + input_ids.shape[1] > max_cache_length
1270
+ ):
1271
+ attention_mask = attention_mask[:, -max_cache_length:]
1272
+
1273
+ position_ids = kwargs.get("position_ids", None)
1274
+ if attention_mask is not None and position_ids is None:
1275
+ # create position_ids on the fly for batch generation
1276
+ position_ids = attention_mask.long().cumsum(-1) - 1
1277
+ position_ids.masked_fill_(attention_mask == 0, 1)
1278
+ if past_key_values:
1279
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1280
+
1281
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1282
+ if inputs_embeds is not None and past_key_values is None:
1283
+ model_inputs = {"inputs_embeds": inputs_embeds}
1284
+ else:
1285
+ model_inputs = {"input_ids": input_ids}
1286
+
1287
+ model_inputs.update(
1288
+ {
1289
+ "position_ids": position_ids,
1290
+ "past_key_values": past_key_values,
1291
+ "use_cache": kwargs.get("use_cache"),
1292
+ "attention_mask": attention_mask,
1293
+ }
1294
+ )
1295
+ return model_inputs
1296
+
1297
+ @staticmethod
1298
+ def _reorder_cache(past_key_values, beam_idx):
1299
+ reordered_past = ()
1300
+ for layer_past in past_key_values:
1301
+ reordered_past += (
1302
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1303
+ )
1304
+ return reordered_past
1305
+
1306
+ class IdentityMap(nn.Module):
1307
+ def __init__(self):
1308
+ super().__init__()
1309
+
1310
+ def forward(self, x, *args, **kwargs):
1311
+ return x
1312
+
1313
+ @property
1314
+ def config(self):
1315
+ return {"mm_projector_type": 'identity'}
1316
+
1317
+ class LlavaMetaModel:
1318
+
1319
+ def __init__(self, config):
1320
+ super(LlavaMetaModel, self).__init__(config)
1321
+
1322
+ if hasattr(config, "mm_vision_tower"):
1323
+ self.vision_tower = self.build_vision_tower(config.vision_tower_cfg)
1324
+ self.mm_projector = self.build_vision_projector(config)
1325
+ # hack
1326
+ # [Edited by zhenwei - 2024-02-02 20:36]
1327
+ is_meta = getattr(nn.Linear(1, 1, bias=False).weight, 'is_meta', False)
1328
+ if is_meta:
1329
+ fake_dict = {}
1330
+ for n, p in self.mm_projector.named_parameters():
1331
+ fake_dict[n] = torch.zeros_like(p, device='cpu')
1332
+ from transformers.modeling_utils import _load_state_dict_into_meta_model
1333
+ _load_state_dict_into_meta_model(
1334
+ self.mm_projector,
1335
+ fake_dict,
1336
+ fake_dict.keys(), # left for now but could be removed, see below
1337
+ '',
1338
+ fake_dict.keys(),
1339
+ )
1340
+ self.mm_projector.to('cuda' if torch.cuda.is_available() else 'cpu')
1341
+
1342
+ def get_vision_tower(self):
1343
+ vision_tower = getattr(self, 'vision_tower', None)
1344
+ if type(vision_tower) is list:
1345
+ vision_tower = vision_tower[0]
1346
+ return vision_tower
1347
+
1348
+ def build_vision_tower(self,vision_tower_cfg):
1349
+ return VisionTower(vision_tower_cfg)
1350
+
1351
+ def build_vision_projector(self,config):
1352
+ projector_type = getattr(config, 'mm_projector_type', 'linear')
1353
+
1354
+ if projector_type == 'linear':
1355
+ return nn.Linear(config.mm_hidden_size, config.hidden_size)
1356
+
1357
+ mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
1358
+ if mlp_gelu_match:
1359
+ mlp_depth = int(mlp_gelu_match.group(1))
1360
+ modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
1361
+ for _ in range(1, mlp_depth):
1362
+ modules.append(nn.GELU())
1363
+ modules.append(nn.Linear(config.hidden_size, config.hidden_size))
1364
+ return nn.Sequential(*modules)
1365
+
1366
+ if projector_type == 'identity':
1367
+ return IdentityMap()
1368
+
1369
+ raise ValueError(f'Unknown projector type: {projector_type}')
1370
+
1371
+ def initialize_vision_modules(self, model_args, fsdp=None):
1372
+ vision_tower = model_args.vision_tower
1373
+ mm_vision_select_layer = model_args.mm_vision_select_layer
1374
+ mm_vision_select_feature = model_args.mm_vision_select_feature
1375
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
1376
+
1377
+ self.config.mm_vision_tower = vision_tower
1378
+
1379
+ if self.get_vision_tower() is None:
1380
+ vision_tower = build_vision_tower(model_args)
1381
+
1382
+ if fsdp is not None and len(fsdp) > 0:
1383
+ self.vision_tower = [vision_tower]
1384
+ else:
1385
+ self.vision_tower = vision_tower
1386
+ else:
1387
+ if fsdp is not None and len(fsdp) > 0:
1388
+ vision_tower = self.vision_tower[0]
1389
+ else:
1390
+ vision_tower = self.vision_tower
1391
+ vision_tower.load_model()
1392
+
1393
+ self.config.use_mm_proj = True
1394
+ self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
1395
+ self.config.mm_hidden_size = vision_tower.hidden_size
1396
+ self.config.mm_vision_select_layer = mm_vision_select_layer
1397
+ self.config.mm_vision_select_feature = mm_vision_select_feature
1398
+
1399
+ if getattr(self, 'mm_projector', None) is None:
1400
+ self.mm_projector = build_vision_projector(self.config)
1401
+ else:
1402
+ # In case it is frozen by LoRA
1403
+ for p in self.mm_projector.parameters():
1404
+ p.requires_grad = True
1405
+ # param_0 = list(self.mm_projector.parameters())[0]
1406
+ # def backward_hook(grad):
1407
+ # global ix
1408
+ # if ix % 100 == 0:
1409
+ # mean = torch.mean(grad).item()
1410
+ # std = torch.std(grad).item()
1411
+ # # print(f'[{ix}], mean: {mean}, std: {std}', file=debug_file, flush=True)
1412
+ # print(f'[{ix}], mean: {mean}, std: {std}', flush=True)
1413
+ # ix += 1
1414
+ # return grad
1415
+ # param_0.register_hook(backward_hook)
1416
+ if pretrain_mm_mlp_adapter is not None:
1417
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
1418
+ def get_w(weights, keyword):
1419
+ return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
1420
+
1421
+ self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
1422
+
1423
+ class LlavaMetaForCausalLM(ABC):
1424
+
1425
+ def init_constants(self, config):
1426
+ self.IGNORE_INDEX = getattr(config, 'ignore_index', -100)
1427
+ self.IMAGE_TOKEN_INDEX = getattr(config, 'image_token_index', 151646)
1428
+ self.DEFAULT_IMAGE_TOKEN = getattr(config, 'image_token', "<image>")
1429
+
1430
+
1431
+ @abstractmethod
1432
+ def get_model(self):
1433
+ pass
1434
+
1435
+ def get_vision_tower(self):
1436
+ return self.get_model().get_vision_tower()
1437
+
1438
+ def encode_images(self, images):
1439
+ image_features = self.get_model().get_vision_tower()(images)
1440
+ # image_features.requires_grad_(True)
1441
+ image_features = self.get_model().mm_projector(image_features)
1442
+ return image_features
1443
+
1444
+ def prepare_inputs_labels_for_multimodal(
1445
+ self, input_ids, position_ids, attention_mask, past_key_values, labels, images
1446
+ ):
1447
+ vision_tower = self.get_vision_tower()
1448
+ if past_key_values is not None:
1449
+ target_shape = past_key_values[0][0].shape[2] + 1
1450
+ attention_mask = torch.ones(
1451
+ (attention_mask.shape[0], target_shape),
1452
+ dtype=attention_mask.dtype,
1453
+ device=attention_mask.device
1454
+ )
1455
+ position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
1456
+ return input_ids[:, -1:], position_ids, attention_mask, past_key_values, None, labels
1457
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
1458
+ # if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1:
1459
+ # target_shape = past_key_values.seqlen_offset + 1
1460
+ # attention_mask = torch.cat((attention_mask, torch.ones(
1461
+ # (attention_mask.shape[0], target_shape - attention_mask.shape[1]),
1462
+ # dtype=attention_mask.dtype,
1463
+ # device=attention_mask.device
1464
+ # )), dim=1)
1465
+ # position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
1466
+ return input_ids, None, None, past_key_values, None, None
1467
+ # return input_ids, position_ids, attention_mask, past_key_values, None, labels
1468
+
1469
+ if type(images) is list or images.ndim == 5:
1470
+ concat_images = torch.cat([image for image in images], dim=0)
1471
+ # concat_images.requires_grad_(True)
1472
+ image_features = self.encode_images(concat_images)
1473
+ split_sizes = [image.shape[0] for image in images]
1474
+ image_features = torch.split(image_features, split_sizes, dim=0)
1475
+ image_features = [x.flatten(0, 1).to(self.device) for x in image_features]
1476
+ else:
1477
+ # images.requires_grad_(True)
1478
+ image_features = self.encode_images(images).to(self.device)
1479
+
1480
+ # TODO: image start / end is not implemented here to support pretraining.
1481
+ if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
1482
+ raise NotImplementedError
1483
+
1484
+ # Let's just add dummy tensors if they do not exist,
1485
+ # it is a headache to deal with None all the time.
1486
+ # But it is not ideal, and if you have a better idea,
1487
+ # please open an issue / submit a PR, thanks.
1488
+ _labels = labels
1489
+ _position_ids = position_ids
1490
+ _attention_mask = attention_mask
1491
+ if attention_mask is None:
1492
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
1493
+ else:
1494
+ attention_mask = attention_mask.bool()
1495
+ if position_ids is None:
1496
+ position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
1497
+ if labels is None:
1498
+ labels = torch.full_like(input_ids, self.IGNORE_INDEX)
1499
+
1500
+ # remove the padding using attention_mask -- TODO: double check
1501
+ input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
1502
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
1503
+
1504
+ new_input_embeds = []
1505
+ new_labels = []
1506
+ cur_image_idx = 0
1507
+ for batch_idx, cur_input_ids in enumerate(input_ids):
1508
+ num_images = (cur_input_ids == self.IMAGE_TOKEN_INDEX).sum()
1509
+ if num_images == 0:
1510
+ cur_image_features = image_features[cur_image_idx]
1511
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
1512
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
1513
+ new_input_embeds.append(cur_input_embeds)
1514
+ new_labels.append(labels[batch_idx])
1515
+ cur_image_idx += 1
1516
+ continue
1517
+
1518
+ image_token_indices = [-1] + torch.where(cur_input_ids == self.IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
1519
+ cur_input_ids_noim = []
1520
+ cur_labels = labels[batch_idx]
1521
+ cur_labels_noim = []
1522
+ for i in range(len(image_token_indices) - 1):
1523
+ cur_input_ids_noim.append(cur_input_ids[image_token_indices[i]+1:image_token_indices[i+1]])
1524
+ cur_labels_noim.append(cur_labels[image_token_indices[i]+1:image_token_indices[i+1]])
1525
+ split_sizes = [x.shape[0] for x in cur_labels_noim]
1526
+ cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
1527
+ cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
1528
+ cur_new_input_embeds = []
1529
+ cur_new_labels = []
1530
+
1531
+ for i in range(num_images + 1):
1532
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
1533
+ cur_new_labels.append(cur_labels_noim[i])
1534
+ if i < num_images:
1535
+ cur_image_features = image_features[cur_image_idx]
1536
+ cur_image_idx += 1
1537
+ cur_new_input_embeds.append(cur_image_features)
1538
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), self.IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
1539
+
1540
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
1541
+ cur_new_labels = torch.cat(cur_new_labels)
1542
+
1543
+ new_input_embeds.append(cur_new_input_embeds)
1544
+ new_labels.append(cur_new_labels)
1545
+
1546
+ # Truncate sequences to max length as image embeddings can make the sequence longer
1547
+ tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None)
1548
+ if tokenizer_model_max_length is not None:
1549
+ new_input_embeds = [x[:tokenizer_model_max_length] for x in new_input_embeds]
1550
+ new_labels = [x[:tokenizer_model_max_length] for x in new_labels]
1551
+ # Combine them
1552
+ max_len = max(x.shape[0] for x in new_input_embeds)
1553
+ batch_size = len(new_input_embeds)
1554
+
1555
+ new_input_embeds_padded = []
1556
+ new_labels_padded = torch.full((batch_size, max_len), self.IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
1557
+ attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
1558
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
1559
+
1560
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
1561
+ cur_len = cur_new_embed.shape[0]
1562
+ if getattr(self.config, 'tokenizer_padding_side', 'right') == "left":
1563
+ new_input_embeds_padded.append(torch.cat((
1564
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device),
1565
+ cur_new_embed
1566
+ ), dim=0))
1567
+ if cur_len > 0:
1568
+ new_labels_padded[i, -cur_len:] = cur_new_labels
1569
+ attention_mask[i, -cur_len:] = True
1570
+ position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
1571
+ else:
1572
+ new_input_embeds_padded.append(torch.cat((
1573
+ cur_new_embed,
1574
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)
1575
+ ), dim=0))
1576
+ if cur_len > 0:
1577
+ new_labels_padded[i, :cur_len] = cur_new_labels
1578
+ attention_mask[i, :cur_len] = True
1579
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
1580
+
1581
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
1582
+ # logger.info(f"shape of new_input_embeds: {new_input_embeds.shape}")
1583
+
1584
+ if _labels is None:
1585
+ new_labels = None
1586
+ else:
1587
+ new_labels = new_labels_padded
1588
+
1589
+ if _attention_mask is None:
1590
+ attention_mask = None
1591
+ else:
1592
+ attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
1593
+
1594
+ if _position_ids is None:
1595
+ position_ids = None
1596
+
1597
+ return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
1598
+
1599
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
1600
+ if model_args.mm_use_im_patch_token:
1601
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
1602
+ self.resize_token_embeddings(len(tokenizer))
1603
+
1604
+ if model_args.mm_use_im_start_end:
1605
+ num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
1606
+ self.resize_token_embeddings(len(tokenizer))
1607
+
1608
+ if num_new_tokens > 0:
1609
+ input_embeddings = self.get_input_embeddings().weight.data
1610
+ output_embeddings = self.get_output_embeddings().weight.data
1611
+
1612
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
1613
+ dim=0, keepdim=True)
1614
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
1615
+ dim=0, keepdim=True)
1616
+
1617
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
1618
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
1619
+
1620
+ if model_args.tune_mm_mlp_adapter:
1621
+ for p in self.get_input_embeddings().parameters():
1622
+ p.requires_grad = True
1623
+ for p in self.get_output_embeddings().parameters():
1624
+ p.requires_grad = False
1625
+
1626
+ if model_args.pretrain_mm_mlp_adapter:
1627
+ mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location='cpu')
1628
+ embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight']
1629
+ assert num_new_tokens == 2
1630
+ if input_embeddings.shape == embed_tokens_weight.shape:
1631
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
1632
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
1633
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
1634
+ else:
1635
+ raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
1636
+ elif model_args.mm_use_im_patch_token:
1637
+ if model_args.tune_mm_mlp_adapter:
1638
+ for p in self.get_input_embeddings().parameters():
1639
+ p.requires_grad = False
1640
+ for p in self.get_output_embeddings().parameters():
1641
+ p.requires_grad = False
1642
+
1643
+
1644
+ class ImpQwen2Model(LlavaMetaModel, Qwen2Model):
1645
+ config_class = ImpQwen2Config
1646
+
1647
+ def __init__(self, config: ImpQwen2Config):
1648
+ super(ImpQwen2Model, self).__init__(config)
1649
+
1650
+ class ImpQwen2ForCausalLM(Qwen2ForCausalLM, LlavaMetaForCausalLM):
1651
+ config_class = ImpQwen2Config
1652
+
1653
+ def __init__(self, config):
1654
+ super(ImpQwen2ForCausalLM, self).__init__(config)
1655
+ self.model = ImpQwen2Model(config)
1656
+ self.vocab_size = config.vocab_size
1657
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1658
+ self.need_clear_cache = False
1659
+
1660
+ self.post_init()
1661
+ self.init_constants(config)
1662
+
1663
+ def get_model(self):
1664
+ return self.model
1665
+
1666
+ def image_preprocess(self, images):
1667
+ return self.get_vision_tower().image_processor(images)['pixel_values']
1668
+
1669
+
1670
+ def forward(
1671
+ self,
1672
+ input_ids: torch.LongTensor = None,
1673
+ attention_mask: Optional[torch.Tensor] = None,
1674
+ position_ids: Optional[torch.LongTensor] = None,
1675
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1676
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1677
+ labels: Optional[torch.LongTensor] = None,
1678
+ use_cache: Optional[bool] = None,
1679
+ output_attentions: Optional[bool] = None,
1680
+ output_hidden_states: Optional[bool] = None,
1681
+ images: Optional[torch.FloatTensor] = None,
1682
+ return_dict: Optional[bool] = None,
1683
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1684
+
1685
+ if inputs_embeds is None:
1686
+ (
1687
+ input_ids,
1688
+ position_ids,
1689
+ attention_mask,
1690
+ past_key_values,
1691
+ inputs_embeds,
1692
+ labels
1693
+ ) = self.prepare_inputs_labels_for_multimodal(
1694
+ input_ids,
1695
+ position_ids,
1696
+ attention_mask,
1697
+ past_key_values,
1698
+ labels,
1699
+ images
1700
+ )
1701
+ return super().forward(
1702
+ input_ids=input_ids,
1703
+ attention_mask=attention_mask,
1704
+ position_ids=position_ids,
1705
+ past_key_values=past_key_values,
1706
+ inputs_embeds=inputs_embeds,
1707
+ labels=labels,
1708
+ use_cache=use_cache,
1709
+ output_attentions=output_attentions,
1710
+ output_hidden_states=output_hidden_states,
1711
+ return_dict=return_dict
1712
+ )
1713
+
1714
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
1715
+ images = kwargs.pop("images", None)
1716
+ _inputs = super().prepare_inputs_for_generation(
1717
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
1718
+ )
1719
+ if images is not None:
1720
+ _inputs['images'] = images
1721
+ return _inputs
1722
+
1723
+
1724
+ AutoConfig.register("imp_qwen2", ImpQwen2Config)
1725
+ AutoModelForCausalLM.register(ImpQwen2Config, ImpQwen2ForCausalLM)
special_tokens_map.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>"
5
+ ],
6
+ "eos_token": {
7
+ "content": "<|im_end|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "pad_token": {
14
+ "content": "<|endoftext|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ }
20
+ }
tokenization_qwen2.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for Qwen2."""
16
+
17
+ import json
18
+ import os
19
+ import unicodedata
20
+ from functools import lru_cache
21
+ from typing import Optional, Tuple
22
+
23
+ import regex as re
24
+
25
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
26
+ from transformers.utils import logging
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+ VOCAB_FILES_NAMES = {
32
+ "vocab_file": "vocab.json",
33
+ "merges_file": "merges.txt",
34
+ }
35
+
36
+ PRETRAINED_VOCAB_FILES_MAP = {
37
+ "vocab_file": {"qwen/qwen-tokenizer": "https://huggingface.co/qwen/qwen-tokenizer/resolve/main/vocab.json"},
38
+ "merges_file": {"qwen/qwen-tokenizer": "https://huggingface.co/qwen/qwen-tokenizer/resolve/main/merges.txt"},
39
+ }
40
+
41
+ MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
42
+
43
+ PRETOKENIZE_REGEX = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
44
+
45
+
46
+ @lru_cache()
47
+ # Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
48
+ def bytes_to_unicode():
49
+ """
50
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
51
+ characters the bpe code barfs on.
52
+
53
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
54
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
55
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
56
+ tables between utf-8 bytes and unicode strings.
57
+ """
58
+ bs = (
59
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
60
+ )
61
+ cs = bs[:]
62
+ n = 0
63
+ for b in range(2**8):
64
+ if b not in bs:
65
+ bs.append(b)
66
+ cs.append(2**8 + n)
67
+ n += 1
68
+ cs = [chr(n) for n in cs]
69
+ return dict(zip(bs, cs))
70
+
71
+
72
+ # Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
73
+ def get_pairs(word):
74
+ """
75
+ Return set of symbol pairs in a word.
76
+
77
+ Word is represented as tuple of symbols (symbols being variable-length strings).
78
+ """
79
+ pairs = set()
80
+ prev_char = word[0]
81
+ for char in word[1:]:
82
+ pairs.add((prev_char, char))
83
+ prev_char = char
84
+ return pairs
85
+
86
+
87
+ class Qwen2Tokenizer(PreTrainedTokenizer):
88
+ """
89
+ Construct a Qwen2 tokenizer. Based on byte-level Byte-Pair-Encoding.
90
+
91
+ Same with GPT2Tokenzier, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
92
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
93
+
94
+ ```python
95
+ >>> from transformers import Qwen2Tokenizer
96
+
97
+ >>> tokenizer = Qwen2Tokenizer.from_pretrained("Qwen/Qwen-tokenizer")
98
+ >>> tokenizer("Hello world")["input_ids"]
99
+ [9707, 1879]
100
+
101
+ >>> tokenizer(" Hello world")["input_ids"]
102
+ [21927, 1879]
103
+ ```
104
+ This is expected.
105
+
106
+ You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
107
+
108
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
109
+ this superclass for more information regarding those methods.
110
+
111
+ Args:
112
+ vocab_file (`str`):
113
+ Path to the vocabulary file.
114
+ merges_file (`str`):
115
+ Path to the merges file.
116
+ errors (`str`, *optional*, defaults to `"replace"`):
117
+ Paradigm to follow when decoding bytes to UTF-8. See
118
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
119
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
120
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
121
+ token instead.
122
+ bos_token (`str`, *optional*):
123
+ The beginning of sequence token. Not applicable for this tokenizer.
124
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
125
+ The end of sequence token.
126
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
127
+ The token used for padding, for example when batching sequences of different lengths.
128
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
129
+ Whether or not the model should cleanup the spaces that were added when splitting the input text during the
130
+ tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
131
+ split_special_tokens (`bool`, *optional*, defaults to `False`):
132
+ Whether or not the special tokens should be split during the tokenization process. The default behavior is
133
+ to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
134
+ ['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
135
+ '|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
136
+ """
137
+
138
+ vocab_files_names = VOCAB_FILES_NAMES
139
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
140
+ max_model_input_sizes = MAX_MODEL_INPUT_SIZES
141
+ model_input_names = ["input_ids", "attention_mask"]
142
+
143
+ def __init__(
144
+ self,
145
+ vocab_file,
146
+ merges_file,
147
+ errors="replace",
148
+ unk_token="<|endoftext|>",
149
+ bos_token=None,
150
+ eos_token="<|endoftext|>",
151
+ pad_token="<|endoftext|>",
152
+ clean_up_tokenization_spaces=False,
153
+ split_special_tokens=False,
154
+ **kwargs,
155
+ ):
156
+ # Qwen vocab does not contain control tokens; added tokens need to be special
157
+ bos_token = (
158
+ AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
159
+ if isinstance(bos_token, str)
160
+ else bos_token
161
+ )
162
+ eos_token = (
163
+ AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
164
+ if isinstance(eos_token, str)
165
+ else eos_token
166
+ )
167
+ unk_token = (
168
+ AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
169
+ if isinstance(unk_token, str)
170
+ else unk_token
171
+ )
172
+ pad_token = (
173
+ AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
174
+ if isinstance(pad_token, str)
175
+ else pad_token
176
+ )
177
+
178
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
179
+ self.encoder = json.load(vocab_handle)
180
+ self.decoder = {v: k for k, v in self.encoder.items()}
181
+ self.errors = errors # how to handle errors in decoding
182
+ self.byte_encoder = bytes_to_unicode()
183
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
184
+ bpe_merges = []
185
+ with open(merges_file, encoding="utf-8") as merges_handle:
186
+ for line in merges_handle:
187
+ line = line.strip()
188
+ if not line or line.startswith("#"):
189
+ continue
190
+ bpe_merges.append(tuple(line.split()))
191
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
192
+ # NOTE: the cache can grow without bound and will get really large for long running processes
193
+ # (esp. for texts of language that do not use space between word, e.g. Chinese); technically
194
+ # not a memory leak but appears as one.
195
+ # GPT2Tokenizer has the same problem, so let's be consistent.
196
+ self.cache = {}
197
+
198
+ self.pat = re.compile(PRETOKENIZE_REGEX)
199
+
200
+ if kwargs.get("add_prefix_space", False):
201
+ logger.warning_once(
202
+ f"{self.__class__.__name} does not support `add_prefix_space`, setting it to True has no effect."
203
+ )
204
+
205
+ super().__init__(
206
+ errors=errors,
207
+ bos_token=bos_token,
208
+ eos_token=eos_token,
209
+ pad_token=pad_token,
210
+ unk_token=unk_token,
211
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
212
+ split_special_tokens=split_special_tokens,
213
+ **kwargs,
214
+ )
215
+
216
+ @property
217
+ def vocab_size(self) -> int:
218
+ return len(self.encoder)
219
+
220
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_vocab
221
+ def get_vocab(self):
222
+ return dict(self.encoder, **self.added_tokens_encoder)
223
+
224
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
225
+ def bpe(self, token):
226
+ if token in self.cache:
227
+ return self.cache[token]
228
+ word = tuple(token)
229
+ pairs = get_pairs(word)
230
+
231
+ if not pairs:
232
+ return token
233
+
234
+ while True:
235
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
236
+ if bigram not in self.bpe_ranks:
237
+ break
238
+ first, second = bigram
239
+ new_word = []
240
+ i = 0
241
+ while i < len(word):
242
+ try:
243
+ j = word.index(first, i)
244
+ except ValueError:
245
+ new_word.extend(word[i:])
246
+ break
247
+ else:
248
+ new_word.extend(word[i:j])
249
+ i = j
250
+
251
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
252
+ new_word.append(first + second)
253
+ i += 2
254
+ else:
255
+ new_word.append(word[i])
256
+ i += 1
257
+ new_word = tuple(new_word)
258
+ word = new_word
259
+ if len(word) == 1:
260
+ break
261
+ else:
262
+ pairs = get_pairs(word)
263
+ word = " ".join(word)
264
+ self.cache[token] = word
265
+ return word
266
+
267
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._tokenize
268
+ def _tokenize(self, text):
269
+ """Tokenize a string."""
270
+ bpe_tokens = []
271
+ for token in re.findall(self.pat, text):
272
+ token = "".join(
273
+ self.byte_encoder[b] for b in token.encode("utf-8")
274
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
275
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
276
+ return bpe_tokens
277
+
278
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
279
+ def _convert_token_to_id(self, token):
280
+ """Converts a token (str) in an id using the vocab."""
281
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
282
+
283
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
284
+ def _convert_id_to_token(self, index):
285
+ """Converts an index (integer) in a token (str) using the vocab."""
286
+ return self.decoder.get(index)
287
+
288
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
289
+ def convert_tokens_to_string(self, tokens):
290
+ """Converts a sequence of tokens (string) in a single string."""
291
+ text = "".join(tokens)
292
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
293
+ return text
294
+
295
+ def decode(
296
+ self,
297
+ token_ids,
298
+ skip_special_tokens: bool = False,
299
+ clean_up_tokenization_spaces: Optional[bool] = False,
300
+ spaces_between_special_tokens: bool = False,
301
+ **kwargs,
302
+ ) -> str:
303
+ # `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
304
+ # and cannot be configured elsewhere, but it should default to False for Qwen2Tokenizer
305
+ return super().decode(
306
+ token_ids,
307
+ skip_special_tokens=skip_special_tokens,
308
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
309
+ spaces_between_special_tokens=spaces_between_special_tokens,
310
+ **kwargs,
311
+ )
312
+
313
+ # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
314
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
315
+ if not os.path.isdir(save_directory):
316
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
317
+ return
318
+ vocab_file = os.path.join(
319
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
320
+ )
321
+ merge_file = os.path.join(
322
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
323
+ )
324
+
325
+ with open(vocab_file, "w", encoding="utf-8") as f:
326
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
327
+
328
+ index = 0
329
+ with open(merge_file, "w", encoding="utf-8") as writer:
330
+ writer.write("#version: 0.2\n")
331
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
332
+ if index != token_index:
333
+ logger.warning(
334
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
335
+ " Please check that the tokenizer is not corrupted!"
336
+ )
337
+ index = token_index
338
+ writer.write(" ".join(bpe_tokens) + "\n")
339
+ index += 1
340
+
341
+ return vocab_file, merge_file
342
+
343
+ def prepare_for_tokenization(self, text, **kwargs):
344
+ text = unicodedata.normalize("NFC", text)
345
+ return (text, kwargs)
tokenizer_config.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "151643": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151644": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151645": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "151646": {
29
+ "content": "<image>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ }
36
+ },
37
+ "additional_special_tokens": [
38
+ "<|im_start|>",
39
+ "<|im_end|>"
40
+ ],
41
+ "auto_map": {
42
+ "AutoTokenizer": [
43
+ "tokenization_qwen2.Qwen2Tokenizer",
44
+ null
45
+ ]
46
+ },
47
+ "bos_token": null,
48
+ "chat_template": "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
49
+ "clean_up_tokenization_spaces": false,
50
+ "eos_token": "<|endoftext|>",
51
+ "errors": "replace",
52
+ "model_max_length": 32768,
53
+ "pad_token": "<|endoftext|>",
54
+ "split_special_tokens": false,
55
+ "tokenizer_class": "Qwen2Tokenizer",
56
+ "unk_token": null
57
+ }
vision_encoder.py ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MILVLG team.
2
+ # Licensed under the Apache 2.0 license.
3
+ #
4
+ # Some code here is copied from the project Phi-2 (https://huggingface.co/microsoft/phi-2),
5
+ # SigLIP@transformers==4.37.0.dev0 (https://huggingface.co/google/siglip-so400m-patch14-384),
6
+ # and Llava (https://github.com/haotian-liu/LLaVA), and modified by
7
+ # Zhenwei Shao ([email protected]) @ MILVLG. We thank them for their great works.
8
+ # And their original licenses and copyright should be inherited (see the statements
9
+ # in `configuration_imp.py` for more details).
10
+
11
+
12
+ from typing import Any, Optional, Tuple, Union, List, Dict
13
+ from dataclasses import dataclass
14
+ import math
15
+ import warnings
16
+ from functools import partial, reduce
17
+
18
+
19
+ import numpy as np
20
+ from PIL import Image
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+
25
+ from transformers.image_processing_utils import BatchFeature
26
+ from transformers.image_transforms import (
27
+ convert_to_rgb,
28
+ normalize,
29
+ rescale,
30
+ resize,
31
+ to_channel_dimension_format,
32
+ )
33
+ from transformers.image_utils import (
34
+ ChannelDimension,
35
+ PILImageResampling,
36
+ to_numpy_array,
37
+ )
38
+ from transformers.activations import ACT2FN
39
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.utils import ModelOutput
42
+
43
+ from .configuration_imp_qwen import SiglipVisionConfig
44
+
45
+
46
+ # ============================================================================
47
+ # A simple image preprocessor for SigLIP models.
48
+ # ============================================================================
49
+
50
+ def simple_image_processor(
51
+ images,
52
+ image_mean=(0.5, 0.5, 0.5),
53
+ image_std=(0.5, 0.5, 0.5),
54
+ size=(384, 384),
55
+ resample=PILImageResampling.BICUBIC,
56
+ rescale_factor=1 / 255,
57
+ data_format=ChannelDimension.FIRST,
58
+ return_tensors="pt"
59
+ ):
60
+
61
+ if isinstance(images, Image.Image):
62
+ images = [images]
63
+ else:
64
+ assert isinstance(images, list)
65
+
66
+ transforms = [
67
+ convert_to_rgb,
68
+ to_numpy_array,
69
+ partial(resize, size=size, resample=resample, data_format=data_format),
70
+ partial(rescale, scale=rescale_factor, data_format=data_format),
71
+ partial(normalize, mean=image_mean, std=image_std, data_format=data_format),
72
+ partial(to_channel_dimension_format, channel_dim=data_format, input_channel_dim=data_format),
73
+ ]
74
+
75
+ images = reduce(lambda x, f: [*map(f, x)], transforms, images)
76
+ data = {"pixel_values": images}
77
+
78
+ return BatchFeature(data=data, tensor_type=return_tensors)
79
+
80
+ # ============================================================================
81
+ # Definitions for SigLIP models.
82
+ # ============================================================================
83
+
84
+ @dataclass
85
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Siglip
86
+ class SiglipVisionModelOutput(ModelOutput):
87
+ """
88
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
89
+
90
+ Args:
91
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
92
+ The image embeddings obtained by applying the projection layer to the pooler_output.
93
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
94
+ Sequence of hidden-states at the output of the last layer of the model.
95
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
96
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
97
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
98
+
99
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
100
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
101
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
102
+ sequence_length)`.
103
+
104
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
105
+ heads.
106
+ """
107
+
108
+ image_embeds: Optional[torch.FloatTensor] = None
109
+ last_hidden_state: torch.FloatTensor = None
110
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
111
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
112
+
113
+
114
+ class SiglipVisionEmbeddings(nn.Module):
115
+ def __init__(self, config: SiglipVisionConfig):
116
+ super().__init__()
117
+ self.config = config
118
+ self.embed_dim = config.hidden_size
119
+ self.image_size = config.image_size
120
+ self.patch_size = config.patch_size
121
+
122
+ self.patch_embedding = nn.Conv2d(
123
+ in_channels=config.num_channels,
124
+ out_channels=self.embed_dim,
125
+ kernel_size=self.patch_size,
126
+ stride=self.patch_size,
127
+ padding="valid",
128
+ )
129
+
130
+ self.num_patches = (self.image_size // self.patch_size) ** 2
131
+ self.num_positions = self.num_patches
132
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
133
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
134
+
135
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
136
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
137
+ embeddings = patch_embeds.flatten(2).transpose(1, 2)
138
+
139
+ embeddings = embeddings + self.position_embedding(self.position_ids)
140
+ return embeddings
141
+
142
+
143
+
144
+ class SiglipAttention(nn.Module):
145
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
146
+
147
+ # Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__
148
+ def __init__(self, config):
149
+ super().__init__()
150
+ self.config = config
151
+ self.embed_dim = config.hidden_size
152
+ self.num_heads = config.num_attention_heads
153
+ self.head_dim = self.embed_dim // self.num_heads
154
+ if self.head_dim * self.num_heads != self.embed_dim:
155
+ raise ValueError(
156
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
157
+ f" {self.num_heads})."
158
+ )
159
+ self.scale = self.head_dim**-0.5
160
+ self.dropout = config.attention_dropout
161
+
162
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
163
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
164
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
165
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
166
+
167
+ def forward(
168
+ self,
169
+ hidden_states: torch.Tensor,
170
+ attention_mask: Optional[torch.Tensor] = None,
171
+ output_attentions: Optional[bool] = False,
172
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
173
+ """Input shape: Batch x Time x Channel"""
174
+
175
+ batch_size, q_len, _ = hidden_states.size()
176
+
177
+ query_states = self.q_proj(hidden_states)
178
+ key_states = self.k_proj(hidden_states)
179
+ value_states = self.v_proj(hidden_states)
180
+
181
+ query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
182
+ key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
183
+ value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
184
+
185
+ k_v_seq_len = key_states.shape[-2]
186
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
187
+
188
+ if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
189
+ raise ValueError(
190
+ f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is"
191
+ f" {attn_weights.size()}"
192
+ )
193
+
194
+ if attention_mask is not None:
195
+ if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
196
+ raise ValueError(
197
+ f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}"
198
+ )
199
+ attn_weights = attn_weights + attention_mask
200
+
201
+ # upcast attention to fp32
202
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
203
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
204
+ attn_output = torch.matmul(attn_weights, value_states)
205
+
206
+ if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
207
+ raise ValueError(
208
+ f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is"
209
+ f" {attn_output.size()}"
210
+ )
211
+
212
+ attn_output = attn_output.transpose(1, 2).contiguous()
213
+ attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
214
+
215
+ attn_output = self.out_proj(attn_output)
216
+
217
+ return attn_output, attn_weights
218
+
219
+
220
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglip
221
+ class SiglipMLP(nn.Module):
222
+ def __init__(self, config):
223
+ super().__init__()
224
+ self.config = config
225
+ self.activation_fn = ACT2FN[config.hidden_act]
226
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
227
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
228
+
229
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
230
+ hidden_states = self.fc1(hidden_states)
231
+ hidden_states = self.activation_fn(hidden_states)
232
+ hidden_states = self.fc2(hidden_states)
233
+ return hidden_states
234
+
235
+
236
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Siglip
237
+ class SiglipEncoderLayer(nn.Module):
238
+ def __init__(self, config: SiglipVisionConfig):
239
+ super().__init__()
240
+ self.embed_dim = config.hidden_size
241
+ self.self_attn = SiglipAttention(config)
242
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
243
+ self.mlp = SiglipMLP(config)
244
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
245
+
246
+ # Ignore copy
247
+ def forward(
248
+ self,
249
+ hidden_states: torch.Tensor,
250
+ attention_mask: torch.Tensor,
251
+ output_attentions: Optional[bool] = False,
252
+ ) -> Tuple[torch.FloatTensor]:
253
+ """
254
+ Args:
255
+ hidden_states (`torch.FloatTensor`):
256
+ Input to the layer of shape `(batch, seq_len, embed_dim)`.
257
+ attention_mask (`torch.FloatTensor`):
258
+ Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
259
+ output_attentions (`bool`, *optional*, defaults to `False`):
260
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
261
+ returned tensors for more detail.
262
+ """
263
+ residual = hidden_states
264
+
265
+ hidden_states = self.layer_norm1(hidden_states)
266
+ hidden_states, attn_weights = self.self_attn(
267
+ hidden_states=hidden_states,
268
+ attention_mask=attention_mask,
269
+ output_attentions=output_attentions,
270
+ )
271
+ hidden_states = residual + hidden_states
272
+
273
+ residual = hidden_states
274
+ hidden_states = self.layer_norm2(hidden_states)
275
+ hidden_states = self.mlp(hidden_states)
276
+ hidden_states = residual + hidden_states
277
+
278
+ outputs = (hidden_states,)
279
+
280
+ if output_attentions:
281
+ outputs += (attn_weights,)
282
+
283
+ return outputs
284
+
285
+
286
+ class SiglipPreTrainedModel(PreTrainedModel):
287
+ """
288
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
289
+ models.
290
+ """
291
+
292
+ config_class = SiglipVisionConfig
293
+ base_model_prefix = "siglip"
294
+ supports_gradient_checkpointing = True
295
+
296
+ def _init_weights(self, module):
297
+ """Initialize the weights"""
298
+ pass
299
+
300
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Siglip
301
+ class SiglipEncoder(nn.Module):
302
+ """
303
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
304
+ [`SiglipEncoderLayer`].
305
+
306
+ Args:
307
+ config: SiglipVisionConfig
308
+ """
309
+
310
+ def __init__(self, config: SiglipVisionConfig):
311
+ super().__init__()
312
+ self.config = config
313
+ self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
314
+ self.gradient_checkpointing = False
315
+
316
+ # Ignore copy
317
+ def forward(
318
+ self,
319
+ inputs_embeds,
320
+ attention_mask: Optional[torch.Tensor] = None,
321
+ output_attentions: Optional[bool] = None,
322
+ output_hidden_states: Optional[bool] = None,
323
+ return_dict: Optional[bool] = None,
324
+ ) -> Union[Tuple, BaseModelOutput]:
325
+ r"""
326
+ Args:
327
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
328
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
329
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
330
+ than the model's internal embedding lookup matrix.
331
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
332
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
333
+
334
+ - 1 for tokens that are **not masked**,
335
+ - 0 for tokens that are **masked**.
336
+
337
+ [What are attention masks?](../glossary#attention-mask)
338
+ output_attentions (`bool`, *optional*):
339
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
340
+ returned tensors for more detail.
341
+ output_hidden_states (`bool`, *optional*):
342
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
343
+ for more detail.
344
+ return_dict (`bool`, *optional*):
345
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
346
+ """
347
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
348
+ output_hidden_states = (
349
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
350
+ )
351
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
352
+
353
+ encoder_states = () if output_hidden_states else None
354
+ all_attentions = () if output_attentions else None
355
+
356
+ hidden_states = inputs_embeds
357
+ for encoder_layer in self.layers:
358
+ if output_hidden_states:
359
+ encoder_states = encoder_states + (hidden_states,)
360
+ if self.gradient_checkpointing and self.training:
361
+ layer_outputs = self._gradient_checkpointing_func(
362
+ encoder_layer.__call__,
363
+ hidden_states,
364
+ attention_mask,
365
+ output_attentions,
366
+ )
367
+ else:
368
+ layer_outputs = encoder_layer(
369
+ hidden_states,
370
+ attention_mask,
371
+ output_attentions=output_attentions,
372
+ )
373
+
374
+ hidden_states = layer_outputs[0]
375
+
376
+ if output_attentions:
377
+ all_attentions = all_attentions + (layer_outputs[1],)
378
+
379
+ if output_hidden_states:
380
+ encoder_states = encoder_states + (hidden_states,)
381
+
382
+ if not return_dict:
383
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
384
+ return BaseModelOutput(
385
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
386
+ )
387
+
388
+
389
+ class SiglipVisionTransformer(nn.Module):
390
+ def __init__(self, config: SiglipVisionConfig):
391
+ super().__init__()
392
+ self.config = config
393
+ embed_dim = config.hidden_size
394
+
395
+ self.embeddings = SiglipVisionEmbeddings(config)
396
+ self.encoder = SiglipEncoder(config)
397
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
398
+ self.head = SiglipMultiheadAttentionPoolingHead(config)
399
+
400
+ def forward(
401
+ self,
402
+ pixel_values,
403
+ output_attentions: Optional[bool] = None,
404
+ output_hidden_states: Optional[bool] = None,
405
+ return_dict: Optional[bool] = None,
406
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
407
+ r"""
408
+ Returns:
409
+
410
+ """
411
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
412
+ output_hidden_states = (
413
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
414
+ )
415
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
416
+
417
+ hidden_states = self.embeddings(pixel_values)
418
+
419
+ encoder_outputs = self.encoder(
420
+ inputs_embeds=hidden_states,
421
+ output_attentions=output_attentions,
422
+ output_hidden_states=output_hidden_states,
423
+ return_dict=return_dict,
424
+ )
425
+
426
+ last_hidden_state = encoder_outputs[0]
427
+ last_hidden_state = self.post_layernorm(last_hidden_state)
428
+
429
+ pooled_output = self.head(last_hidden_state)
430
+
431
+ if not return_dict:
432
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
433
+
434
+ return BaseModelOutputWithPooling(
435
+ last_hidden_state=last_hidden_state,
436
+ pooler_output=pooled_output,
437
+ hidden_states=encoder_outputs.hidden_states,
438
+ attentions=encoder_outputs.attentions,
439
+ )
440
+
441
+
442
+ class SiglipMultiheadAttentionPoolingHead(nn.Module):
443
+ """Multihead Attention Pooling."""
444
+
445
+ def __init__(self, config: SiglipVisionConfig):
446
+ super().__init__()
447
+
448
+ self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
449
+ self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
450
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
451
+ self.mlp = SiglipMLP(config)
452
+
453
+ def forward(self, hidden_state):
454
+ batch_size = hidden_state.shape[0]
455
+ probe = self.probe.repeat(batch_size, 1, 1)
456
+
457
+ hidden_state = self.attention(probe, hidden_state, hidden_state)[0]
458
+
459
+ residual = hidden_state
460
+ hidden_state = self.layernorm(hidden_state)
461
+ hidden_state = residual + self.mlp(hidden_state)
462
+
463
+ return hidden_state[:, 0]
464
+
465
+
466
+ class SiglipVisionModel(SiglipPreTrainedModel):
467
+ config_class = SiglipVisionConfig
468
+ main_input_name = "pixel_values"
469
+ _no_split_modules = ["SiglipEncoderLayer"]
470
+
471
+ def __init__(self, config: SiglipVisionConfig):
472
+ super().__init__(config)
473
+
474
+ self.vision_model = SiglipVisionTransformer(config)
475
+
476
+ # Initialize weights and apply final processing
477
+ self.post_init()
478
+
479
+ def get_input_embeddings(self) -> nn.Module:
480
+ return self.vision_model.embeddings.patch_embedding
481
+
482
+ def forward(
483
+ self,
484
+ pixel_values,
485
+ output_attentions: Optional[bool] = None,
486
+ output_hidden_states: Optional[bool] = None,
487
+ return_dict: Optional[bool] = None,
488
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
489
+ r"""
490
+ Returns:
491
+
492
+ Examples:
493
+
494
+ ```python
495
+ >>> from PIL import Image
496
+ >>> import requests
497
+ >>> from transformers import AutoProcessor, SiglipVisionModel
498
+
499
+ >>> model = SiglipVisionModel.from_pretrained("google/siglip-base-patch16-224")
500
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
501
+
502
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
503
+ >>> image = Image.open(requests.get(url, stream=True).raw)
504
+
505
+ >>> inputs = processor(images=image, return_tensors="pt")
506
+
507
+ >>> outputs = model(**inputs)
508
+ >>> last_hidden_state = outputs.last_hidden_state
509
+ >>> pooled_output = outputs.pooler_output # pooled features
510
+ ```"""
511
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
512
+
513
+ return self.vision_model(
514
+ pixel_values=pixel_values,
515
+ output_attentions=output_attentions,
516
+ output_hidden_states=output_hidden_states,
517
+ return_dict=return_dict,
518
+ )
519
+
520
+
521
+ # ============================================================================
522
+ # VisionTower module for Imp
523
+ # ============================================================================
524
+
525
+ class VisionTower(nn.Module):
526
+ def __init__(self, vision_tower_cfg, delay_load=False):
527
+ super().__init__()
528
+
529
+ self.is_loaded = False
530
+
531
+ self.config = vision_tower_cfg
532
+ self.vision_tower_name = vision_tower_cfg.mm_vision_tower
533
+ self.select_layer = vision_tower_cfg.mm_vision_select_layer
534
+ # self.select_feature = getattr(vision_tower_cfg, 'mm_vision_select_feature', 'patch')
535
+
536
+ self.image_processor = simple_image_processor
537
+
538
+ if not delay_load:
539
+ self.load_model()
540
+ else:
541
+ raise NotImplementedError("delay load is not implemented yet.")
542
+
543
+ def load_model(self):
544
+ if self.is_loaded:
545
+ return
546
+
547
+ # "google/siglip-so400m-patch14-384"
548
+ # self.vision_tower = SiglipVisionModel.from_pretrained(self.vision_tower_name)
549
+ self.vision_tower = SiglipVisionModel(self.config)
550
+ del self.vision_tower.vision_model.encoder.layers[(self.select_layer + 1):]
551
+ self.vision_tower.vision_model.head = nn.Identity()
552
+ self.vision_tower.requires_grad_(False)
553
+ self.vision_tower.eval()
554
+
555
+ self.is_loaded = True
556
+
557
+ @torch.no_grad()
558
+ def forward(self, images):
559
+ if type(images) is list:
560
+ image_features = []
561
+ for image in images:
562
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
563
+ image_feature = image_forward_out.hidden_states[-1].to(image.dtype)
564
+ assert image_features.shape[-2] == 729
565
+ image_features.append(image_feature)
566
+ else:
567
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
568
+ image_features = image_forward_outs.hidden_states[-1].to(images.dtype)
569
+ assert image_features.shape[-2] == 729
570
+
571
+ return image_features
572
+
573
+ @property
574
+ def dummy_feature(self):
575
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
576
+
577
+ @property
578
+ def dtype(self):
579
+ for p in self.vision_tower.parameters():
580
+ return p.dtype
581
+
582
+ @property
583
+ def device(self):
584
+ for p in self.vision_tower.parameters():
585
+ return p.device
586
+
587
+ @property
588
+ def hidden_size(self):
589
+ return self.config.hidden_size
590
+
591
+ @property
592
+ def num_patches(self):
593
+ return (self.config.image_size // self.config.patch_size) ** 2
vocab.json ADDED
The diff for this file is too large to render. See raw diff