sharpenb commited on
Commit
9835fa5
1 Parent(s): 10c5621

f7243118a058fbafbb5a1b9892398ade5150fc2cfe2559a2109f979291b79be7

Browse files
README.md ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ thumbnail: "https://assets-global.website-files.com/646b351987a8d8ce158d1940/64ec9e96b4334c0e1ac41504_Logo%20with%20white%20text.svg"
3
+ base_model: MILVLG/imp-v1-3b
4
+ metrics:
5
+ - memory_disk
6
+ - memory_inference
7
+ - inference_latency
8
+ - inference_throughput
9
+ - inference_CO2_emissions
10
+ - inference_energy_consumption
11
+ tags:
12
+ - pruna-ai
13
+ ---
14
+ <!-- header start -->
15
+ <!-- 200823 -->
16
+ <div style="width: auto; margin-left: auto; margin-right: auto">
17
+ <a href="https://www.pruna.ai/" target="_blank" rel="noopener noreferrer">
18
+ <img src="https://i.imgur.com/eDAlcgk.png" alt="PrunaAI" style="width: 100%; min-width: 400px; display: block; margin: auto;">
19
+ </a>
20
+ </div>
21
+ <!-- header end -->
22
+
23
+ [![Twitter](https://img.shields.io/twitter/follow/PrunaAI?style=social)](https://twitter.com/PrunaAI)
24
+ [![GitHub](https://img.shields.io/github/followers/PrunaAI?label=Follow%20%40PrunaAI&style=social)](https://github.com/PrunaAI)
25
+ [![LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-blue)](https://www.linkedin.com/company/93832878/admin/feed/posts/?feedType=following)
26
+ [![Discord](https://img.shields.io/badge/Discord-Join%20Us-blue?style=social&logo=discord)](https://discord.gg/rskEr4BZJx)
27
+
28
+ # Simply make AI models cheaper, smaller, faster, and greener!
29
+
30
+ - Give a thumbs up if you like this model!
31
+ - Contact us and tell us which model to compress next [here](https://www.pruna.ai/contact).
32
+ - Request access to easily compress your *own* AI models [here](https://z0halsaff74.typeform.com/pruna-access?typeform-source=www.pruna.ai).
33
+ - Read the documentations to know more [here](https://pruna-ai-pruna.readthedocs-hosted.com/en/latest/)
34
+ - Join Pruna AI community on Discord [here](https://discord.gg/CP4VSgck) to share feedback/suggestions or get help.
35
+
36
+ ## Results
37
+
38
+ ![image info](./plots.png)
39
+
40
+ **Frequently Asked Questions**
41
+ - ***How does the compression work?*** The model is compressed with llm-int8.
42
+ - ***How does the model quality change?*** The quality of the model output might vary compared to the base model.
43
+ - ***How is the model efficiency evaluated?*** These results were obtained on HARDWARE_NAME with configuration described in `model/smash_config.json` and are obtained after a hardware warmup. The smashed model is directly compared to the original base model. Efficiency results may vary in other settings (e.g. other hardware, image size, batch size, ...). We recommend to directly run them in the use-case conditions to know if the smashed model can benefit you.
44
+ - ***What is the model format?*** We use safetensors.
45
+ - ***What calibration data has been used?*** If needed by the compression method, we used WikiText as the calibration data.
46
+ - ***What is the naming convention for Pruna Huggingface models?*** We take the original model name and append "turbo", "tiny", or "green" if the smashed model has a measured inference speed, inference memory, or inference energy consumption which is less than 90% of the original base model.
47
+ - ***How to compress my own models?*** You can request premium access to more compression methods and tech support for your specific use-cases [here](https://z0halsaff74.typeform.com/pruna-access?typeform-source=www.pruna.ai).
48
+ - ***What are "first" metrics?*** Results mentioning "first" are obtained after the first run of the model. The first run might take more memory or be slower than the subsequent runs due cuda overheads.
49
+ - ***What are "Sync" and "Async" metrics?*** "Sync" metrics are obtained by syncing all GPU processes and stop measurement when all of them are executed. "Async" metrics are obtained without syncing all GPU processes and stop when the model output can be used by the CPU. We provide both metrics since both could be relevant depending on the use-case. We recommend to test the efficiency gains directly in your use-cases.
50
+
51
+ ## Setup
52
+
53
+ You can run the smashed model with these steps:
54
+
55
+ 0. Check requirements from the original repo MILVLG/imp-v1-3b installed. In particular, check python, cuda, and transformers versions.
56
+ 1. Make sure that you have installed quantization related packages.
57
+ ```bash
58
+ pip install transformers accelerate bitsandbytes>0.37.0
59
+ ```
60
+ 2. Load & run the model.
61
+ ```python
62
+ from transformers import AutoModelForCausalLM, AutoTokenizer
63
+
64
+
65
+ model = AutoModelForCausalLM.from_pretrained("PrunaAI/MILVLG-imp-v1-3b-bnb-4bit-smashed", trust_remote_code=True, device_map='auto')
66
+ tokenizer = AutoTokenizer.from_pretrained("MILVLG/imp-v1-3b")
67
+
68
+ input_ids = tokenizer("What is the color of prunes?,", return_tensors='pt').to(model.device)["input_ids"]
69
+
70
+ outputs = model.generate(input_ids, max_new_tokens=216)
71
+ tokenizer.decode(outputs[0])
72
+ ```
73
+
74
+ ## Configurations
75
+
76
+ The configuration info are in `smash_config.json`.
77
+
78
+ ## Credits & License
79
+
80
+ The license of the smashed model follows the license of the original model. Please check the license of the original model MILVLG/imp-v1-3b before using this model which provided the base model. The license of the `pruna-engine` is [here](https://pypi.org/project/pruna-engine/) on Pypi.
81
+
82
+ ## Want to compress other models?
83
+
84
+ - Contact us and tell us which model to compress next [here](https://www.pruna.ai/contact).
85
+ - Request access to easily compress your own AI models [here](https://z0halsaff74.typeform.com/pruna-access?typeform-source=www.pruna.ai).
added_tokens.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "\t\t": 50294,
3
+ "\t\t\t": 50293,
4
+ "\t\t\t\t": 50292,
5
+ "\t\t\t\t\t": 50291,
6
+ "\t\t\t\t\t\t": 50290,
7
+ "\t\t\t\t\t\t\t": 50289,
8
+ "\t\t\t\t\t\t\t\t": 50288,
9
+ "\t\t\t\t\t\t\t\t\t": 50287,
10
+ " ": 50286,
11
+ " ": 50285,
12
+ " ": 50284,
13
+ " ": 50283,
14
+ " ": 50282,
15
+ " ": 50281,
16
+ " ": 50280,
17
+ " ": 50279,
18
+ " ": 50278,
19
+ " ": 50277,
20
+ " ": 50276,
21
+ " ": 50275,
22
+ " ": 50274,
23
+ " ": 50273,
24
+ " ": 50272,
25
+ " ": 50271,
26
+ " ": 50270,
27
+ " ": 50269,
28
+ " ": 50268,
29
+ " ": 50267,
30
+ " ": 50266,
31
+ " ": 50265,
32
+ " ": 50264,
33
+ " ": 50263,
34
+ " ": 50262,
35
+ " ": 50261,
36
+ " ": 50260,
37
+ " ": 50259,
38
+ " ": 50258,
39
+ " ": 50257,
40
+ "</s>": 50295,
41
+ "<image>": 50296
42
+ }
config.json ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/ceph/hdd/staff/charpent/.cache/models1ogh7zr57phyperr",
3
+ "activation_function": "gelu_new",
4
+ "architectures": [
5
+ "ImpForCausalLM"
6
+ ],
7
+ "attention_dropout": 0.0,
8
+ "attn_pdrop": 0.0,
9
+ "auto_map": {
10
+ "AutoConfig": "configuration_imp.ImpConfig",
11
+ "AutoModelForCausalLM": "modeling_imp.ImpForCausalLM"
12
+ },
13
+ "bos_token_id": 1,
14
+ "embd_pdrop": 0.0,
15
+ "eos_token_id": 50295,
16
+ "freeze_mm_mlp_adapter": false,
17
+ "hidden_act": "gelu_new",
18
+ "hidden_size": 2560,
19
+ "image_aspect_ratio": "square",
20
+ "image_token": "<image>",
21
+ "image_token_index": 50296,
22
+ "img_processor": null,
23
+ "initializer_range": 0.02,
24
+ "intermediate_size": 10240,
25
+ "layer_norm_eps": 1e-05,
26
+ "max_position_embeddings": 3072,
27
+ "mm_hidden_size": 1152,
28
+ "mm_projector_lr": 2e-05,
29
+ "mm_projector_type": "mlp2x_gelu",
30
+ "mm_use_im_patch_token": false,
31
+ "mm_use_im_start_end": false,
32
+ "mm_vision_select_feature": "patch",
33
+ "mm_vision_select_layer": -2,
34
+ "mm_vision_tower": "google/siglip-so400m-patch14-384",
35
+ "model_type": "imp",
36
+ "num_attention_heads": 32,
37
+ "num_hidden_layers": 32,
38
+ "num_key_value_heads": 32,
39
+ "pad_token_id": 50256,
40
+ "partial_rotary_factor": 0.4,
41
+ "qk_layernorm": false,
42
+ "quantization_config": {
43
+ "_load_in_4bit": true,
44
+ "_load_in_8bit": false,
45
+ "bnb_4bit_compute_dtype": "bfloat16",
46
+ "bnb_4bit_quant_storage": "uint8",
47
+ "bnb_4bit_quant_type": "fp4",
48
+ "bnb_4bit_use_double_quant": false,
49
+ "llm_int8_enable_fp32_cpu_offload": false,
50
+ "llm_int8_has_fp16_weight": false,
51
+ "llm_int8_skip_modules": [
52
+ "lm_head"
53
+ ],
54
+ "llm_int8_threshold": 6.0,
55
+ "load_in_4bit": true,
56
+ "load_in_8bit": false,
57
+ "quant_method": "bitsandbytes"
58
+ },
59
+ "resid_pdrop": 0.1,
60
+ "rope_scaling": null,
61
+ "rope_theta": 10000.0,
62
+ "tie_word_embeddings": false,
63
+ "tokenizer_model_max_length": 3072,
64
+ "tokenizer_padding_side": "right",
65
+ "torch_dtype": "float16",
66
+ "transformers_version": "4.42.4",
67
+ "use_cache": true,
68
+ "use_mm_proj": true,
69
+ "vision_tower_config": {
70
+ "attention_dropout": 0.0,
71
+ "attn_implementation": null,
72
+ "hidden_act": "gelu_pytorch_tanh",
73
+ "hidden_size": 1152,
74
+ "image_size": 384,
75
+ "intermediate_size": 4304,
76
+ "layer_norm_eps": 1e-06,
77
+ "model_type": "siglip_vision_model",
78
+ "num_attention_heads": 16,
79
+ "num_channels": 3,
80
+ "num_hidden_layers": 27,
81
+ "patch_size": 14
82
+ },
83
+ "vocab_size": 51200
84
+ }
configuration_imp.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 (shaozw@hdu.edu.cn) @ MILVLG. We thank them for their great works.
8
+ #
9
+ # We keep their original copyright statements as follows, which should be inherited:
10
+ # ------------------------------- Phi-2 ---------------------------------------------
11
+ # Copyright (c) Microsoft Corporation.
12
+ # Licensed under the MIT license.
13
+ # https://huggingface.co/google/siglip-so400m-patch14-384
14
+ #
15
+ # Copyright (c) 2022, Tri Dao, trid@cs.stanford.edu.
16
+ # Licensed under the BSD 3-Clause License.
17
+ # ------------------------------- SigLIP --------------------------------------------
18
+ # Copyright 2024 Google AI and The HuggingFace Team. All rights reserved.
19
+ #
20
+ # Licensed under the Apache License, Version 2.0 (the "License");
21
+ # you may not use this file except in compliance with the License.
22
+ # You may obtain a copy of the License at
23
+ #
24
+ # http://www.apache.org/licenses/LICENSE-2.0
25
+ #
26
+ # Unless required by applicable law or agreed to in writing, software
27
+ # distributed under the License is distributed on an "AS IS" BASIS,
28
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29
+ # See the License for the specific language governing permissions and
30
+ # limitations under the License.
31
+ # ------------------------------- Llava ---------------------------------------------
32
+ # Copyright 2023 Haotian Liu
33
+ #
34
+ # Licensed under the Apache License, Version 2.0 (the "License");
35
+ # you may not use this file except in compliance with the License.
36
+ # You may obtain a copy of the License at
37
+ #
38
+ # http://www.apache.org/licenses/LICENSE-2.0
39
+ #
40
+ # Unless required by applicable law or agreed to in writing, software
41
+ # distributed under the License is distributed on an "AS IS" BASIS,
42
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
43
+ # See the License for the specific language governing permissions and
44
+ # limitations under the License.
45
+ # -----------------------------------------------------------------------------------
46
+
47
+
48
+ import os
49
+ import math
50
+ from typing import Optional, Union
51
+
52
+ from transformers import PretrainedConfig
53
+ from transformers.utils import logging
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ class PhiConfig(PretrainedConfig):
59
+ r"""
60
+ This is the configuration class to store the configuration of a [`PhiModel`]. It is used to instantiate an Phi
61
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
62
+ defaults will yield a similar configuration to that of the Phi
63
+ [microsoft/phi-1](https://huggingface.co/microsoft/phi-1).
64
+
65
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
66
+ documentation from [`PretrainedConfig`] for more information.
67
+
68
+ Args:
69
+ vocab_size (`int`, *optional*, defaults to 51200):
70
+ Vocabulary size of the Phi model. Defines the number of different tokens that can be represented by the
71
+ `inputs_ids` passed when calling [`PhiModel`].
72
+ hidden_size (`int`, *optional*, defaults to 2048):
73
+ Dimension of the hidden representations.
74
+ intermediate_size (`int`, *optional*, defaults to 8192):
75
+ Dimension of the MLP representations.
76
+ num_hidden_layers (`int`, *optional*, defaults to 24):
77
+ Number of hidden layers in the Transformer decoder.
78
+ num_attention_heads (`int`, *optional*, defaults to 32):
79
+ Number of attention heads for each attention layer in the Transformer decoder.
80
+ num_key_value_heads (`int`, *optional*):
81
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
82
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
83
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
84
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
85
+ by meanpooling all the original heads within that group. For more details checkout [this
86
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
87
+ `num_attention_heads`.
88
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
89
+ Dropout probability for mlp outputs.
90
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
91
+ The dropout ratio for the embeddings.
92
+ attention_dropout (`float`, *optional*, defaults to 0.0):
93
+ The dropout ratio after computing the attention scores.
94
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
95
+ The non-linear activation function (function or string) in the decoder.
96
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
97
+ The maximum sequence length that this model might ever be used with. Phi-1 and Phi-1.5 supports up to 2048
98
+ tokens.
99
+ initializer_range (`float`, *optional*, defaults to 0.02):
100
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
101
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
102
+ The epsilon used by the rms normalization layers.
103
+ use_cache (`bool`, *optional*, defaults to `True`):
104
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
105
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
106
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
107
+ Whether to tie weight embeddings
108
+ rope_theta (`float`, *optional*, defaults to 10000.0):
109
+ The base period of the RoPE embeddings.
110
+ rope_scaling (`Dict`, *optional*):
111
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
112
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
113
+ is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
114
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
115
+ these scaling strategies behave:
116
+ https://www.reddit.com/r/LocalPersimmon/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This
117
+ is an experimental feature, subject to breaking API changes in future versions.
118
+ partial_rotary_factor (`float`, *optional*, defaults to 0.5):
119
+ Percentage of the query and keys which will have rotary embedding.
120
+ qk_layernorm (`bool`, *optional*, defaults to `False`):
121
+ Whether or not to normalize the Queries and Keys after projecting the hidden states.
122
+ bos_token_id (`int`, *optional*, defaults to 1):
123
+ Denotes beginning of sequences token id.
124
+ eos_token_id (`int`, *optional*, defaults to 2):
125
+ Denotes end of sequences token id.
126
+
127
+ Example:
128
+
129
+ ```python
130
+ >>> from transformers import PhiModel, PhiConfig
131
+
132
+ >>> # Initializing a Phi-1 style configuration
133
+ >>> configuration = PhiConfig.from_pretrained("microsoft/phi-1")
134
+
135
+ >>> # Initializing a model from the configuration
136
+ >>> model = PhiModel(configuration)
137
+
138
+ >>> # Accessing the model configuration
139
+ >>> configuration = model.config
140
+ ```"""
141
+
142
+ model_type = "phi"
143
+ keys_to_ignore_at_inference = ["past_key_values"]
144
+
145
+ def __init__(
146
+ self,
147
+ vocab_size=51200,
148
+ hidden_size=2048,
149
+ intermediate_size=8192,
150
+ num_hidden_layers=32, #24
151
+ num_attention_heads=32,
152
+ num_key_value_heads=None,
153
+ resid_pdrop=0.0,
154
+ embd_pdrop=0.0,
155
+ attention_dropout=0.0,
156
+ hidden_act="gelu_new",
157
+ max_position_embeddings=2048,
158
+ initializer_range=0.02,
159
+ layer_norm_eps=1e-5,
160
+ use_cache=True,
161
+ tie_word_embeddings=False,
162
+ rope_theta=10000.0,
163
+ rope_scaling=None,
164
+ partial_rotary_factor=0.5,
165
+ qk_layernorm=False,
166
+ bos_token_id=1,
167
+ eos_token_id=2,
168
+ **kwargs,
169
+ ):
170
+ self.vocab_size = vocab_size
171
+ self.hidden_size = hidden_size
172
+ self.intermediate_size = intermediate_size
173
+ self.num_hidden_layers = num_hidden_layers
174
+ self.num_attention_heads = num_attention_heads
175
+
176
+ if num_key_value_heads is None:
177
+ num_key_value_heads = num_attention_heads
178
+
179
+ self.num_key_value_heads = num_key_value_heads
180
+ self.resid_pdrop = resid_pdrop
181
+ self.embd_pdrop = embd_pdrop
182
+ self.attention_dropout = attention_dropout
183
+ self.hidden_act = hidden_act
184
+ self.max_position_embeddings = max_position_embeddings
185
+ self.initializer_range = initializer_range
186
+ self.layer_norm_eps = layer_norm_eps
187
+ self.use_cache = use_cache
188
+ self.rope_theta = rope_theta
189
+ self.rope_scaling = rope_scaling
190
+ self.partial_rotary_factor = partial_rotary_factor
191
+ self.qk_layernorm = qk_layernorm
192
+ self._rope_scaling_validation()
193
+
194
+ super().__init__(
195
+ bos_token_id=bos_token_id,
196
+ eos_token_id=eos_token_id,
197
+ tie_word_embeddings=tie_word_embeddings,
198
+ **kwargs,
199
+ )
200
+
201
+ # Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
202
+ def _rope_scaling_validation(self):
203
+ """
204
+ Validate the `rope_scaling` configuration.
205
+ """
206
+ if self.rope_scaling is None:
207
+ return
208
+
209
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
210
+ raise ValueError(
211
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
212
+ f"got {self.rope_scaling}"
213
+ )
214
+ rope_scaling_type = self.rope_scaling.get("type", None)
215
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
216
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
217
+ raise ValueError(
218
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
219
+ )
220
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
221
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
222
+
223
+
224
+ class SiglipVisionConfig(PretrainedConfig):
225
+
226
+ model_type = "siglip_vision_model"
227
+
228
+ def __init__(
229
+ self,
230
+ hidden_size=768,
231
+ intermediate_size=3072,
232
+ num_hidden_layers=12,
233
+ num_attention_heads=12,
234
+ num_channels=3,
235
+ image_size=224,
236
+ patch_size=16,
237
+ hidden_act="gelu_pytorch_tanh",
238
+ layer_norm_eps=1e-6,
239
+ attention_dropout=0.0,
240
+ **kwargs,
241
+ ):
242
+ super().__init__(**kwargs)
243
+
244
+ self.hidden_size = hidden_size
245
+ self.intermediate_size = intermediate_size
246
+ self.num_hidden_layers = num_hidden_layers
247
+ self.num_attention_heads = num_attention_heads
248
+ self.num_channels = num_channels
249
+ self.patch_size = patch_size
250
+ self.image_size = image_size
251
+ self.attention_dropout = attention_dropout
252
+ self.layer_norm_eps = layer_norm_eps
253
+ self.hidden_act = hidden_act
254
+
255
+ @classmethod
256
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
257
+ cls._set_token_in_kwargs(kwargs)
258
+
259
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
260
+
261
+ # get the vision config dict if we are loading from SiglipConfig
262
+ if config_dict.get("model_type") == "siglip":
263
+ config_dict = config_dict["vision_config"]
264
+
265
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
266
+ logger.warning(
267
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
268
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
269
+ )
270
+
271
+ return cls.from_dict(config_dict, **kwargs)
272
+
273
+
274
+ class ImpConfig(PhiConfig):
275
+ model_type = "imp"
276
+
277
+ def __init__(self, **kwargs):
278
+ super().__init__(**kwargs)
279
+ self.image_token_index = getattr(self, "image_token_index", 50296)
280
+ self.image_token = getattr(self, "image_token", "<image>")
281
+
282
+ if not hasattr(self, "vision_tower_config") and hasattr(self, "mm_vision_tower"):
283
+ vision_tower_config = SiglipVisionConfig.from_pretrained(self.mm_vision_tower)
284
+ self.vision_tower_config = vision_tower_config.to_diff_dict()
285
+
286
+ @property
287
+ def vision_tower_cfg(self):
288
+ cfg = SiglipVisionConfig.from_dict(self.vision_tower_config)
289
+ # imp-v1 only supports `patch` feature for now w/o cls token
290
+ # cfg.mm_vision_select_feature = self.mm_vision_select_feature
291
+ cfg.mm_vision_select_layer = self.mm_vision_select_layer
292
+ cfg.mm_vision_tower = self.mm_vision_tower
293
+ return cfg
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "eos_token_id": 50295,
4
+ "pad_token_id": 50256,
5
+ "transformers_version": "4.42.4"
6
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
modeling_imp.py ADDED
@@ -0,0 +1,1297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 (shaozw@hdu.edu.cn) @ 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
+ # Be careful: The way how `past_key_values.seqlen_offset` is updated is modified from
13
+ # the implementation of original Phi-2. See the comments below for details.
14
+
15
+ from __future__ import annotations
16
+ import os
17
+ import math
18
+ import re
19
+ # from dataclasses import dataclass, field
20
+ from typing import Any, Dict, Optional, Tuple, Union, List
21
+ from abc import ABC, abstractmethod
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+ import torch.utils.checkpoint
29
+ from transformers import (
30
+ PretrainedConfig,
31
+ PreTrainedModel,
32
+ AutoConfig,
33
+ AutoModelForCausalLM
34
+ )
35
+ from transformers.activations import ACT2FN
36
+ from transformers.cache_utils import Cache, DynamicCache
37
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
38
+ from transformers.modeling_outputs import (
39
+ BaseModelOutputWithPast,
40
+ CausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ TokenClassifierOutput,
43
+ )
44
+ from transformers.modeling_utils import PreTrainedModel
45
+ from transformers.utils import (
46
+ add_code_sample_docstrings,
47
+ add_start_docstrings,
48
+ add_start_docstrings_to_model_forward,
49
+ is_flash_attn_2_available,
50
+ is_flash_attn_greater_or_equal_2_10,
51
+ logging,
52
+ replace_return_docstrings,
53
+ )
54
+ import sys
55
+ from .configuration_imp import PhiConfig, ImpConfig
56
+ from .vision_encoder import VisionTower
57
+
58
+ try:
59
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
60
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
61
+ except:
62
+ pass
63
+
64
+ logger = logging.get_logger(__name__)
65
+
66
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Phi
67
+ class PhiRotaryEmbedding(nn.Module):
68
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
69
+ super().__init__()
70
+
71
+ self.dim = dim
72
+ self.max_position_embeddings = max_position_embeddings
73
+ self.base = base
74
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
75
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
76
+
77
+ # Build here to make `torch.jit.trace` work.
78
+ self._set_cos_sin_cache(
79
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
80
+ )
81
+
82
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
83
+ self.max_seq_len_cached = seq_len
84
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
85
+
86
+ freqs = torch.outer(t, self.inv_freq)
87
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
88
+ emb = torch.cat((freqs, freqs), dim=-1)
89
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
90
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
91
+
92
+ def forward(self, x, seq_len=None):
93
+ # x: [bs, num_attention_heads, seq_len, head_size]
94
+ if seq_len > self.max_seq_len_cached:
95
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
96
+
97
+ return (
98
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
99
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
100
+ )
101
+
102
+
103
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Phi
104
+ class PhiLinearScalingRotaryEmbedding(PhiRotaryEmbedding):
105
+ """PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
106
+
107
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
108
+ self.scaling_factor = scaling_factor
109
+ super().__init__(dim, max_position_embeddings, base, device)
110
+
111
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
112
+ self.max_seq_len_cached = seq_len
113
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
114
+ t = t / self.scaling_factor
115
+
116
+ freqs = torch.outer(t, self.inv_freq)
117
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
118
+ emb = torch.cat((freqs, freqs), dim=-1)
119
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
120
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
121
+
122
+
123
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Phi
124
+ class PhiDynamicNTKScalingRotaryEmbedding(PhiRotaryEmbedding):
125
+ """PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
126
+
127
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
128
+ self.scaling_factor = scaling_factor
129
+ super().__init__(dim, max_position_embeddings, base, device)
130
+
131
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
132
+ self.max_seq_len_cached = seq_len
133
+
134
+ if seq_len > self.max_position_embeddings:
135
+ base = self.base * (
136
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
137
+ ) ** (self.dim / (self.dim - 2))
138
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
139
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
140
+
141
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
142
+
143
+ freqs = torch.outer(t, self.inv_freq)
144
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
145
+ emb = torch.cat((freqs, freqs), dim=-1)
146
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
147
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
148
+
149
+
150
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
151
+ def rotate_half(x):
152
+ """Rotates half the hidden dims of the input."""
153
+ x1 = x[..., : x.shape[-1] // 2]
154
+ x2 = x[..., x.shape[-1] // 2 :]
155
+ return torch.cat((-x2, x1), dim=-1)
156
+
157
+
158
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
159
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
160
+ """Applies Rotary Position Embedding to the query and key tensors.
161
+
162
+ Args:
163
+ q (`torch.Tensor`): The query tensor.
164
+ k (`torch.Tensor`): The key tensor.
165
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
166
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
167
+ position_ids (`torch.Tensor`):
168
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
169
+ used to pass offsetted position ids when working with a KV-cache.
170
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
171
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
172
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
173
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
174
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
175
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
176
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
177
+ Returns:
178
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
179
+ """
180
+ temp_type=q.dtype#ouyang modified
181
+ q, k, cos, sin = [t.to(dtype=torch.float32) for t in [q, k, cos, sin]] #ouyang modified
182
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
183
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
184
+ q_embed = (q * cos) + (rotate_half(q) * sin)
185
+ k_embed = (k * cos) + (rotate_half(k) * sin)
186
+ q_embed,k_embed = q_embed.to(temp_type), k_embed.to(temp_type)#ouyang modified
187
+ return q_embed, k_embed
188
+
189
+
190
+
191
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Phi
192
+ class PhiMLP(nn.Module):
193
+ def __init__(self, config):
194
+ super().__init__()
195
+ self.config = config
196
+ self.activation_fn = ACT2FN[config.hidden_act]
197
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
198
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
199
+
200
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
201
+ hidden_states = self.fc1(hidden_states)
202
+ hidden_states = self.activation_fn(hidden_states)
203
+ hidden_states = self.fc2(hidden_states)
204
+ return hidden_states
205
+
206
+
207
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
208
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
209
+ """
210
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
211
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
212
+ """
213
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
214
+ if n_rep == 1:
215
+ return hidden_states
216
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
217
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
218
+
219
+
220
+
221
+ class PhiAttention(nn.Module):
222
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
223
+
224
+ def __init__(self, config: PhiConfig, layer_idx: Optional[int] = None):
225
+ super().__init__()
226
+ self.config = config
227
+ self.layer_idx = layer_idx
228
+ # if layer_idx is None:
229
+ # logger.warning_once(
230
+ # f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
231
+ # "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
232
+ # "when creating this class."
233
+ # )
234
+
235
+ self.attention_dropout = config.attention_dropout
236
+ self.hidden_size = config.hidden_size
237
+ self.num_heads = config.num_attention_heads
238
+ self.head_dim = self.hidden_size // self.num_heads
239
+ self.num_key_value_heads = config.num_key_value_heads
240
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
241
+ self.max_position_embeddings = config.max_position_embeddings
242
+ self.rope_theta = config.rope_theta
243
+ self.partial_rotary_factor = config.partial_rotary_factor
244
+ self.is_causal = True
245
+
246
+ if (self.head_dim * self.num_heads) != self.hidden_size:
247
+ raise ValueError(
248
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
249
+ f" and `num_heads`: {self.num_heads})."
250
+ )
251
+
252
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
253
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
254
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
255
+ self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=True)
256
+
257
+ self.qk_layernorm = config.qk_layernorm
258
+ if self.qk_layernorm:
259
+ self.q_layernorm = nn.LayerNorm(
260
+ config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
261
+ )
262
+ self.k_layernorm = nn.LayerNorm(
263
+ config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
264
+ )
265
+
266
+ self._init_rope()
267
+
268
+ def _init_rope(self):
269
+ if self.config.rope_scaling is None:
270
+ self.rotary_emb = PhiRotaryEmbedding(
271
+ int(self.partial_rotary_factor * self.head_dim),
272
+ max_position_embeddings=self.max_position_embeddings,
273
+ base=self.rope_theta,
274
+ )
275
+ else:
276
+ scaling_type = self.config.rope_scaling["type"]
277
+ scaling_factor = self.config.rope_scaling["factor"]
278
+ if scaling_type == "linear":
279
+ self.rotary_emb = PhiLinearScalingRotaryEmbedding(
280
+ int(self.partial_rotary_factor * self.head_dim),
281
+ max_position_embeddings=self.max_position_embeddings,
282
+ scaling_factor=scaling_factor,
283
+ base=self.rope_theta,
284
+ )
285
+ elif scaling_type == "dynamic":
286
+ self.rotary_emb = PhiDynamicNTKScalingRotaryEmbedding(
287
+ int(self.partial_rotary_factor * self.head_dim),
288
+ max_position_embeddings=self.max_position_embeddings,
289
+ scaling_factor=scaling_factor,
290
+ base=self.rope_theta,
291
+ )
292
+ else:
293
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
294
+
295
+ # Phi-2 has an attention overflow issue (with FP16) and requires autocast to be disabled
296
+ @torch.autocast("cpu", enabled=False)
297
+ @torch.autocast("cuda", enabled=False)
298
+ def forward(
299
+ self,
300
+ hidden_states: torch.Tensor,
301
+ attention_mask: Optional[torch.Tensor] = None,
302
+ position_ids: Optional[torch.LongTensor] = None,
303
+ past_key_value: Optional[Cache] = None,
304
+ output_attentions: bool = False,
305
+ use_cache: bool = False,
306
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
307
+ bsz, q_len, _ = hidden_states.size()
308
+
309
+
310
+ query_states = self.q_proj(hidden_states)
311
+ key_states = self.k_proj(hidden_states)
312
+ value_states = self.v_proj(hidden_states)
313
+
314
+ if self.qk_layernorm:
315
+ query_states = self.q_layernorm(query_states)
316
+ key_states = self.k_layernorm(key_states)
317
+
318
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
319
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
320
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
321
+
322
+ kv_seq_len = key_states.shape[-2]
323
+ if past_key_value is not None:
324
+ if self.layer_idx is None:
325
+ raise ValueError(
326
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
327
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
328
+ "with a layer index."
329
+ )
330
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
331
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
332
+
333
+ # Partial rotary embedding
334
+ query_rot, query_pass = (
335
+ query_states[..., : self.rotary_emb.dim],
336
+ query_states[..., self.rotary_emb.dim :],
337
+ )
338
+ key_rot, key_pass = (
339
+ key_states[..., : self.rotary_emb.dim],
340
+ key_states[..., self.rotary_emb.dim :],
341
+ )
342
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
343
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
344
+
345
+ # [batch_size, seq_length, num_heads, head_dim]
346
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
347
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
348
+
349
+ if past_key_value is not None:
350
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
351
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
352
+
353
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
354
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
355
+
356
+ # Queries and keys upcast to fp32 is required by Phi-2 to avoid overflow
357
+ # attn_weights = torch.matmul(
358
+ # query_states.to(torch.float32), key_states.to(torch.float32).transpose(2, 3)
359
+ # ) / math.sqrt(self.head_dim)
360
+
361
+ softmax_scale = 1.0 / math.sqrt(query_states.shape[-1])
362
+ attn_weights = torch.matmul(
363
+ query_states.to(torch.float32), key_states.to(torch.float32).transpose(2, 3)*softmax_scale
364
+ )#ouyang modified
365
+
366
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
367
+ raise ValueError(
368
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
369
+ f" {attn_weights.size()}"
370
+ )
371
+
372
+ if attention_mask is not None:
373
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
374
+ raise ValueError(
375
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
376
+ )
377
+ attn_weights = attn_weights + attention_mask
378
+
379
+ # upcast attention to fp32
380
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
381
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
382
+
383
+ attn_output = torch.matmul(attn_weights, value_states)
384
+
385
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
386
+ raise ValueError(
387
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
388
+ f" {attn_output.size()}"
389
+ )
390
+
391
+ attn_output = attn_output.transpose(1, 2).contiguous()
392
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
393
+
394
+
395
+ attn_output = self.dense(attn_output)
396
+
397
+ if not output_attentions:
398
+ attn_weights = None
399
+
400
+ return attn_output, attn_weights, past_key_value
401
+
402
+ class PhiFlashAttention2(PhiAttention):
403
+ """
404
+ Phi flash attention module. This module inherits from `PhiAttention` as the weights of the module stays
405
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
406
+ flash attention and deal with padding tokens in case the input contains any of them.
407
+ """
408
+
409
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
410
+ def __init__(self, *args, **kwargs):
411
+ super().__init__(*args, **kwargs)
412
+
413
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
414
+ # 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.
415
+ # 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).
416
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
417
+
418
+ def forward(
419
+ self,
420
+ hidden_states: torch.Tensor,
421
+ attention_mask: Optional[torch.LongTensor] = None,
422
+ position_ids: Optional[torch.LongTensor] = None,
423
+ past_key_value: Optional[Cache] = None,
424
+ output_attentions: bool = False,
425
+ use_cache: bool = False,
426
+ **kwargs,
427
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
428
+ # PhiFlashAttention2 attention does not support output_attentions
429
+
430
+ output_attentions = False
431
+
432
+ bsz, q_len, _ = hidden_states.size()
433
+
434
+ query_states = self.q_proj(hidden_states)
435
+ key_states = self.k_proj(hidden_states)
436
+ value_states = self.v_proj(hidden_states)
437
+
438
+ if self.qk_layernorm:
439
+ query_states = self.q_layernorm(query_states)
440
+ key_states = self.k_layernorm(key_states)
441
+
442
+ # Flash attention requires the input to have the shape
443
+ # batch_size x seq_length x head_dim x hidden_dim
444
+ # therefore we just need to keep the original shape
445
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
446
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
447
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
448
+
449
+ kv_seq_len = key_states.shape[-2]
450
+ if past_key_value is not None:
451
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
452
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
453
+
454
+ # Partial rotary embedding
455
+ query_rot, query_pass = (
456
+ query_states[..., : self.rotary_emb.dim],
457
+ query_states[..., self.rotary_emb.dim :],
458
+ )
459
+ key_rot, key_pass = (
460
+ key_states[..., : self.rotary_emb.dim],
461
+ key_states[..., self.rotary_emb.dim :],
462
+ )
463
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
464
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
465
+
466
+ # [batch_size, seq_length, num_heads, head_dim]
467
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
468
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
469
+
470
+ if past_key_value is not None:
471
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
472
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
473
+
474
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
475
+ # to be able to avoid many of these transpose/reshape/view.
476
+ query_states = query_states.transpose(1, 2)
477
+ key_states = key_states.transpose(1, 2)
478
+ value_states = value_states.transpose(1, 2)
479
+
480
+ attn_dropout = self.attention_dropout if self.training else 0.0
481
+
482
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
483
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
484
+ # cast them back in the correct dtype just to be sure everything works as expected.
485
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
486
+ # in fp32.
487
+
488
+ if query_states.dtype == torch.float32:
489
+ if torch.is_autocast_enabled():
490
+ target_dtype = torch.get_autocast_gpu_dtype()
491
+ # Handle the case where the model is quantized
492
+ elif hasattr(self.config, "_pre_quantization_dtype"):
493
+ target_dtype = self.config._pre_quantization_dtype
494
+ else:
495
+ target_dtype = self.q_proj.weight.dtype
496
+
497
+ logger.warning_once(
498
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
499
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
500
+ f" {target_dtype}."
501
+ )
502
+
503
+ query_states = query_states.to(target_dtype)
504
+ key_states = key_states.to(target_dtype)
505
+ value_states = value_states.to(target_dtype)
506
+
507
+ attn_output = self._flash_attention_forward(
508
+ query_states, key_states, value_states, attention_mask, q_len, dropout=attn_dropout, softmax_scale=None
509
+ )
510
+
511
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
512
+ attn_output = self.dense(attn_output)
513
+
514
+ if not output_attentions:
515
+ attn_weights = None
516
+
517
+ return attn_output, attn_weights, past_key_value
518
+
519
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
520
+ def _flash_attention_forward(
521
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
522
+ ):
523
+ """
524
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
525
+ first unpad the input, then computes the attention scores and pad the final attention scores.
526
+
527
+ Args:
528
+ query_states (`torch.Tensor`):
529
+ Input query states to be passed to Flash Attention API
530
+ key_states (`torch.Tensor`):
531
+ Input key states to be passed to Flash Attention API
532
+ value_states (`torch.Tensor`):
533
+ Input value states to be passed to Flash Attention API
534
+ attention_mask (`torch.Tensor`):
535
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
536
+ position of padding tokens and 1 for the position of non-padding tokens.
537
+ dropout (`int`, *optional*):
538
+ Attention dropout
539
+ softmax_scale (`float`, *optional*):
540
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
541
+ """
542
+ if not self._flash_attn_uses_top_left_mask:
543
+ causal = self.is_causal
544
+ else:
545
+ # 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__.
546
+ causal = self.is_causal and query_length != 1
547
+
548
+ # Contains at least one padding token in the sequence
549
+ if attention_mask is not None:
550
+ batch_size = query_states.shape[0]
551
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
552
+ query_states, key_states, value_states, attention_mask, query_length
553
+ )
554
+
555
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
556
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
557
+
558
+ attn_output_unpad = flash_attn_varlen_func(
559
+ query_states,
560
+ key_states,
561
+ value_states,
562
+ cu_seqlens_q=cu_seqlens_q,
563
+ cu_seqlens_k=cu_seqlens_k,
564
+ max_seqlen_q=max_seqlen_in_batch_q,
565
+ max_seqlen_k=max_seqlen_in_batch_k,
566
+ dropout_p=dropout,
567
+ softmax_scale=softmax_scale,
568
+ causal=causal,
569
+ )
570
+
571
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
572
+ else:
573
+ attn_output = flash_attn_func(
574
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
575
+ )
576
+
577
+ return attn_output
578
+
579
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
580
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
581
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
582
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
583
+
584
+ key_layer = index_first_axis(
585
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
586
+ )
587
+ value_layer = index_first_axis(
588
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
589
+ )
590
+ if query_length == kv_seq_len:
591
+ query_layer = index_first_axis(
592
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
593
+ )
594
+ cu_seqlens_q = cu_seqlens_k
595
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
596
+ indices_q = indices_k
597
+ elif query_length == 1:
598
+ max_seqlen_in_batch_q = 1
599
+ cu_seqlens_q = torch.arange(
600
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
601
+ ) # There is a memcpy here, that is very bad.
602
+ indices_q = cu_seqlens_q[:-1]
603
+ query_layer = query_layer.squeeze(1)
604
+ else:
605
+ # The -q_len: slice assumes left padding.
606
+ attention_mask = attention_mask[:, -query_length:]
607
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
608
+
609
+ return (
610
+ query_layer,
611
+ key_layer,
612
+ value_layer,
613
+ indices_q,
614
+ (cu_seqlens_q, cu_seqlens_k),
615
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
616
+ )
617
+
618
+
619
+
620
+ PHI_ATTENTION_CLASSES = {
621
+ "eager": PhiAttention,
622
+ "flash_attention_2": PhiFlashAttention2,
623
+ }
624
+
625
+
626
+ class PhiDecoderLayer(nn.Module):
627
+ def __init__(self, config: PhiConfig, layer_idx: int):
628
+ super().__init__()
629
+ self.self_attn = PHI_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
630
+ self.mlp = PhiMLP(config)
631
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
632
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
633
+
634
+ def forward(
635
+ self,
636
+ hidden_states: torch.Tensor,
637
+ attention_mask: Optional[torch.Tensor] = None,
638
+ position_ids: Optional[torch.LongTensor] = None,
639
+ output_attentions: Optional[bool] = False,
640
+ use_cache: Optional[bool] = False,
641
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
642
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
643
+ """
644
+ Args:
645
+ hidden_states (`torch.FloatTensor`):
646
+ input to the layer of shape `(batch, seq_len, embed_dim)`
647
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
648
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
649
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
650
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
651
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
652
+ output_attentions (`bool`, *optional*):
653
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
654
+ returned tensors for more detail.
655
+ use_cache (`bool`, *optional*):
656
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
657
+ (see `past_key_values`).
658
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
659
+ """
660
+
661
+ residual = hidden_states
662
+
663
+ hidden_states = self.input_layernorm(hidden_states)
664
+
665
+ # Self Attention
666
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
667
+ hidden_states=hidden_states,
668
+ attention_mask=attention_mask,
669
+ position_ids=position_ids,
670
+ past_key_value=past_key_value,
671
+ output_attentions=output_attentions,
672
+ use_cache=use_cache,
673
+ )
674
+ attn_outputs = self.resid_dropout(attn_outputs)
675
+
676
+ feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
677
+ hidden_states = attn_outputs + feed_forward_hidden_states + residual
678
+ outputs = (hidden_states,)
679
+
680
+ if output_attentions:
681
+ outputs += (self_attn_weights,)
682
+
683
+ if use_cache:
684
+ outputs += (present_key_value,)
685
+
686
+ return outputs
687
+
688
+
689
+ class PhiPreTrainedModel(PreTrainedModel):
690
+ """Phi pre-trained model."""
691
+
692
+ config_class = PhiConfig
693
+ base_model_prefix = "model"
694
+ supports_gradient_checkpointing = True
695
+ _no_split_modules = ["PhiDecoderLayer"]
696
+ _skip_keys_device_placement = "past_key_values"
697
+ _supports_flash_attn_2 = True
698
+ _supports_cache_class = True
699
+
700
+ def __init__(self, *inputs, **kwargs) -> None:
701
+ super().__init__(*inputs, **kwargs)
702
+
703
+ def _init_weights(self, module):
704
+ std = self.config.initializer_range
705
+ if isinstance(module, nn.Linear):
706
+ module.weight.data.normal_(mean=0.0, std=std)
707
+ if module.bias is not None:
708
+ module.bias.data.zero_()
709
+ elif isinstance(module, nn.Embedding):
710
+ module.weight.data.normal_(mean=0.0, std=std)
711
+ if module.padding_idx is not None:
712
+ module.weight.data[module.padding_idx].zero_()
713
+
714
+ def prepare_inputs_for_generation(
715
+ self,
716
+ input_ids: torch.LongTensor,
717
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
718
+ inputs_embeds: Optional[torch.FloatTensor] = None,
719
+ attention_mask: Optional[Union[torch.LongTensor, torch.BoolTensor]] = None,
720
+ **kwargs,
721
+ ) -> Dict[str, Any]:
722
+ if past_key_values is not None:
723
+ if isinstance(past_key_values, Cache):
724
+ cache_length = past_key_values.get_seq_length()
725
+ past_length = past_key_values.seen_tokens
726
+ max_cache_length = past_key_values.get_max_length()
727
+ else:
728
+ cache_length = past_length = past_key_values[0][0].shape[2]
729
+ max_cache_length = None
730
+
731
+ # Keep only the unprocessed tokens:
732
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
733
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
734
+ # input)
735
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
736
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
737
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
738
+ # input_ids based on the past_length.
739
+ elif past_length < input_ids.shape[1]:
740
+ input_ids = input_ids[:, past_length:]
741
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
742
+
743
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
744
+ if (
745
+ max_cache_length is not None
746
+ and attention_mask is not None
747
+ and cache_length + input_ids.shape[1] > max_cache_length
748
+ ):
749
+ attention_mask = attention_mask[:, -max_cache_length:]
750
+
751
+ position_ids = kwargs.get("position_ids", None)
752
+ if attention_mask is not None and position_ids is None:
753
+ # create position_ids on the fly for batch generation
754
+ position_ids = attention_mask.long().cumsum(-1) - 1
755
+ position_ids.masked_fill_(attention_mask == 0, 1)
756
+ if past_key_values:
757
+ position_ids = position_ids[:, -input_ids.shape[1] :]
758
+
759
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
760
+ if inputs_embeds is not None and past_key_values is None:
761
+ model_inputs = {"inputs_embeds": inputs_embeds}
762
+ else:
763
+ model_inputs = {"input_ids": input_ids}
764
+
765
+ model_inputs.update(
766
+ {
767
+ "position_ids": position_ids,
768
+ "past_key_values": past_key_values,
769
+ "use_cache": kwargs.get("use_cache"),
770
+ "attention_mask": attention_mask,
771
+ }
772
+ )
773
+ return model_inputs
774
+
775
+
776
+ class LlavaMetaModel(ABC):
777
+ """
778
+ Define the APIs for building components that are related to image perceiving.
779
+ This implementation is based on the implementation from the Llave project.
780
+ """
781
+
782
+ def get_vision_tower(self):
783
+ vision_tower = getattr(self, 'vision_tower', None)
784
+ if type(vision_tower) is list:
785
+ vision_tower = vision_tower[0]
786
+ return vision_tower
787
+
788
+ def build_vision_tower(self, config):
789
+ self.vision_tower = VisionTower(config.vision_tower_cfg)
790
+
791
+ def build_vision_projector(self, config):
792
+ projector_type = getattr(config, 'mm_projector_type', 'linear')
793
+
794
+ if projector_type == 'linear':
795
+ self.mm_projector = nn.Linear(config.mm_hidden_size, config.hidden_size)
796
+ return
797
+
798
+ mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
799
+ if mlp_gelu_match:
800
+ mlp_depth = int(mlp_gelu_match.group(1))
801
+ modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
802
+ for _ in range(1, mlp_depth):
803
+ modules.append(nn.GELU())
804
+ modules.append(nn.Linear(config.hidden_size, config.hidden_size))
805
+ self.mm_projector = nn.Sequential(*modules)
806
+ return
807
+
808
+ if projector_type == 'identity':
809
+ self.mm_projector = nn.Identity()
810
+ return
811
+
812
+ raise ValueError(f'Unknown projector type: {projector_type}')
813
+
814
+
815
+ class ImpModel(PhiPreTrainedModel, LlavaMetaModel):
816
+ """Imp model. This implementation is modified from the implementation of Phi-2"""
817
+
818
+
819
+ def __init__(self, config: ImpConfig) -> None:
820
+ super().__init__(config)
821
+ self.padding_idx = config.pad_token_id
822
+ self.vocab_size = config.vocab_size
823
+
824
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
825
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
826
+ self.layers = nn.ModuleList(
827
+ [PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
828
+ )
829
+ self.final_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
830
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
831
+
832
+ self.gradient_checkpointing = False
833
+
834
+ if hasattr(config, "mm_vision_tower"):
835
+ self.build_vision_tower(config)
836
+ self.build_vision_projector(config)
837
+
838
+ self.post_init()
839
+
840
+ # def embed_tokens(self, input_ids: torch.LongTensor) -> torch.FloatTensor: #old
841
+ # return self.embd(input_ids)[0]
842
+
843
+ def get_input_embeddings(self) -> nn.Embedding:
844
+ # return self.embd.wte#old
845
+ return self.embed_tokens
846
+
847
+ def set_input_embeddings(self, value: nn.Embedding) -> None:
848
+ self.embed_tokens = value
849
+
850
+ def forward(
851
+ self,
852
+ input_ids: torch.LongTensor,
853
+ attention_mask: Optional[torch.BoolTensor] = None,
854
+ position_ids: Optional[torch.LongTensor] = None,
855
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
856
+ inputs_embeds: Optional[torch.FloatTensor] = None,
857
+ use_cache: Optional[bool] = None,
858
+ output_attentions: Optional[bool] = None,
859
+ output_hidden_states: Optional[bool] = None,
860
+ return_dict: Optional[bool] = None,
861
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
862
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
863
+ output_hidden_states = (
864
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
865
+ )
866
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
867
+
868
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
869
+
870
+ # retrieve input_ids and inputs_embeds
871
+ if input_ids is not None and inputs_embeds is not None:
872
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
873
+ elif input_ids is not None:
874
+ batch_size, seq_length = input_ids.shape
875
+ elif inputs_embeds is not None:
876
+ batch_size, seq_length, _ = inputs_embeds.shape
877
+ else:
878
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
879
+
880
+ past_key_values_length = 0
881
+
882
+ if self.gradient_checkpointing and self.training:
883
+ if use_cache:
884
+ logger.warning_once(
885
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
886
+ )
887
+ use_cache = False
888
+ if use_cache:
889
+ use_legacy_cache = not isinstance(past_key_values, Cache)
890
+ if use_legacy_cache:
891
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
892
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
893
+
894
+
895
+
896
+ if position_ids is None:
897
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
898
+ position_ids = torch.arange(
899
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
900
+ )
901
+ position_ids = position_ids.unsqueeze(0)
902
+
903
+ if inputs_embeds is None:
904
+ inputs_embeds = self.embed_tokens(input_ids)
905
+
906
+ inputs_embeds = self.embed_dropout(inputs_embeds)
907
+
908
+ if self._use_flash_attention_2:
909
+ # 2d mask is passed through the layers
910
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
911
+ else:
912
+ # 4d mask is passed through the layers
913
+ attention_mask = _prepare_4d_causal_attention_mask(
914
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
915
+ )
916
+ hidden_states = inputs_embeds
917
+ # ok
918
+
919
+ # decoder layers
920
+ all_hidden_states = () if output_hidden_states else None
921
+ all_self_attns = () if output_attentions else None
922
+ next_decoder_cache = None
923
+
924
+
925
+ for nums,decoder_layer in enumerate(self.layers):
926
+ if output_hidden_states:
927
+ all_hidden_states += (hidden_states,)
928
+
929
+ if self.gradient_checkpointing and self.training:
930
+ layer_outputs = self._gradient_checkpointing_func(
931
+ decoder_layer.__call__,
932
+ hidden_states,
933
+ attention_mask,
934
+ position_ids,
935
+ past_key_values,
936
+ output_attentions,
937
+ )
938
+ else:
939
+ layer_outputs = decoder_layer(
940
+ hidden_states,
941
+ attention_mask=attention_mask,
942
+ position_ids=position_ids,
943
+ past_key_value=past_key_values,
944
+ output_attentions=output_attentions,
945
+ use_cache=use_cache,
946
+ )
947
+ hidden_states = layer_outputs[0]
948
+
949
+ if use_cache:
950
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
951
+ if output_attentions:
952
+ all_self_attns += (layer_outputs[1],)
953
+
954
+
955
+ hidden_states = self.final_layernorm(hidden_states) #final_new_phi
956
+
957
+ # add hidden states from the last decoder layer
958
+ if output_hidden_states:
959
+ all_hidden_states += (hidden_states,)
960
+
961
+ next_cache = None
962
+ if use_cache:
963
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
964
+ if not return_dict:
965
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
966
+ return BaseModelOutputWithPast(
967
+ last_hidden_state=hidden_states,
968
+ past_key_values=next_cache,
969
+ hidden_states=all_hidden_states,
970
+ attentions=all_self_attns,
971
+ )
972
+
973
+
974
+
975
+ class LlavaMetaForCausalLM(ABC):
976
+ """This implementation is based on the implementation from the Llave project."""
977
+
978
+ def init_constants(self, config):
979
+ self.IGNORE_INDEX = getattr(config, 'ignore_index', -100)
980
+ self.IMAGE_TOKEN_INDEX = getattr(config, 'image_token_index', 50296)
981
+ self.DEFAULT_IMAGE_TOKEN = getattr(config, 'image_token', "<image>")
982
+
983
+ @abstractmethod
984
+ def get_model(self):
985
+ pass
986
+
987
+ def get_vision_tower(self):
988
+ return self.get_model().get_vision_tower()
989
+
990
+ def encode_images(self, images):
991
+ image_features = self.get_model().get_vision_tower()(images)
992
+ image_features = self.get_model().mm_projector(image_features)
993
+ return image_features
994
+
995
+ def prepare_inputs_labels_for_multimodal(
996
+ self, input_ids, position_ids, attention_mask, past_key_values, labels, images
997
+ ):
998
+ vision_tower = self.get_vision_tower()
999
+ if past_key_values is not None:
1000
+ target_shape = past_key_values[0][0].shape[2] + 1
1001
+ attention_mask = torch.ones(
1002
+ (attention_mask.shape[0], target_shape),
1003
+ dtype=attention_mask.dtype,
1004
+ device=attention_mask.device
1005
+ )
1006
+ position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
1007
+ # print(input_ids[:, -1:].item())
1008
+ return input_ids[:, -1:], position_ids, attention_mask, past_key_values, None, labels
1009
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
1010
+ # if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1:
1011
+ # target_shape = past_key_values.seqlen_offset + 1
1012
+ # attention_mask = torch.cat((attention_mask, torch.ones(
1013
+ # (attention_mask.shape[0], target_shape - attention_mask.shape[1]),
1014
+ # dtype=attention_mask.dtype,
1015
+ # device=attention_mask.device
1016
+ # )), dim=1)
1017
+ # position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
1018
+ return input_ids, None, None, past_key_values, None, None
1019
+ # return input_ids, position_ids, attention_mask, past_key_values, None, labels
1020
+
1021
+ # if vision_tower is None or images is None or past_key_values.seqlen_offset != 0:
1022
+ # if vision_tower is None or images is None or input_ids.shape[1] == 1:
1023
+ # if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1:
1024
+ # target_shape = past_key_values.seqlen_offset + 1
1025
+ # # inference_params.key_value_memory_dict[layer_idx][batch_start:batch_end, sequence_start:sequence_end, ...]
1026
+ # attention_mask = torch.cat((attention_mask, torch.ones(
1027
+ # (attention_mask.shape[0], target_shape - attention_mask.shape[1]),
1028
+ # dtype=attention_mask.dtype,
1029
+ # device=attention_mask.device
1030
+ # )), dim=1)
1031
+ # position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
1032
+ # return input_ids, position_ids, attention_mask, past_key_values, None, labels
1033
+
1034
+ if type(images) is list or images.ndim == 5:
1035
+ concat_images = torch.cat([image for image in images], dim=0)
1036
+ concat_images = concat_images.to(device=self.device, dtype=vision_tower.dtype)
1037
+ image_features = self.encode_images(concat_images)
1038
+ split_sizes = [image.shape[0] for image in images]
1039
+ image_features = torch.split(image_features, split_sizes, dim=0)
1040
+ image_features = [x.flatten(0, 1).to(self.device) for x in image_features]
1041
+ else:
1042
+ images = images.to(device=self.device, dtype=vision_tower.dtype)
1043
+ image_features = self.encode_images(images).to(self.device)
1044
+
1045
+ # TODO: image start / end is not implemented here to support pretraining.
1046
+ if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
1047
+ raise NotImplementedError
1048
+
1049
+ # Let's just add dummy tensors if they do not exist,
1050
+ # it is a headache to deal with None all the time.
1051
+ # But it is not ideal, and if you have a better idea,
1052
+ # please open an issue / submit a PR, thanks.
1053
+ _labels = labels
1054
+ _position_ids = position_ids
1055
+ _attention_mask = attention_mask
1056
+ if attention_mask is None:
1057
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
1058
+ else:
1059
+ attention_mask = attention_mask.bool()
1060
+ if position_ids is None:
1061
+ position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
1062
+ if labels is None:
1063
+ labels = torch.full_like(input_ids, self.IGNORE_INDEX)
1064
+
1065
+ # remove the padding using attention_mask -- TODO: double check
1066
+ input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
1067
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
1068
+
1069
+ new_input_embeds = []
1070
+ new_labels = []
1071
+ cur_image_idx = 0
1072
+ for batch_idx, cur_input_ids in enumerate(input_ids):
1073
+ num_images = (cur_input_ids == self.IMAGE_TOKEN_INDEX).sum()
1074
+ if num_images == 0:
1075
+ cur_image_features = image_features[cur_image_idx]
1076
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
1077
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
1078
+ new_input_embeds.append(cur_input_embeds)
1079
+ new_labels.append(labels[batch_idx])
1080
+ cur_image_idx += 1
1081
+ continue
1082
+
1083
+ image_token_indices = [-1] + torch.where(cur_input_ids == self.IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
1084
+ cur_input_ids_noim = []
1085
+ cur_labels = labels[batch_idx]
1086
+ cur_labels_noim = []
1087
+ for i in range(len(image_token_indices) - 1):
1088
+ cur_input_ids_noim.append(cur_input_ids[image_token_indices[i]+1:image_token_indices[i+1]])
1089
+ cur_labels_noim.append(cur_labels[image_token_indices[i]+1:image_token_indices[i+1]])
1090
+ split_sizes = [x.shape[0] for x in cur_labels_noim]
1091
+ cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
1092
+ # print(cur_input_embeds.shape)
1093
+ cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
1094
+ cur_new_input_embeds = []
1095
+ cur_new_labels = []
1096
+
1097
+ for i in range(num_images + 1):
1098
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
1099
+ cur_new_labels.append(cur_labels_noim[i])
1100
+ if i < num_images:
1101
+ cur_image_features = image_features[cur_image_idx]
1102
+ cur_image_idx += 1
1103
+ cur_new_input_embeds.append(cur_image_features)
1104
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), self.IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
1105
+
1106
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
1107
+ cur_new_labels = torch.cat(cur_new_labels)
1108
+
1109
+ new_input_embeds.append(cur_new_input_embeds)
1110
+ new_labels.append(cur_new_labels)
1111
+
1112
+ # Truncate sequences to max length as image embeddings can make the sequence longer
1113
+ tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None)
1114
+ if tokenizer_model_max_length is not None:
1115
+ new_input_embeds = [x[:tokenizer_model_max_length] for x in new_input_embeds]
1116
+ new_labels = [x[:tokenizer_model_max_length] for x in new_labels]
1117
+
1118
+ # Combine them
1119
+ max_len = max(x.shape[0] for x in new_input_embeds)
1120
+ batch_size = len(new_input_embeds)
1121
+
1122
+ new_input_embeds_padded = []
1123
+ new_labels_padded = torch.full((batch_size, max_len), self.IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
1124
+ attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
1125
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
1126
+
1127
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
1128
+ cur_len = cur_new_embed.shape[0]
1129
+ if getattr(self.config, 'tokenizer_padding_side', 'right') == "left":
1130
+ new_input_embeds_padded.append(torch.cat((
1131
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device),
1132
+ cur_new_embed
1133
+ ), dim=0))
1134
+ if cur_len > 0:
1135
+ new_labels_padded[i, -cur_len:] = cur_new_labels
1136
+ attention_mask[i, -cur_len:] = True
1137
+ position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
1138
+ else:
1139
+ new_input_embeds_padded.append(torch.cat((
1140
+ cur_new_embed,
1141
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)
1142
+ ), dim=0))
1143
+ if cur_len > 0:
1144
+ new_labels_padded[i, :cur_len] = cur_new_labels
1145
+ attention_mask[i, :cur_len] = True
1146
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
1147
+
1148
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
1149
+
1150
+ if _labels is None:
1151
+ new_labels = None
1152
+ else:
1153
+ new_labels = new_labels_padded
1154
+
1155
+ if _attention_mask is None:
1156
+ attention_mask = None
1157
+ else:
1158
+ attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
1159
+
1160
+ if _position_ids is None:
1161
+ position_ids = None
1162
+
1163
+ return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
1164
+ #return input_ids, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
1165
+
1166
+
1167
+ class ImpForCausalLM(PhiPreTrainedModel, LlavaMetaForCausalLM):
1168
+ """Imp for Causal Language Modeling."""
1169
+
1170
+ # _keys_to_ignore_on_load_missing = [""]
1171
+ # _keys_to_ignore_on_load_unexpected = [r"transformer\.h\.\d+\.mlp.(fc_in|fc_out)\.(weight|bias)"]
1172
+ config_class = ImpConfig
1173
+
1174
+ def __init__(self, config: ImpConfig) -> None:
1175
+ super().__init__(config)
1176
+
1177
+ self.model = ImpModel(config)
1178
+ self.vocab_size = config.vocab_size
1179
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
1180
+
1181
+ self.post_init()
1182
+ self.init_constants(config)
1183
+
1184
+ def get_input_embeddings(self):
1185
+ return self.model.embed_tokens
1186
+
1187
+ def set_input_embeddings(self, value):
1188
+ self.model.embed_tokens = value
1189
+
1190
+ def get_output_embeddings(self) -> nn.Linear:
1191
+ return self.lm_head
1192
+
1193
+ def set_output_embeddings(self, new_embeddings: nn.Linear) -> None:
1194
+ self.lm_head = new_embeddings
1195
+
1196
+ def get_model(self):
1197
+ return self.model
1198
+
1199
+ def get_decoder(self):
1200
+ return self.model
1201
+
1202
+ def set_decoder(self, decoder):#会被用?
1203
+ self.model = decoder
1204
+
1205
+ def image_preprocess(self, images):
1206
+ return self.get_vision_tower().image_processor(images)['pixel_values']
1207
+
1208
+ def forward(
1209
+ self,
1210
+ input_ids: torch.LongTensor = None,
1211
+ attention_mask: Optional[torch.Tensor] = None,
1212
+ position_ids: Optional[torch.LongTensor] = None,
1213
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1214
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1215
+ labels: Optional[torch.LongTensor] = None,
1216
+ use_cache: Optional[bool] = None,
1217
+ output_attentions: Optional[bool] = None,
1218
+ output_hidden_states: Optional[bool] = None,
1219
+ images: Optional[torch.FloatTensor] = None,
1220
+ return_dict: Optional[bool] = None,
1221
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1222
+
1223
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1224
+ output_hidden_states = (
1225
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1226
+ )
1227
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1228
+
1229
+ if inputs_embeds is None:
1230
+ (
1231
+ input_ids,
1232
+ position_ids,
1233
+ attention_mask,
1234
+ past_key_values,
1235
+ inputs_embeds,
1236
+ labels
1237
+ ) = self.prepare_inputs_labels_for_multimodal(
1238
+ input_ids,
1239
+ position_ids,
1240
+ attention_mask,
1241
+ past_key_values,
1242
+ labels,
1243
+ images
1244
+ )
1245
+
1246
+ outputs = self.model(
1247
+ input_ids=input_ids,
1248
+ past_key_values=past_key_values,
1249
+ attention_mask=attention_mask,
1250
+ position_ids=position_ids,
1251
+ inputs_embeds=inputs_embeds,
1252
+ use_cache=use_cache,
1253
+ output_attentions=output_attentions,
1254
+ output_hidden_states=output_hidden_states,
1255
+ return_dict=return_dict
1256
+ )
1257
+ hidden_states = outputs[0]
1258
+ logits = self.lm_head(hidden_states)
1259
+ logits = logits.float()
1260
+
1261
+ loss = None
1262
+ if labels is not None:
1263
+ # Shift so that tokens < n predict n
1264
+ shift_logits = logits[..., :-1, :].contiguous()
1265
+ shift_labels = labels[..., 1:].contiguous()
1266
+ # Flatten the tokens
1267
+ loss_fct = CrossEntropyLoss()
1268
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1269
+ shift_labels = shift_labels.view(-1)
1270
+ # Enable model parallelism
1271
+ shift_labels = shift_labels.to(shift_logits.device)
1272
+ loss = loss_fct(shift_logits, shift_labels)
1273
+ if not return_dict:
1274
+ loss = None
1275
+ output = (logits,) + outputs[1:]
1276
+ return (loss,) + output if loss is not None else output
1277
+
1278
+ return CausalLMOutputWithPast(
1279
+ loss=loss,
1280
+ logits=logits,
1281
+ past_key_values=outputs.past_key_values,
1282
+ hidden_states=outputs.hidden_states,
1283
+ attentions=outputs.attentions,
1284
+ )
1285
+
1286
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
1287
+ images = kwargs.pop("images", None)
1288
+ _inputs = super().prepare_inputs_for_generation(
1289
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
1290
+ )
1291
+ if images is not None:
1292
+ _inputs['images'] = images
1293
+ return _inputs
1294
+
1295
+
1296
+ AutoConfig.register("imp", ImpConfig)
1297
+ AutoModelForCausalLM.register(ImpConfig, ImpForCausalLM)
smash_config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "api_key": null,
3
+ "verify_url": "http://johnrachwan.pythonanywhere.com",
4
+ "smash_config": {
5
+ "pruners": "None",
6
+ "pruning_ratio": 0.0,
7
+ "factorizers": "None",
8
+ "quantizers": "['llm-int8']",
9
+ "weight_quantization_bits": 4,
10
+ "output_deviation": 0.005,
11
+ "compilers": "None",
12
+ "static_batch": true,
13
+ "static_shape": true,
14
+ "controlnet": "None",
15
+ "unet_dim": 4,
16
+ "device": "cuda",
17
+ "cache_dir": "/ceph/hdd/staff/charpent/.cache/models1ogh7zr5",
18
+ "batch_size": 1,
19
+ "model_name": "MILVLG/imp-v1-3b",
20
+ "task": "text_text_generation",
21
+ "max_batch_size": 1,
22
+ "qtype_weight": "torch.qint8",
23
+ "qtype_activation": "torch.quint8",
24
+ "qobserver": "<class 'torch.ao.quantization.observer.MinMaxObserver'>",
25
+ "qscheme": "torch.per_tensor_symmetric",
26
+ "qconfig": "x86",
27
+ "group_size": 128,
28
+ "damp_percent": 0.1,
29
+ "save_load_fn": "bitsandbytes"
30
+ }
31
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|endoftext|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "50256": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "50257": {
14
+ "content": " ",
15
+ "lstrip": false,
16
+ "normalized": true,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": false
20
+ },
21
+ "50258": {
22
+ "content": " ",
23
+ "lstrip": false,
24
+ "normalized": true,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": false
28
+ },
29
+ "50259": {
30
+ "content": " ",
31
+ "lstrip": false,
32
+ "normalized": true,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": false
36
+ },
37
+ "50260": {
38
+ "content": " ",
39
+ "lstrip": false,
40
+ "normalized": true,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": false
44
+ },
45
+ "50261": {
46
+ "content": " ",
47
+ "lstrip": false,
48
+ "normalized": true,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": false
52
+ },
53
+ "50262": {
54
+ "content": " ",
55
+ "lstrip": false,
56
+ "normalized": true,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": false
60
+ },
61
+ "50263": {
62
+ "content": " ",
63
+ "lstrip": false,
64
+ "normalized": true,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": false
68
+ },
69
+ "50264": {
70
+ "content": " ",
71
+ "lstrip": false,
72
+ "normalized": true,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": false
76
+ },
77
+ "50265": {
78
+ "content": " ",
79
+ "lstrip": false,
80
+ "normalized": true,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": false
84
+ },
85
+ "50266": {
86
+ "content": " ",
87
+ "lstrip": false,
88
+ "normalized": true,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": false
92
+ },
93
+ "50267": {
94
+ "content": " ",
95
+ "lstrip": false,
96
+ "normalized": true,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": false
100
+ },
101
+ "50268": {
102
+ "content": " ",
103
+ "lstrip": false,
104
+ "normalized": true,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": false
108
+ },
109
+ "50269": {
110
+ "content": " ",
111
+ "lstrip": false,
112
+ "normalized": true,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": false
116
+ },
117
+ "50270": {
118
+ "content": " ",
119
+ "lstrip": false,
120
+ "normalized": true,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "50271": {
126
+ "content": " ",
127
+ "lstrip": false,
128
+ "normalized": true,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "50272": {
134
+ "content": " ",
135
+ "lstrip": false,
136
+ "normalized": true,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "50273": {
142
+ "content": " ",
143
+ "lstrip": false,
144
+ "normalized": true,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "50274": {
150
+ "content": " ",
151
+ "lstrip": false,
152
+ "normalized": true,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "50275": {
158
+ "content": " ",
159
+ "lstrip": false,
160
+ "normalized": true,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "50276": {
166
+ "content": " ",
167
+ "lstrip": false,
168
+ "normalized": true,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "50277": {
174
+ "content": " ",
175
+ "lstrip": false,
176
+ "normalized": true,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "50278": {
182
+ "content": " ",
183
+ "lstrip": false,
184
+ "normalized": true,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "50279": {
190
+ "content": " ",
191
+ "lstrip": false,
192
+ "normalized": true,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "50280": {
198
+ "content": " ",
199
+ "lstrip": false,
200
+ "normalized": true,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "50281": {
206
+ "content": " ",
207
+ "lstrip": false,
208
+ "normalized": true,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ },
213
+ "50282": {
214
+ "content": " ",
215
+ "lstrip": false,
216
+ "normalized": true,
217
+ "rstrip": false,
218
+ "single_word": false,
219
+ "special": false
220
+ },
221
+ "50283": {
222
+ "content": " ",
223
+ "lstrip": false,
224
+ "normalized": true,
225
+ "rstrip": false,
226
+ "single_word": false,
227
+ "special": false
228
+ },
229
+ "50284": {
230
+ "content": " ",
231
+ "lstrip": false,
232
+ "normalized": true,
233
+ "rstrip": false,
234
+ "single_word": false,
235
+ "special": false
236
+ },
237
+ "50285": {
238
+ "content": " ",
239
+ "lstrip": false,
240
+ "normalized": true,
241
+ "rstrip": false,
242
+ "single_word": false,
243
+ "special": false
244
+ },
245
+ "50286": {
246
+ "content": " ",
247
+ "lstrip": false,
248
+ "normalized": true,
249
+ "rstrip": false,
250
+ "single_word": false,
251
+ "special": false
252
+ },
253
+ "50287": {
254
+ "content": "\t\t\t\t\t\t\t\t\t",
255
+ "lstrip": false,
256
+ "normalized": true,
257
+ "rstrip": false,
258
+ "single_word": false,
259
+ "special": false
260
+ },
261
+ "50288": {
262
+ "content": "\t\t\t\t\t\t\t\t",
263
+ "lstrip": false,
264
+ "normalized": true,
265
+ "rstrip": false,
266
+ "single_word": false,
267
+ "special": false
268
+ },
269
+ "50289": {
270
+ "content": "\t\t\t\t\t\t\t",
271
+ "lstrip": false,
272
+ "normalized": true,
273
+ "rstrip": false,
274
+ "single_word": false,
275
+ "special": false
276
+ },
277
+ "50290": {
278
+ "content": "\t\t\t\t\t\t",
279
+ "lstrip": false,
280
+ "normalized": true,
281
+ "rstrip": false,
282
+ "single_word": false,
283
+ "special": false
284
+ },
285
+ "50291": {
286
+ "content": "\t\t\t\t\t",
287
+ "lstrip": false,
288
+ "normalized": true,
289
+ "rstrip": false,
290
+ "single_word": false,
291
+ "special": false
292
+ },
293
+ "50292": {
294
+ "content": "\t\t\t\t",
295
+ "lstrip": false,
296
+ "normalized": true,
297
+ "rstrip": false,
298
+ "single_word": false,
299
+ "special": false
300
+ },
301
+ "50293": {
302
+ "content": "\t\t\t",
303
+ "lstrip": false,
304
+ "normalized": true,
305
+ "rstrip": false,
306
+ "single_word": false,
307
+ "special": false
308
+ },
309
+ "50294": {
310
+ "content": "\t\t",
311
+ "lstrip": false,
312
+ "normalized": true,
313
+ "rstrip": false,
314
+ "single_word": false,
315
+ "special": false
316
+ },
317
+ "50295": {
318
+ "content": "</s>",
319
+ "lstrip": false,
320
+ "normalized": false,
321
+ "rstrip": false,
322
+ "single_word": false,
323
+ "special": true
324
+ },
325
+ "50296": {
326
+ "content": "<image>",
327
+ "lstrip": false,
328
+ "normalized": false,
329
+ "rstrip": false,
330
+ "single_word": false,
331
+ "special": true
332
+ }
333
+ },
334
+ "bos_token": "<|endoftext|>",
335
+ "clean_up_tokenization_spaces": true,
336
+ "eos_token": "<|endoftext|>",
337
+ "errors": "replace",
338
+ "legacy": false,
339
+ "model_max_length": 3072,
340
+ "pad_token": null,
341
+ "return_token_type_ids": false,
342
+ "tokenizer_class": "CodeGenTokenizer",
343
+ "unk_token": "<|endoftext|>"
344
+ }
vision_encoder.py ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 (shaozw@hdu.edu.cn) @ 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 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.vision_model.post_layernorm=nn.Identity()
553
+ self.vision_tower.requires_grad_(False)
554
+ self.vision_tower.eval()
555
+
556
+ self.is_loaded = True
557
+
558
+ @torch.no_grad()
559
+ def forward(self, images):
560
+ if type(images) is list:
561
+ image_features = []
562
+ for image in images:
563
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
564
+ image_feature = image_forward_out.hidden_states[-1].to(image.dtype)
565
+ assert image_features.shape[-2] == 729
566
+ image_features.append(image_feature)
567
+ else:
568
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
569
+ image_features = image_forward_outs.hidden_states[-1].to(images.dtype)
570
+ assert image_features.shape[-2] == 729
571
+
572
+ return image_features
573
+
574
+ @property
575
+ def dummy_feature(self):
576
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
577
+
578
+ @property
579
+ def dtype(self):
580
+ for p in self.vision_tower.parameters():
581
+ return p.dtype
582
+
583
+ @property
584
+ def device(self):
585
+ for p in self.vision_tower.parameters():
586
+ return p.device
587
+
588
+ @property
589
+ def hidden_size(self):
590
+ return self.config.hidden_size
591
+
592
+ @property
593
+ def num_patches(self):
594
+ 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