Isotr0py commited on
Commit
cea6bc5
1 Parent(s): a53569b

Upload 10 files

Browse files
config.json ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/root/.cache/huggingface/hub/models--microsoft--Phi-3.5-vision-instruct/snapshots/ee47981071d28a0f08c1ab22c0337d5d22184dab",
3
+ "architectures": [
4
+ "Phi3VForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi3_v.Phi3VConfig",
9
+ "AutoModelForCausalLM": "modeling_phi3_v.Phi3VForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "embd_layer": {
13
+ "embedding_cls": "image",
14
+ "hd_transform_order": "sub_glb",
15
+ "projection_cls": "mlp",
16
+ "use_hd_transform": true,
17
+ "with_learnable_separator": true
18
+ },
19
+ "embd_pdrop": 0.0,
20
+ "eos_token_id": 2,
21
+ "hidden_act": "silu",
22
+ "hidden_size": 3072,
23
+ "img_processor": {
24
+ "image_dim_out": 1024,
25
+ "model_name": "openai/clip-vit-large-patch14-336",
26
+ "name": "clip_vision_model",
27
+ "num_img_tokens": 144
28
+ },
29
+ "initializer_range": 0.02,
30
+ "intermediate_size": 8192,
31
+ "max_position_embeddings": 131072,
32
+ "model_type": "phi3_v",
33
+ "num_attention_heads": 32,
34
+ "num_hidden_layers": 32,
35
+ "num_key_value_heads": 32,
36
+ "original_max_position_embeddings": 4096,
37
+ "pad_token_id": 32000,
38
+ "quantization_config": {
39
+ "bits": 4,
40
+ "group_size": 128,
41
+ "modules_to_not_convert": [
42
+ "vision_embed_tokens"
43
+ ],
44
+ "quant_method": "awq",
45
+ "version": "gemm",
46
+ "zero_point": true
47
+ },
48
+ "resid_pdrop": 0.0,
49
+ "rms_norm_eps": 1e-05,
50
+ "rope_scaling": {
51
+ "long_factor": [
52
+ 1.0800000429153442,
53
+ 1.1100000143051147,
54
+ 1.1399999856948853,
55
+ 1.340000033378601,
56
+ 1.5899999141693115,
57
+ 1.600000023841858,
58
+ 1.6200000047683716,
59
+ 2.620000123977661,
60
+ 3.2300000190734863,
61
+ 3.2300000190734863,
62
+ 4.789999961853027,
63
+ 7.400000095367432,
64
+ 7.700000286102295,
65
+ 9.09000015258789,
66
+ 12.199999809265137,
67
+ 17.670000076293945,
68
+ 24.46000099182129,
69
+ 28.57000160217285,
70
+ 30.420001983642578,
71
+ 30.840002059936523,
72
+ 32.590003967285156,
73
+ 32.93000411987305,
74
+ 42.320003509521484,
75
+ 44.96000289916992,
76
+ 50.340003967285156,
77
+ 50.45000457763672,
78
+ 57.55000305175781,
79
+ 57.93000411987305,
80
+ 58.21000289916992,
81
+ 60.1400032043457,
82
+ 62.61000442504883,
83
+ 62.62000274658203,
84
+ 62.71000289916992,
85
+ 63.1400032043457,
86
+ 63.1400032043457,
87
+ 63.77000427246094,
88
+ 63.93000411987305,
89
+ 63.96000289916992,
90
+ 63.970001220703125,
91
+ 64.02999877929688,
92
+ 64.06999969482422,
93
+ 64.08000183105469,
94
+ 64.12000274658203,
95
+ 64.41000366210938,
96
+ 64.4800033569336,
97
+ 64.51000213623047,
98
+ 64.52999877929688,
99
+ 64.83999633789062
100
+ ],
101
+ "short_factor": [
102
+ 1.08,
103
+ 1.1,
104
+ 1.1300000000000001,
105
+ 1.2800000000000002,
106
+ 1.3100000000000003,
107
+ 1.4500000000000004,
108
+ 1.4500000000000004,
109
+ 1.9500000000000008,
110
+ 2.030000000000001,
111
+ 2.4299999999999926,
112
+ 2.5699999999999896,
113
+ 2.9499999999999815,
114
+ 3.729999999999965,
115
+ 3.869999999999962,
116
+ 4.189999999999955,
117
+ 4.43999999999995,
118
+ 4.6399999999999455,
119
+ 4.979999999999938,
120
+ 5.159999999999934,
121
+ 5.279999999999932,
122
+ 5.759999999999922,
123
+ 5.889999999999919,
124
+ 5.889999999999919,
125
+ 5.969999999999917,
126
+ 6.089999999999915,
127
+ 6.2799999999999105,
128
+ 6.7699999999999,
129
+ 6.8899999999998975,
130
+ 7.109999999999893,
131
+ 7.129999999999892,
132
+ 7.179999999999891,
133
+ 7.289999999999889,
134
+ 7.339999999999888,
135
+ 7.559999999999883,
136
+ 7.619999999999882,
137
+ 7.69999999999988,
138
+ 7.879999999999876,
139
+ 7.879999999999876,
140
+ 7.879999999999876,
141
+ 7.939999999999875,
142
+ 7.949999999999875,
143
+ 7.979999999999874,
144
+ 8.19999999999987,
145
+ 8.439999999999864,
146
+ 8.469999999999864,
147
+ 8.589999999999861,
148
+ 8.809999999999857,
149
+ 8.999999999999853
150
+ ],
151
+ "type": "su"
152
+ },
153
+ "rope_theta": 10000.0,
154
+ "sliding_window": 262144,
155
+ "tie_word_embeddings": false,
156
+ "torch_dtype": "float16",
157
+ "transformers_version": "4.44.1",
158
+ "use_cache": false,
159
+ "vocab_size": 32064
160
+ }
configuration_phi3_v.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ Phi-3-V model configuration"""
17
+
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ PHI3V_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "microsoft/Phi-3-vision-128k-instruct": "https://huggingface.co/microsoft/Phi-3-vision-128k-instruct/resolve/main/config.json",
27
+ "microsoft/Phi-3.5-vision-instruct": "https://huggingface.co/microsoft/Phi-3.5-vision-instruct/resolve/main/config.json",
28
+ }
29
+
30
+
31
+ class Phi3VConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`Phi3VModel`]. It is used to instantiate a Phi-3
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the
36
+ [microsoft/Phi-3-vision-128k-instruct](https://huggingface.co/microsoft/Phi-3-vision-128k-instruct).
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32064):
43
+ Vocabulary size of the Phi-3-V model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`Phi3VModel`].
45
+ hidden_size (`int`, *optional*, defaults to 3072):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 8192):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
62
+ Dropout probability for mlp outputs.
63
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
64
+ The dropout ratio for the embeddings.
65
+ attention_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio after computing the attention scores.
67
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
68
+ The non-linear activation function (function or string) in the decoder.
69
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
70
+ The maximum sequence length that this model might ever be used with.
71
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
72
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
73
+ original RoPE embeddings when using long scaling.
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
77
+ The epsilon value used for the RMSNorm.
78
+ use_cache (`bool`, *optional*, defaults to `True`):
79
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
80
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
+ Whether to tie weight embeddings
83
+ rope_theta (`float`, *optional*, defaults to 10000.0):
84
+ The base period of the RoPE embeddings.
85
+ rope_scaling (`dict`, *optional*):
86
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
87
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be either `su` or `yarn` and
88
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
89
+ divided by the number of attention heads divided by 2.
90
+ bos_token_id (`int`, *optional*, defaults to 1):
91
+ The id of the "beginning-of-sequence" token.
92
+ eos_token_id (`int`, *optional*, defaults to 32000):
93
+ The id of the "end-of-sequence" token.
94
+ pad_token_id (`int`, *optional*, defaults to 32000):
95
+ The id of the padding token.
96
+ sliding_window (`int`, *optional*):
97
+ Sliding window attention window size. If `None`, no sliding window is applied.
98
+ embd_layer (`str`, *optional*, defaults to `"default"`):
99
+ The embedding layer to use. Can be either `"default"` or `"image"`. "default" uses the standard embedding for text.
100
+
101
+ Example:
102
+
103
+ ```python
104
+ >>> from transformers import Phi3VModel, Phi3VConfig
105
+
106
+ >>> # Initializing a Phi-3-V style configuration
107
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-vision-128k-instruct")
108
+
109
+ >>> # Initializing a model from the configuration
110
+ >>> model = Phi3VModel(configuration)
111
+
112
+ >>> # Accessing the model configuration
113
+ >>> configuration = model.config
114
+ ```"""
115
+
116
+ model_type = "phi3_v"
117
+ keys_to_ignore_at_inference = ["past_key_values"]
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_size=32064,
122
+ hidden_size=3072,
123
+ intermediate_size=8192,
124
+ num_hidden_layers=32,
125
+ num_attention_heads=32,
126
+ num_key_value_heads=None,
127
+ resid_pdrop=0.0,
128
+ embd_pdrop=0.0,
129
+ attention_dropout=0.0,
130
+ hidden_act="silu",
131
+ max_position_embeddings=4096,
132
+ original_max_position_embeddings=4096,
133
+ initializer_range=0.02,
134
+ rms_norm_eps=1e-5,
135
+ use_cache=True,
136
+ tie_word_embeddings=False,
137
+ rope_theta=10000.0,
138
+ rope_scaling=None,
139
+ bos_token_id=1,
140
+ eos_token_id=32000,
141
+ pad_token_id=32000,
142
+ sliding_window=None,
143
+ embd_layer: str = "default",
144
+ **kwargs,
145
+ ):
146
+ self.vocab_size = vocab_size
147
+ self.hidden_size = hidden_size
148
+ self.intermediate_size = intermediate_size
149
+ self.num_hidden_layers = num_hidden_layers
150
+ self.num_attention_heads = num_attention_heads
151
+
152
+ if num_key_value_heads is None:
153
+ num_key_value_heads = num_attention_heads
154
+
155
+ self.num_key_value_heads = num_key_value_heads
156
+ self.resid_pdrop = resid_pdrop
157
+ self.embd_pdrop = embd_pdrop
158
+ self.attention_dropout = attention_dropout
159
+ self.hidden_act = hidden_act
160
+ self.max_position_embeddings = max_position_embeddings
161
+ self.original_max_position_embeddings = original_max_position_embeddings
162
+ self.initializer_range = initializer_range
163
+ self.rms_norm_eps = rms_norm_eps
164
+ self.use_cache = use_cache
165
+ self.rope_theta = rope_theta
166
+ self.rope_scaling = rope_scaling
167
+ self._rope_scaling_validation()
168
+ self.sliding_window = sliding_window
169
+ self.embd_layer = embd_layer
170
+
171
+
172
+ super().__init__(
173
+ bos_token_id=bos_token_id,
174
+ eos_token_id=eos_token_id,
175
+ pad_token_id=pad_token_id,
176
+ tie_word_embeddings=tie_word_embeddings,
177
+ **kwargs,
178
+ )
179
+
180
+ def _rope_scaling_validation(self):
181
+ """
182
+ Validate the `rope_scaling` configuration.
183
+ """
184
+ if self.rope_scaling is None:
185
+ return
186
+
187
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
188
+ raise ValueError(
189
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
190
+ f"got {self.rope_scaling}"
191
+ )
192
+ rope_scaling_type = self.rope_scaling.get("type", None)
193
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
194
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
195
+ if rope_scaling_type is None or rope_scaling_type not in ["su", "yarn"]:
196
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['su', 'yarn'], got {rope_scaling_type}")
197
+ if not (
198
+ isinstance(rope_scaling_short_factor, list)
199
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
200
+ ):
201
+ raise ValueError(
202
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
203
+ )
204
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
205
+ raise ValueError(
206
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
207
+ )
208
+ if not (
209
+ isinstance(rope_scaling_long_factor, list)
210
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
211
+ ):
212
+ raise ValueError(
213
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
214
+ )
215
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
216
+ raise ValueError(
217
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
218
+ )
generation_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "do_sample": true,
5
+ "eos_token_id": 2,
6
+ "pad_token_id": 32000,
7
+ "transformers_version": "4.44.1"
8
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:854cdeb5ac52f045ddf296e6ae0a10eea5983f9e9c9fceda43a4db4357e921f1
3
+ size 3125321560
modeling_phi3_v.py ADDED
@@ -0,0 +1,1935 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ PyTorch Phi-3-V model."""
17
+
18
+ import inspect
19
+ import math
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
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
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_greater_or_equal_2_10,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from .configuration_phi3_v import Phi3VConfig
48
+
49
+ try:
50
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
51
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
52
+
53
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
54
+ except ImportError:
55
+ pass
56
+
57
+ import torch
58
+ from torch import nn
59
+ from transformers import CLIPVisionConfig, CLIPVisionModel, PretrainedConfig
60
+ from transformers.models.clip.modeling_clip import CLIPAttention
61
+ from transformers.utils import logging
62
+
63
+ logger = logging.get_logger(__name__)
64
+
65
+
66
+ MAX_INPUT_ID = int(1e9)
67
+
68
+ CLIP_VIT_LARGE_PATCH14_336_CONFIG = CLIPVisionConfig(
69
+ attention_dropout=0.0,
70
+ dropout=0.0,
71
+ hidden_act="quick_gelu",
72
+ hidden_size=1024,
73
+ image_size=336,
74
+ initializer_factor=1.0,
75
+ initializer_range=0.02,
76
+ intermediate_size=4096,
77
+ layer_norm_eps=1e-05,
78
+ num_attention_heads=16,
79
+ num_channels=3,
80
+ num_hidden_layers=24,
81
+ patch_size=14,
82
+ projection_dim=768
83
+ )
84
+
85
+ class CLIPAttentionFA2(CLIPAttention):
86
+ """Add flash attention 2 to CLIPAttention. (This is only used in the vision encoder)"""
87
+
88
+ def forward(self,
89
+ hidden_states,
90
+ attention_mask=None,
91
+ causal_attention_mask=None,
92
+ output_attentions=False,
93
+ ):
94
+ """Input shape: Batch x Time x Channel"""
95
+
96
+ assert attention_mask is None, "CLIPAttentionFA2 does not support attention_mask"
97
+ assert causal_attention_mask is None, "CLIPAttentionFA2 does not support causal_attention_mask"
98
+ assert output_attentions is False, "CLIPAttentionFA2 does not support output_attentions"
99
+
100
+ bsz, tgt_len, embed_dim = hidden_states.size()
101
+ query_states = self.q_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
102
+ key_states = self.k_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
103
+ value_states = self.v_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
104
+
105
+ attn_output = flash_attn_func(
106
+ query_states,
107
+ key_states,
108
+ value_states,
109
+ dropout_p=self.dropout if self.training else 0.0,
110
+ softmax_scale=self.scale,
111
+ causal=False,
112
+ ).reshape(bsz, tgt_len, embed_dim)
113
+
114
+ attn_output = self.out_proj(attn_output)
115
+ return attn_output, None
116
+
117
+
118
+ class Phi3ImageEmbedding(nn.Module):
119
+ """Phi3 Image embedding."""
120
+
121
+ def __init__(self, config: PretrainedConfig, wte=None, **kwargs) -> None:
122
+ super().__init__()
123
+
124
+ # n_embed or hidden_size
125
+ hidden_size = config.n_embd if hasattr(config, 'n_embd') else config.hidden_size
126
+ if hasattr(config, 'embd_pdrop') or hasattr(config, 'embed_pdrop'):
127
+ embd_drop = config.embd_pdrop if hasattr(config, 'embd_pdrop') else config.embed_pdrop
128
+ self.drop = nn.Dropout(embd_drop)
129
+ else:
130
+ self.drop = None
131
+
132
+ self.wte = wte
133
+
134
+ if isinstance(config.img_processor, dict) and config.img_processor.get('name', None) == 'clip_vision_model':
135
+ assert 'model_name' in config.img_processor, 'model_name must be provided for CLIPVisionModel'
136
+ assert 'image_dim_out' in config.img_processor, 'image_dim_out must be provided for CLIPVisionModel'
137
+ assert 'num_img_tokens' in config.img_processor, 'num_img_tokens must be provided for CLIPVisionModel'
138
+ assert config.img_processor['model_name'] == 'openai/clip-vit-large-patch14-336'
139
+ clip_config = CLIP_VIT_LARGE_PATCH14_336_CONFIG
140
+ self.img_processor = CLIPVisionModel(clip_config)
141
+ image_dim_out = config.img_processor['image_dim_out']
142
+ self.num_img_tokens = config.img_processor['num_img_tokens']
143
+
144
+ # FA2 in CLIP
145
+ if config._attn_implementation == 'flash_attention_2':
146
+ for layer in self.img_processor.vision_model.encoder.layers:
147
+ clip_fa2 = CLIPAttentionFA2(clip_config)
148
+ del layer.self_attn
149
+ layer.self_attn = clip_fa2
150
+ else:
151
+ raise NotImplementedError(f'img_processor = {config.img_processor}, not implemented')
152
+
153
+ self.image_dim_out = image_dim_out
154
+ self.img_sizes = None
155
+
156
+ # global_gn and sub_gn for hd transform, serves as line separator
157
+ self.use_hd_transform = kwargs.get('use_hd_transform', False)
158
+ self.with_learnable_separator = kwargs.get('with_learnable_separator', False)
159
+ self.hd_transform_order = kwargs.get('hd_transform_order', 'glb_sub')
160
+ # with_hd_transform and with_learnable_separator should have same value
161
+ assert self.use_hd_transform == self.with_learnable_separator, 'use_hd_transform and with_learnable_separator should have same value'
162
+ if self.with_learnable_separator:
163
+ assert self.use_hd_transform, 'learnable separator is only for hd transform'
164
+ # 1024 * 4, merge spatial to channel dimension
165
+ self.glb_GN = nn.Parameter(torch.zeros([1, 1, self.image_dim_out * 4]))
166
+ self.sub_GN = nn.Parameter(torch.zeros([1, 1, 1, self.image_dim_out * 4]))
167
+ logger.info(f'learnable separator enabled for hd transform, hd_transform_order = {self.hd_transform_order}')
168
+
169
+ projection_cls = kwargs.get('projection_cls', 'linear')
170
+ if projection_cls == 'linear':
171
+ self.img_projection = nn.Linear(image_dim_out, hidden_size)
172
+ elif projection_cls == 'mlp' and self.use_hd_transform:
173
+ dim_projection = hidden_size
174
+ depth = 2
175
+ layers = [nn.Linear(image_dim_out * 4, dim_projection)]
176
+ for _ in range(1, depth):
177
+ layers.extend([nn.GELU(),
178
+ nn.Linear(dim_projection, dim_projection)])
179
+ self.img_projection = nn.Sequential(*layers)
180
+ elif projection_cls == 'mlp':
181
+ dim_projection = hidden_size
182
+ depth = 2
183
+ layers = [nn.Linear(image_dim_out, dim_projection)]
184
+ for _ in range(1, depth):
185
+ layers.extend([nn.GELU(),
186
+ nn.Linear(dim_projection, dim_projection)])
187
+ self.img_projection = nn.Sequential(*layers)
188
+ else:
189
+ raise NotImplementedError(f'projection_cls = {projection_cls}, not implemented')
190
+
191
+ self.vocab_size = config.vocab_size
192
+ self.img_features = None
193
+
194
+ if isinstance(config.img_processor, dict):
195
+ self.layer_idx = config.img_processor.get('layer_idx', -2)
196
+ self.type_feature = config.img_processor.get('type_feature', 'patch')
197
+ else:
198
+ self.layer_idx = -2
199
+ self.type_feature = 'patch'
200
+
201
+
202
+ def set_img_features(self, img_features: torch.FloatTensor) -> None:
203
+ self.img_features = img_features
204
+
205
+ def set_img_sizes(self, img_sizes: torch.LongTensor) -> None:
206
+ self.img_sizes = img_sizes
207
+
208
+ def get_img_features(self, img_embeds: torch.FloatTensor) -> torch.FloatTensor:
209
+ LAYER_IDX = self.layer_idx
210
+ TYPE_FEATURE = self.type_feature
211
+
212
+ img_processor_output = self.img_processor(img_embeds, output_hidden_states=True)
213
+ img_feature = img_processor_output.hidden_states[LAYER_IDX]
214
+
215
+ if TYPE_FEATURE == "patch":
216
+ patch_feature = img_feature[:, 1:]
217
+ return patch_feature
218
+
219
+ raise NotImplementedError
220
+
221
+ def forward(
222
+ self, input_ids: torch.LongTensor, pixel_values: torch.FloatTensor, image_sizes=None
223
+ ) -> torch.FloatTensor:
224
+ input_shape = input_ids.size()
225
+ input_ids = input_ids.view(-1, input_shape[-1])
226
+
227
+ # positions for image tokens
228
+ positions = torch.nonzero((input_ids < 0) & (input_ids > -MAX_INPUT_ID), as_tuple=True)
229
+ has_image = len(positions[0].tolist()) > 0
230
+ input_ids = input_ids.clamp_min(0).clamp_max(self.vocab_size).detach()
231
+ hidden_states = self.wte(input_ids)
232
+
233
+ if has_image:
234
+ assert self.use_hd_transform
235
+ num_images, num_crops, c, h, w = pixel_values.shape
236
+ assert c == 3 and h == w == 336
237
+ img_features = self.get_img_features(pixel_values.flatten(0, 1)).reshape(
238
+ num_images, num_crops, -1, self.image_dim_out
239
+ )
240
+ image_features_proj = self.hd_feature_transform(img_features, image_sizes)
241
+ hidden_states = hidden_states.index_put(
242
+ positions, image_features_proj, accumulate=False
243
+ )
244
+
245
+ if self.drop is not None:
246
+ hidden_states = self.drop(hidden_states)
247
+
248
+ return hidden_states
249
+
250
+ def hd_feature_transform(self, image_features, image_sizes):
251
+ """
252
+ image_features: (num_images, num_crops+1, 24*24, 1024)
253
+ """
254
+ assert (
255
+ self.hd_transform_order == 'sub_glb'
256
+ ), f'hd_transform_order `{self.hd_transform_order}` not implemented'
257
+ if isinstance(self.img_projection, nn.Sequential):
258
+ target_device = self.img_projection[0].bias.device
259
+ target_dtype = self.img_projection[0].bias.dtype
260
+ else: # It's a single nn.Linear layer
261
+ target_device = self.img_projection.bias.device
262
+ target_dtype = self.img_projection.bias.dtype
263
+
264
+ global_image_features = image_features[:, 0] # (num_images, 24*24, 1024)
265
+ # global feature can be viewed as a special HD case with num_crops 1x1
266
+ global_image_features_hd = self.reshape_hd_patches_2x2merge(global_image_features, 1, 1)
267
+ global_image_features_hd_newline = self.add_image_newline(global_image_features_hd)
268
+
269
+ all_image_embeddings = []
270
+ # need a for loop to process each image because of different image sizes
271
+ # (patch arrangement is different for each image)
272
+ for i, img_size in enumerate(image_sizes):
273
+ h, w = img_size
274
+ h_crop = h // 336
275
+ w_crop = w // 336
276
+ num_crops = h_crop * w_crop
277
+
278
+ # NOTE: real num_crops is padded
279
+ # (num_crops, 24*24, 1024)
280
+ sub_image_features = image_features[i, 1 : 1 + num_crops]
281
+ sub_image_features_hd = self.reshape_hd_patches_2x2merge(
282
+ sub_image_features, h_crop, w_crop
283
+ )
284
+ sub_image_features_hd_newline = self.add_image_newline(sub_image_features_hd)
285
+
286
+ # [sub features, separator, global features]
287
+ all_image_embeddings.extend(
288
+ [
289
+ sub_image_features_hd_newline.squeeze(0), # (h_crop*12*(w_crop*12+1), 4096)
290
+ self.glb_GN.squeeze(0),
291
+ global_image_features_hd_newline[i],
292
+ ]
293
+ )
294
+
295
+ image_features_proj = self.img_projection(
296
+ torch.cat(all_image_embeddings, dim=0).to(target_device).to(target_dtype)
297
+ )
298
+
299
+ return image_features_proj
300
+
301
+ def reshape_hd_patches_2x2merge(self, image_features, h_crop, w_crop):
302
+ """
303
+ image_features: (num_images*num_crops, 24*24, 1024)
304
+ output: (num_images, h_crop*12, w_crop*12, 4096), h_crop*w_crop == num_crops
305
+ """
306
+ N, L, C = image_features.shape
307
+ assert L == 24 * 24 and C == 1024 and N % (h_crop * w_crop) == 0
308
+ num_images = N // (h_crop * w_crop)
309
+ H = int(L**0.5)
310
+ image_features_hd = (
311
+ image_features.reshape(N, H, H, C) # N, 24, 24, 1024
312
+ .reshape(N, H // 2, 2, H // 2, 2, C) # N, 12, 2, 12, 2, 1024
313
+ .permute(0, 1, 3, 2, 4, 5) # N, 12, 12, 2, 2, 1024
314
+ .reshape(N, -1, 4 * C) # N, 144, 4096
315
+ .reshape(
316
+ num_images, h_crop, w_crop, H // 2, H // 2, -1
317
+ ) # n_img, h_crop, w_crop, 12, 12, 4096
318
+ .permute(0, 1, 3, 2, 4, 5) # n_img, h_crop, 12, w_crop, 12, 4096
319
+ .reshape(
320
+ num_images, h_crop * H // 2, w_crop * H // 2, 4 * C
321
+ ) # n_img, h_crop*12, w_crop*12, 4096
322
+ )
323
+
324
+ # alternative implementation using einops
325
+ # from einops import rearrange
326
+ # image_features_nhwc = rearrange(
327
+ # image_features,
328
+ # 'N (H W) c -> N H W c',
329
+ # H=H,
330
+ # W=H,
331
+ # )
332
+ # image_features_2x2merge = rearrange(
333
+ # image_features_nhwc,
334
+ # 'N (h h_pool) (w w_pool) c -> N h w (h_pool w_pool c)',
335
+ # h_pool=2,
336
+ # w_pool=2,
337
+ # )
338
+ # image_features_hd = rearrange(
339
+ # image_features_2x2merge,
340
+ # '(n_img h_crop w_crop) h w C -> n_img (h_crop h) (w_crop w) C',
341
+ # h_crop=h_crop,
342
+ # w_crop=w_crop,
343
+ # )
344
+
345
+ return image_features_hd
346
+
347
+ def add_image_newline(self, image_features_hd):
348
+ """
349
+ image_features_hd: (num_images, h_crop*12, w_crop*12, 4096)
350
+ output: (num_images, (h_crop*12) * (w_crop*12+1), 4096)
351
+ """
352
+ num_images, h, w, hid_dim = image_features_hd.shape
353
+ # add the newline token to the HD image feature patches
354
+ newline_embeddings = self.sub_GN.expand(num_images, h, -1, -1) # (n_img, h, 1, hid_dim)
355
+ image_features_hd_newline = torch.cat(
356
+ [image_features_hd, newline_embeddings], dim=2
357
+ ).reshape(num_images, -1, hid_dim)
358
+ return image_features_hd_newline
359
+
360
+
361
+ logger = logging.get_logger(__name__)
362
+
363
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-vision-128k-instruct"
364
+ _CONFIG_FOR_DOC = "Phi3VConfig"
365
+
366
+ PHI3V_PRETRAINED_MODEL_ARCHIVE_LIST = [
367
+ "microsoft/Phi-3-vision-128k-instruct",
368
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
369
+ ]
370
+
371
+
372
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
373
+ class Phi3RMSNorm(nn.Module):
374
+ def __init__(self, hidden_size, eps=1e-6):
375
+ """
376
+ Phi3RMSNorm is equivalent to T5LayerNorm
377
+ """
378
+ super().__init__()
379
+ self.weight = nn.Parameter(torch.ones(hidden_size))
380
+ self.variance_epsilon = eps
381
+
382
+ def forward(self, hidden_states):
383
+ input_dtype = hidden_states.dtype
384
+ hidden_states = hidden_states.to(torch.float32)
385
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
386
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
387
+ return self.weight * hidden_states.to(input_dtype)
388
+
389
+
390
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
391
+ def _get_unpad_data(attention_mask):
392
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
393
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
394
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
395
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
396
+ return (
397
+ indices,
398
+ cu_seqlens,
399
+ max_seqlen_in_batch,
400
+ )
401
+
402
+
403
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
404
+ class Phi3RotaryEmbedding(nn.Module):
405
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
406
+ super().__init__()
407
+
408
+ self.dim = dim
409
+ self.max_position_embeddings = max_position_embeddings
410
+ self.base = base
411
+ self.register_buffer("inv_freq", None, persistent=False)
412
+
413
+ @torch.no_grad()
414
+ def forward(self, x, position_ids, seq_len=None):
415
+ # x: [bs, num_attention_heads, seq_len, head_size]
416
+ if self.inv_freq is None:
417
+ self.inv_freq = 1.0 / (
418
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
419
+ )
420
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
421
+ position_ids_expanded = position_ids[:, None, :].float()
422
+ # Force float32 since bfloat16 loses precision on long contexts
423
+ # See https://github.com/huggingface/transformers/pull/29285
424
+ device_type = x.device.type
425
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
426
+ with torch.autocast(device_type=device_type, enabled=False):
427
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
428
+ emb = torch.cat((freqs, freqs), dim=-1)
429
+ cos = emb.cos()
430
+ sin = emb.sin()
431
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
432
+
433
+
434
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
435
+ def __init__(self, dim, config, device=None):
436
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
437
+
438
+ self.short_factor = config.rope_scaling["short_factor"]
439
+ self.long_factor = config.rope_scaling["long_factor"]
440
+ self.original_max_position_embeddings = config.original_max_position_embeddings
441
+
442
+ @torch.no_grad()
443
+ def forward(self, x, position_ids, seq_len=None):
444
+ seq_len = torch.max(position_ids) + 1
445
+ if seq_len > self.original_max_position_embeddings:
446
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
447
+ else:
448
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
449
+
450
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
451
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
452
+
453
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
454
+ position_ids_expanded = position_ids[:, None, :].float()
455
+
456
+ # Force float32 since bfloat16 loses precision on long contexts
457
+ # See https://github.com/huggingface/transformers/pull/29285
458
+ device_type = x.device.type
459
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
460
+ with torch.autocast(device_type=device_type, enabled=False):
461
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
462
+ emb = torch.cat((freqs, freqs), dim=-1)
463
+
464
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
465
+ if scale <= 1.0:
466
+ scaling_factor = 1.0
467
+ else:
468
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
469
+
470
+ cos = emb.cos() * scaling_factor
471
+ sin = emb.sin() * scaling_factor
472
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
473
+
474
+
475
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
476
+ def __init__(self, dim, config, device=None):
477
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
478
+
479
+ self.short_factor = config.rope_scaling["short_factor"]
480
+ self.long_factor = config.rope_scaling["long_factor"]
481
+ self.original_max_position_embeddings = config.original_max_position_embeddings
482
+
483
+ @torch.no_grad()
484
+ def forward(self, x, position_ids, seq_len=None):
485
+ seq_len = torch.max(position_ids) + 1
486
+ if seq_len > self.original_max_position_embeddings:
487
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
488
+ else:
489
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
490
+
491
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
492
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
493
+
494
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
495
+ position_ids_expanded = position_ids[:, None, :].float()
496
+
497
+ # Force float32 since bfloat16 loses precision on long contexts
498
+ # See https://github.com/huggingface/transformers/pull/29285
499
+ device_type = x.device.type
500
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
501
+ with torch.autocast(device_type=device_type, enabled=False):
502
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
503
+ emb = torch.cat((freqs, freqs), dim=-1)
504
+
505
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
506
+ if scale <= 1.0:
507
+ scaling_factor = 1.0
508
+ else:
509
+ scaling_factor = 0.1 * math.log(scale) + 1.0
510
+
511
+ cos = emb.cos() * scaling_factor
512
+ sin = emb.sin() * scaling_factor
513
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
514
+
515
+
516
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
517
+ def rotate_half(x):
518
+ """Rotates half the hidden dims of the input."""
519
+ x1 = x[..., : x.shape[-1] // 2]
520
+ x2 = x[..., x.shape[-1] // 2 :]
521
+ return torch.cat((-x2, x1), dim=-1)
522
+
523
+
524
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
525
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
526
+ """Applies Rotary Position Embedding to the query and key tensors.
527
+
528
+ Args:
529
+ q (`torch.Tensor`): The query tensor.
530
+ k (`torch.Tensor`): The key tensor.
531
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
532
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
533
+ position_ids (`torch.Tensor`, *optional*):
534
+ Deprecated and unused.
535
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
536
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
537
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
538
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
539
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
540
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
541
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
542
+ Returns:
543
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
544
+ """
545
+ cos = cos.unsqueeze(unsqueeze_dim)
546
+ sin = sin.unsqueeze(unsqueeze_dim)
547
+ q_embed = (q * cos) + (rotate_half(q) * sin)
548
+ k_embed = (k * cos) + (rotate_half(k) * sin)
549
+ return q_embed, k_embed
550
+
551
+
552
+ class Phi3MLP(nn.Module):
553
+ def __init__(self, config):
554
+ super().__init__()
555
+
556
+ self.config = config
557
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
558
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
559
+
560
+ self.activation_fn = ACT2FN[config.hidden_act]
561
+
562
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
563
+ up_states = self.gate_up_proj(hidden_states)
564
+
565
+ gate, up_states = up_states.chunk(2, dim=-1)
566
+ up_states = up_states * self.activation_fn(gate)
567
+
568
+ return self.down_proj(up_states)
569
+
570
+
571
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
572
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
573
+ """
574
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
575
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
576
+ """
577
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
578
+ if n_rep == 1:
579
+ return hidden_states
580
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
581
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
582
+
583
+
584
+ class Phi3Attention(nn.Module):
585
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
586
+
587
+ def __init__(self, config: Phi3VConfig, layer_idx: Optional[int] = None):
588
+ super().__init__()
589
+ self.config = config
590
+ self.layer_idx = layer_idx
591
+ if layer_idx is None:
592
+ logger.warning_once(
593
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
594
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
595
+ "when creating this class."
596
+ )
597
+
598
+ self.attention_dropout = config.attention_dropout
599
+ self.hidden_size = config.hidden_size
600
+ self.num_heads = config.num_attention_heads
601
+ self.head_dim = self.hidden_size // self.num_heads
602
+ self.num_key_value_heads = config.num_key_value_heads
603
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
604
+ self.max_position_embeddings = config.max_position_embeddings
605
+ self.original_max_position_embeddings = config.original_max_position_embeddings
606
+ self.rope_theta = config.rope_theta
607
+ self.rope_scaling = config.rope_scaling
608
+ self.is_causal = True
609
+
610
+ if (self.head_dim * self.num_heads) != self.hidden_size:
611
+ raise ValueError(
612
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
613
+ f" and `num_heads`: {self.num_heads})."
614
+ )
615
+
616
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
617
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
618
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
619
+ self._init_rope()
620
+
621
+ def _init_rope(self):
622
+ if self.rope_scaling is None:
623
+ self.rotary_emb = Phi3RotaryEmbedding(
624
+ self.head_dim,
625
+ max_position_embeddings=self.max_position_embeddings,
626
+ base=self.rope_theta,
627
+ )
628
+ else:
629
+ scaling_type = self.config.rope_scaling["type"]
630
+ if scaling_type == "su":
631
+ self.rotary_emb = Phi3SuScaledRotaryEmbedding(self.head_dim, self.config)
632
+ elif scaling_type == "yarn":
633
+ self.rotary_emb = Phi3YarnScaledRotaryEmbedding(self.head_dim, self.config)
634
+ else:
635
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
636
+
637
+ def forward(
638
+ self,
639
+ hidden_states: torch.Tensor,
640
+ attention_mask: Optional[torch.Tensor] = None,
641
+ position_ids: Optional[torch.LongTensor] = None,
642
+ past_key_value: Optional[Cache] = None,
643
+ output_attentions: bool = False,
644
+ use_cache: bool = False,
645
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
646
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
647
+
648
+ bsz, q_len, _ = hidden_states.size()
649
+
650
+ qkv = self.qkv_proj(hidden_states)
651
+ query_pos = self.num_heads * self.head_dim
652
+ query_states = qkv[..., :query_pos]
653
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
654
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
655
+
656
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
657
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
658
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
659
+
660
+ kv_seq_len = key_states.shape[-2]
661
+ if past_key_value is not None:
662
+ if self.layer_idx is None:
663
+ raise ValueError(
664
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
665
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
666
+ "with a layer index."
667
+ )
668
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
669
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
670
+
671
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
672
+
673
+ if past_key_value is not None:
674
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
675
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
676
+
677
+ # repeat k/v heads if n_kv_heads < n_heads
678
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
679
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
680
+
681
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
682
+
683
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
684
+ raise ValueError(
685
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
686
+ f" {attn_weights.size()}"
687
+ )
688
+
689
+ if attention_mask is not None:
690
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
691
+ raise ValueError(
692
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
693
+ )
694
+ attn_weights = attn_weights + attention_mask
695
+
696
+ # upcast attention to fp32
697
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
698
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
699
+
700
+ attn_output = torch.matmul(attn_weights, value_states)
701
+
702
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
703
+ raise ValueError(
704
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
705
+ f" {attn_output.size()}"
706
+ )
707
+
708
+ attn_output = attn_output.transpose(1, 2).contiguous()
709
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
710
+
711
+ attn_output = self.o_proj(attn_output)
712
+
713
+ if not output_attentions:
714
+ attn_weights = None
715
+
716
+ return attn_output, attn_weights, past_key_value
717
+
718
+
719
+ class Phi3FlashAttention2(Phi3Attention):
720
+ """
721
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
722
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
723
+ flash attention and deal with padding tokens in case the input contains any of them.
724
+ """
725
+
726
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
727
+ def __init__(self, *args, **kwargs):
728
+ super().__init__(*args, **kwargs)
729
+
730
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
731
+ # 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.
732
+ # 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).
733
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
734
+
735
+ def forward(
736
+ self,
737
+ hidden_states: torch.Tensor,
738
+ attention_mask: Optional[torch.LongTensor] = None,
739
+ position_ids: Optional[torch.LongTensor] = None,
740
+ past_key_value: Optional[Cache] = None,
741
+ output_attentions: bool = False,
742
+ use_cache: bool = False,
743
+ **kwargs,
744
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
745
+ # Phi3FlashAttention2 attention does not support output_attentions
746
+
747
+ if not _flash_supports_window_size:
748
+ logger.warning_once(
749
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
750
+ )
751
+ raise ValueError("The current flash attention version does not support sliding window attention.")
752
+
753
+ output_attentions = False
754
+
755
+ if "padding_mask" in kwargs:
756
+ warnings.warn(
757
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
758
+ )
759
+
760
+ # overwrite attention_mask with padding_mask
761
+ attention_mask = kwargs.pop("padding_mask")
762
+
763
+ bsz, q_len, _ = hidden_states.size()
764
+
765
+ qkv = self.qkv_proj(hidden_states)
766
+ query_pos = self.num_heads * self.head_dim
767
+ query_states = qkv[..., :query_pos]
768
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
769
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
770
+
771
+ # Flash attention requires the input to have the shape
772
+ # batch_size x seq_length x head_dim x hidden_dim
773
+ # therefore we just need to keep the original shape
774
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
775
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
776
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
777
+
778
+ kv_seq_len = key_states.shape[-2]
779
+ if past_key_value is not None:
780
+ if self.layer_idx is None:
781
+ raise ValueError(
782
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
783
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
784
+ "with a layer index."
785
+ )
786
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
787
+
788
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
789
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
790
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
791
+
792
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
793
+
794
+ use_sliding_windows = (
795
+ _flash_supports_window_size
796
+ and getattr(self.config, "sliding_window", None) is not None
797
+ and kv_seq_len > self.config.sliding_window
798
+ )
799
+
800
+ if past_key_value is not None:
801
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
802
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
803
+ if (
804
+ getattr(self.config, "sliding_window", None) is not None
805
+ and kv_seq_len > self.config.sliding_window
806
+ and cache_has_contents
807
+ ):
808
+ slicing_tokens = 1 - self.config.sliding_window
809
+
810
+ past_key = past_key_value[self.layer_idx][0]
811
+ past_value = past_key_value[self.layer_idx][1]
812
+
813
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
814
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
815
+
816
+ if past_key.shape[-2] != self.config.sliding_window - 1:
817
+ raise ValueError(
818
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
819
+ f" {past_key.shape}"
820
+ )
821
+
822
+ if attention_mask is not None:
823
+ attention_mask = attention_mask[:, slicing_tokens:]
824
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
825
+
826
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
827
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
828
+
829
+ # repeat k/v heads if n_kv_heads < n_heads
830
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
831
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
832
+
833
+ attn_dropout = self.attention_dropout if self.training else 0.0
834
+
835
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
836
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
837
+ # cast them back in the correct dtype just to be sure everything works as expected.
838
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
839
+ # in fp32.
840
+
841
+ if query_states.dtype == torch.float32:
842
+ if torch.is_autocast_enabled():
843
+ target_dtype = torch.get_autocast_gpu_dtype()
844
+ # Handle the case where the model is quantized
845
+ elif hasattr(self.config, "_pre_quantization_dtype"):
846
+ target_dtype = self.config._pre_quantization_dtype
847
+ else:
848
+ target_dtype = self.qkv_proj.weight.dtype
849
+
850
+ logger.warning_once(
851
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
852
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
853
+ f" {target_dtype}."
854
+ )
855
+
856
+ query_states = query_states.to(target_dtype)
857
+ key_states = key_states.to(target_dtype)
858
+ value_states = value_states.to(target_dtype)
859
+
860
+ # Reashape to the expected shape for Flash Attention
861
+ query_states = query_states.transpose(1, 2)
862
+ key_states = key_states.transpose(1, 2)
863
+ value_states = value_states.transpose(1, 2)
864
+
865
+ attn_output = self._flash_attention_forward(
866
+ query_states,
867
+ key_states,
868
+ value_states,
869
+ attention_mask,
870
+ q_len,
871
+ dropout=attn_dropout,
872
+ use_sliding_windows=use_sliding_windows,
873
+ )
874
+
875
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
876
+ attn_output = self.o_proj(attn_output)
877
+
878
+ if not output_attentions:
879
+ attn_weights = None
880
+
881
+ return attn_output, attn_weights, past_key_value
882
+
883
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
884
+ def _flash_attention_forward(
885
+ self,
886
+ query_states,
887
+ key_states,
888
+ value_states,
889
+ attention_mask,
890
+ query_length,
891
+ dropout=0.0,
892
+ softmax_scale=None,
893
+ use_sliding_windows=False,
894
+ ):
895
+ """
896
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
897
+ first unpad the input, then computes the attention scores and pad the final attention scores.
898
+
899
+ Args:
900
+ query_states (`torch.Tensor`):
901
+ Input query states to be passed to Flash Attention API
902
+ key_states (`torch.Tensor`):
903
+ Input key states to be passed to Flash Attention API
904
+ value_states (`torch.Tensor`):
905
+ Input value states to be passed to Flash Attention API
906
+ attention_mask (`torch.Tensor`):
907
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
908
+ position of padding tokens and 1 for the position of non-padding tokens.
909
+ dropout (`float`):
910
+ Attention dropout
911
+ softmax_scale (`float`, *optional*):
912
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
913
+ use_sliding_windows (`bool`, *optional*):
914
+ Whether to activate sliding window attention.
915
+ """
916
+ if not self._flash_attn_uses_top_left_mask:
917
+ causal = self.is_causal
918
+ else:
919
+ # 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__.
920
+ causal = self.is_causal and query_length != 1
921
+
922
+ # Contains at least one padding token in the sequence
923
+ if attention_mask is not None:
924
+ batch_size = query_states.shape[0]
925
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
926
+ query_states, key_states, value_states, attention_mask, query_length
927
+ )
928
+
929
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
930
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
931
+
932
+ if not use_sliding_windows:
933
+ attn_output_unpad = flash_attn_varlen_func(
934
+ query_states,
935
+ key_states,
936
+ value_states,
937
+ cu_seqlens_q=cu_seqlens_q,
938
+ cu_seqlens_k=cu_seqlens_k,
939
+ max_seqlen_q=max_seqlen_in_batch_q,
940
+ max_seqlen_k=max_seqlen_in_batch_k,
941
+ dropout_p=dropout,
942
+ softmax_scale=softmax_scale,
943
+ causal=causal,
944
+ )
945
+ else:
946
+ attn_output_unpad = flash_attn_varlen_func(
947
+ query_states,
948
+ key_states,
949
+ value_states,
950
+ cu_seqlens_q=cu_seqlens_q,
951
+ cu_seqlens_k=cu_seqlens_k,
952
+ max_seqlen_q=max_seqlen_in_batch_q,
953
+ max_seqlen_k=max_seqlen_in_batch_k,
954
+ dropout_p=dropout,
955
+ softmax_scale=softmax_scale,
956
+ causal=causal,
957
+ window_size=(self.config.sliding_window, self.config.sliding_window),
958
+ )
959
+
960
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
961
+ else:
962
+ if not use_sliding_windows:
963
+ attn_output = flash_attn_func(
964
+ query_states,
965
+ key_states,
966
+ value_states,
967
+ dropout,
968
+ softmax_scale=softmax_scale,
969
+ causal=causal,
970
+ )
971
+ else:
972
+ attn_output = flash_attn_func(
973
+ query_states,
974
+ key_states,
975
+ value_states,
976
+ dropout,
977
+ softmax_scale=softmax_scale,
978
+ causal=causal,
979
+ window_size=(self.config.sliding_window, self.config.sliding_window),
980
+ )
981
+
982
+ return attn_output
983
+
984
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
985
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
986
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
987
+
988
+ # On the first iteration we need to properly re-create the padding mask
989
+ # by slicing it on the proper place
990
+ if kv_seq_len != attention_mask.shape[-1]:
991
+ attention_mask_num_tokens = attention_mask.shape[-1]
992
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
993
+
994
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
995
+
996
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
997
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
998
+
999
+ if query_length == kv_seq_len:
1000
+ query_layer = index_first_axis(
1001
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
1002
+ )
1003
+ cu_seqlens_q = cu_seqlens_k
1004
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1005
+ indices_q = indices_k
1006
+ elif query_length == 1:
1007
+ max_seqlen_in_batch_q = 1
1008
+ cu_seqlens_q = torch.arange(
1009
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1010
+ ) # There is a memcpy here, that is very bad.
1011
+ indices_q = cu_seqlens_q[:-1]
1012
+ query_layer = query_layer.squeeze(1)
1013
+ else:
1014
+ # The -q_len: slice assumes left padding.
1015
+ attention_mask = attention_mask[:, -query_length:]
1016
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
1017
+
1018
+ return (
1019
+ query_layer,
1020
+ key_layer,
1021
+ value_layer,
1022
+ indices_q,
1023
+ (cu_seqlens_q, cu_seqlens_k),
1024
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1025
+ )
1026
+
1027
+
1028
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
1029
+ # TODO @Arthur no longer copied from LLama after static cache
1030
+ class Phi3SdpaAttention(Phi3Attention):
1031
+ """
1032
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
1033
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
1034
+ SDPA API.
1035
+ """
1036
+
1037
+ # Adapted from Phi3Attention.forward
1038
+ def forward(
1039
+ self,
1040
+ hidden_states: torch.Tensor,
1041
+ attention_mask: Optional[torch.Tensor] = None,
1042
+ position_ids: Optional[torch.LongTensor] = None,
1043
+ past_key_value: Optional[Cache] = None,
1044
+ output_attentions: bool = False,
1045
+ use_cache: bool = False,
1046
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1047
+ if output_attentions:
1048
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
1049
+ logger.warning_once(
1050
+ "Phi3Model is using Phi3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
1051
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
1052
+ )
1053
+ return super().forward(
1054
+ hidden_states=hidden_states,
1055
+ attention_mask=attention_mask,
1056
+ position_ids=position_ids,
1057
+ past_key_value=past_key_value,
1058
+ output_attentions=output_attentions,
1059
+ use_cache=use_cache,
1060
+ )
1061
+
1062
+ bsz, q_len, _ = hidden_states.size()
1063
+
1064
+ qkv = self.qkv_proj(hidden_states)
1065
+ query_pos = self.num_heads * self.head_dim
1066
+ query_states = qkv[..., :query_pos]
1067
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
1068
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
1069
+
1070
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
1071
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1072
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1073
+
1074
+ kv_seq_len = key_states.shape[-2]
1075
+ if past_key_value is not None:
1076
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1077
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
1078
+
1079
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
1080
+
1081
+ if past_key_value is not None:
1082
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1083
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
1084
+
1085
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1086
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1087
+
1088
+ if attention_mask is not None:
1089
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
1090
+ raise ValueError(
1091
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
1092
+ )
1093
+
1094
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
1095
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
1096
+ if query_states.device.type == "cuda" and attention_mask is not None:
1097
+ query_states = query_states.contiguous()
1098
+ key_states = key_states.contiguous()
1099
+ value_states = value_states.contiguous()
1100
+
1101
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1102
+ query_states,
1103
+ key_states,
1104
+ value_states,
1105
+ attn_mask=attention_mask,
1106
+ dropout_p=self.attention_dropout if self.training else 0.0,
1107
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
1108
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
1109
+ )
1110
+
1111
+ attn_output = attn_output.transpose(1, 2).contiguous()
1112
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
1113
+
1114
+ attn_output = self.o_proj(attn_output)
1115
+
1116
+ return attn_output, None, past_key_value
1117
+
1118
+
1119
+ PHI3_ATTENTION_CLASSES = {
1120
+ "eager": Phi3Attention,
1121
+ "flash_attention_2": Phi3FlashAttention2,
1122
+ "sdpa": Phi3SdpaAttention,
1123
+ }
1124
+
1125
+
1126
+ class Phi3DecoderLayer(nn.Module):
1127
+ def __init__(self, config: Phi3VConfig, layer_idx: int):
1128
+ super().__init__()
1129
+
1130
+ self.config = config
1131
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
1132
+
1133
+ self.mlp = Phi3MLP(config)
1134
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1135
+
1136
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
1137
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
1138
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1139
+
1140
+ def forward(
1141
+ self,
1142
+ hidden_states: torch.Tensor,
1143
+ attention_mask: Optional[torch.Tensor] = None,
1144
+ position_ids: Optional[torch.LongTensor] = None,
1145
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1146
+ output_attentions: Optional[bool] = False,
1147
+ use_cache: Optional[bool] = False,
1148
+ **kwargs,
1149
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1150
+ if "padding_mask" in kwargs:
1151
+ warnings.warn(
1152
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1153
+ )
1154
+ """
1155
+ Args:
1156
+ hidden_states (`torch.FloatTensor`):
1157
+ input to the layer of shape `(batch, seq_len, embed_dim)`
1158
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
1159
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
1160
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
1161
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
1162
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
1163
+ output_attentions (`bool`, *optional*):
1164
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1165
+ returned tensors for more detail.
1166
+ use_cache (`bool`, *optional*):
1167
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1168
+ (see `past_key_values`).
1169
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1170
+ """
1171
+
1172
+ residual = hidden_states
1173
+
1174
+ hidden_states = self.input_layernorm(hidden_states)
1175
+
1176
+ # Self Attention
1177
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
1178
+ hidden_states=hidden_states,
1179
+ attention_mask=attention_mask,
1180
+ position_ids=position_ids,
1181
+ past_key_value=past_key_value,
1182
+ output_attentions=output_attentions,
1183
+ use_cache=use_cache,
1184
+ )
1185
+
1186
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
1187
+
1188
+ residual = hidden_states
1189
+ hidden_states = self.post_attention_layernorm(hidden_states)
1190
+ hidden_states = self.mlp(hidden_states)
1191
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
1192
+
1193
+ outputs = (hidden_states,)
1194
+
1195
+ if output_attentions:
1196
+ outputs += (self_attn_weights,)
1197
+
1198
+ if use_cache:
1199
+ outputs += (present_key_value,)
1200
+
1201
+ return outputs
1202
+
1203
+
1204
+ PHI3V_START_DOCSTRING = r"""
1205
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1206
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1207
+ etc.)
1208
+
1209
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1210
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1211
+ and behavior.
1212
+
1213
+ Parameters:
1214
+ config ([`Phi3VConfig`]):
1215
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1216
+ load the weights associated with the model, only the configuration. Check out the
1217
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1218
+ """
1219
+
1220
+
1221
+ @add_start_docstrings(
1222
+ "The bare Phi-3-V model outputting raw hidden-states without any specific head on top.",
1223
+ PHI3V_START_DOCSTRING,
1224
+ )
1225
+ class Phi3VPreTrainedModel(PreTrainedModel):
1226
+ config_class = Phi3VConfig
1227
+ base_model_prefix = "model"
1228
+ supports_gradient_checkpointing = True
1229
+ _no_split_modules = ["Phi3DecoderLayer"]
1230
+ _skip_keys_device_placement = "past_key_values"
1231
+ _supports_flash_attn_2 = True
1232
+ _supports_sdpa = False
1233
+ _supports_cache_class = True
1234
+
1235
+ _version = "0.0.5"
1236
+
1237
+ def _init_weights(self, module):
1238
+ std = self.config.initializer_range
1239
+ if isinstance(module, nn.Linear):
1240
+ module.weight.data.normal_(mean=0.0, std=std)
1241
+ if module.bias is not None:
1242
+ module.bias.data.zero_()
1243
+ elif isinstance(module, nn.Embedding):
1244
+ module.weight.data.normal_(mean=0.0, std=std)
1245
+ if module.padding_idx is not None:
1246
+ module.weight.data[module.padding_idx].zero_()
1247
+
1248
+
1249
+ PHI3V_INPUTS_DOCSTRING = r"""
1250
+ Args:
1251
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1252
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1253
+ it.
1254
+
1255
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1256
+ [`PreTrainedTokenizer.__call__`] for details.
1257
+
1258
+ [What are input IDs?](../glossary#input-ids)
1259
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1260
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1261
+
1262
+ - 1 for tokens that are **not masked**,
1263
+ - 0 for tokens that are **masked**.
1264
+
1265
+ [What are attention masks?](../glossary#attention-mask)
1266
+
1267
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1268
+ [`PreTrainedTokenizer.__call__`] for details.
1269
+
1270
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1271
+ `past_key_values`).
1272
+
1273
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1274
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1275
+ information on the default strategy.
1276
+
1277
+ - 1 indicates the head is **not masked**,
1278
+ - 0 indicates the head is **masked**.
1279
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1280
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1281
+ config.n_positions - 1]`.
1282
+
1283
+ [What are position IDs?](../glossary#position-ids)
1284
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1285
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1286
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1287
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1288
+
1289
+ Two formats are allowed:
1290
+ - a [`~cache_utils.Cache`] instance;
1291
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1292
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1293
+ cache format.
1294
+
1295
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1296
+ legacy cache format will be returned.
1297
+
1298
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1299
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1300
+ of shape `(batch_size, sequence_length)`.
1301
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1302
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1303
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1304
+ model's internal embedding lookup matrix.
1305
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
1306
+ The tensors corresponding to the input images. Pixel values can be obtained using [`AutoImageProcessor`].
1307
+ See [`Phi3ImageProcessor.__call__`] for details.
1308
+ image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`, *optional*):
1309
+ The sizes of the images in the batch, being (height, width) for each image.
1310
+ use_cache (`bool`, *optional*):
1311
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1312
+ `past_key_values`).
1313
+ output_attentions (`bool`, *optional*):
1314
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1315
+ tensors for more detail.
1316
+ output_hidden_states (`bool`, *optional*):
1317
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1318
+ more detail.
1319
+ return_dict (`bool`, *optional*):
1320
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1321
+ """
1322
+
1323
+
1324
+ @add_start_docstrings(
1325
+ "The bare Phi-3-V model outputting raw hidden-states without any specific head on top.",
1326
+ PHI3V_START_DOCSTRING,
1327
+ )
1328
+ class Phi3VModel(Phi3VPreTrainedModel):
1329
+ """
1330
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
1331
+
1332
+ Args:
1333
+ config: Phi3Config
1334
+ """
1335
+
1336
+ def __init__(self, config: Phi3VConfig):
1337
+ super().__init__(config)
1338
+ self.padding_idx = config.pad_token_id
1339
+ self.vocab_size = config.vocab_size
1340
+
1341
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1342
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1343
+
1344
+ self.vision_embed_tokens = None
1345
+ if isinstance(config.embd_layer, dict):
1346
+ # vision embedding layer
1347
+ embedding_config = {
1348
+ 'embedding_cls': config.embd_layer['embedding_cls'],
1349
+ **config.embd_layer
1350
+ }
1351
+ self.vision_embed_tokens = Phi3ImageEmbedding(config, wte=self.embed_tokens, **embedding_config)
1352
+ # # set wte the same for vision embedding
1353
+ # self.vision_embed_tokens.wte.weight = self.embed_tokens.weight
1354
+
1355
+ self.layers = nn.ModuleList(
1356
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1357
+ )
1358
+ self._attn_implementation = config._attn_implementation
1359
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1360
+
1361
+ self.gradient_checkpointing = False
1362
+ # Initialize weights and apply final processing
1363
+ self.post_init()
1364
+
1365
+ def get_input_embeddings(self):
1366
+ return self.embed_tokens
1367
+
1368
+ def set_input_embeddings(self, value):
1369
+ self.embed_tokens = value
1370
+
1371
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1372
+ def forward(
1373
+ self,
1374
+ input_ids: torch.LongTensor = None,
1375
+ attention_mask: Optional[torch.Tensor] = None,
1376
+ position_ids: Optional[torch.LongTensor] = None,
1377
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1378
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1379
+ pixel_values: Optional[torch.FloatTensor] = None,
1380
+ image_sizes: Optional[torch.LongTensor] = None,
1381
+ use_cache: Optional[bool] = None,
1382
+ output_attentions: Optional[bool] = None,
1383
+ output_hidden_states: Optional[bool] = None,
1384
+ return_dict: Optional[bool] = None,
1385
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1386
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1387
+ output_hidden_states = (
1388
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1389
+ )
1390
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1391
+
1392
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1393
+
1394
+ # retrieve input_ids and inputs_embeds
1395
+ if input_ids is not None and inputs_embeds is not None:
1396
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1397
+ elif input_ids is not None:
1398
+ batch_size, seq_length = input_ids.shape[:2]
1399
+ elif inputs_embeds is not None:
1400
+ batch_size, seq_length = inputs_embeds.shape[:2]
1401
+ else:
1402
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1403
+
1404
+ past_key_values_length = 0
1405
+
1406
+ if self.gradient_checkpointing and self.training:
1407
+ if use_cache:
1408
+ logger.warning_once(
1409
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1410
+ )
1411
+ use_cache = False
1412
+
1413
+ if use_cache:
1414
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1415
+ if use_legacy_cache:
1416
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1417
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1418
+
1419
+ if position_ids is None:
1420
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1421
+ position_ids = torch.arange(
1422
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1423
+ )
1424
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1425
+ else:
1426
+ position_ids = position_ids.view(-1, seq_length).long()
1427
+
1428
+ if inputs_embeds is None:
1429
+ if pixel_values is not None and image_sizes is not None:
1430
+ assert self.vision_embed_tokens is not None, "Vision embedding layer is not defined"
1431
+ inputs_embeds = self.vision_embed_tokens(input_ids, pixel_values=pixel_values, image_sizes=image_sizes)
1432
+ else:
1433
+ inputs_embeds = self.embed_tokens(input_ids)
1434
+
1435
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1436
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1437
+ if is_padding_right:
1438
+ raise ValueError(
1439
+ "You are attempting to perform batched generation with padding_side='right'"
1440
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1441
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1442
+ )
1443
+
1444
+ if self._attn_implementation == "flash_attention_2":
1445
+ # 2d mask is passed through the layers
1446
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1447
+ else:
1448
+ # 4d mask is passed through the layers
1449
+ attention_mask = _prepare_4d_causal_attention_mask(
1450
+ attention_mask,
1451
+ (batch_size, seq_length),
1452
+ inputs_embeds,
1453
+ past_key_values_length,
1454
+ sliding_window=self.config.sliding_window,
1455
+ )
1456
+
1457
+ hidden_states = inputs_embeds
1458
+
1459
+ # decoder layers
1460
+ all_hidden_states = () if output_hidden_states else None
1461
+ all_self_attns = () if output_attentions else None
1462
+ next_decoder_cache = None
1463
+
1464
+ for decoder_layer in self.layers:
1465
+ if output_hidden_states:
1466
+ all_hidden_states += (hidden_states,)
1467
+
1468
+ if self.gradient_checkpointing and self.training:
1469
+ layer_outputs = self._gradient_checkpointing_func(
1470
+ decoder_layer.__call__,
1471
+ hidden_states,
1472
+ attention_mask,
1473
+ position_ids,
1474
+ past_key_values,
1475
+ output_attentions,
1476
+ use_cache,
1477
+ )
1478
+ else:
1479
+ layer_outputs = decoder_layer(
1480
+ hidden_states,
1481
+ attention_mask=attention_mask,
1482
+ position_ids=position_ids,
1483
+ past_key_value=past_key_values,
1484
+ output_attentions=output_attentions,
1485
+ use_cache=use_cache,
1486
+ )
1487
+
1488
+ hidden_states = layer_outputs[0]
1489
+
1490
+ if use_cache:
1491
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1492
+
1493
+ if output_attentions:
1494
+ all_self_attns += (layer_outputs[1],)
1495
+
1496
+ hidden_states = self.norm(hidden_states)
1497
+
1498
+ # add hidden states from the last decoder layer
1499
+ if output_hidden_states:
1500
+ all_hidden_states += (hidden_states,)
1501
+
1502
+ next_cache = None
1503
+ if use_cache:
1504
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1505
+ if not return_dict:
1506
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1507
+ return BaseModelOutputWithPast(
1508
+ last_hidden_state=hidden_states,
1509
+ past_key_values=next_cache,
1510
+ hidden_states=all_hidden_states,
1511
+ attentions=all_self_attns,
1512
+ )
1513
+
1514
+
1515
+ class Phi3VForCausalLM(Phi3VPreTrainedModel):
1516
+ _tied_weights_keys = ["lm_head.weight"]
1517
+
1518
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1519
+ def __init__(self, config):
1520
+ super().__init__(config)
1521
+ self.model = Phi3VModel(config)
1522
+ self.vocab_size = config.vocab_size
1523
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1524
+
1525
+ # Initialize weights and apply final processing
1526
+ self.post_init()
1527
+
1528
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1529
+ def get_input_embeddings(self):
1530
+ return self.model.embed_tokens
1531
+
1532
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1533
+ def set_input_embeddings(self, value):
1534
+ self.model.embed_tokens = value
1535
+
1536
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1537
+ def get_output_embeddings(self):
1538
+ return self.lm_head
1539
+
1540
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1541
+ def set_output_embeddings(self, new_embeddings):
1542
+ self.lm_head = new_embeddings
1543
+
1544
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1545
+ def set_decoder(self, decoder):
1546
+ self.model = decoder
1547
+
1548
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1549
+ def get_decoder(self):
1550
+ return self.model
1551
+
1552
+ # Ignore copy
1553
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1554
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1555
+ def forward(
1556
+ self,
1557
+ input_ids: torch.LongTensor = None,
1558
+ attention_mask: Optional[torch.Tensor] = None,
1559
+ position_ids: Optional[torch.LongTensor] = None,
1560
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1561
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1562
+ pixel_values: Optional[torch.FloatTensor] = None,
1563
+ image_sizes: Optional[torch.LongTensor] = None,
1564
+ labels: Optional[torch.LongTensor] = None,
1565
+ use_cache: Optional[bool] = None,
1566
+ output_attentions: Optional[bool] = None,
1567
+ output_hidden_states: Optional[bool] = None,
1568
+ return_dict: Optional[bool] = None,
1569
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1570
+ r"""
1571
+ Args:
1572
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1573
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1574
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1575
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1576
+
1577
+ Returns:
1578
+
1579
+ Example:
1580
+
1581
+ ```python
1582
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1583
+
1584
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1585
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1586
+
1587
+ >>> prompt = "This is an example script ."
1588
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1589
+
1590
+ >>> # Generate
1591
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1592
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1593
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1594
+ ```"""
1595
+
1596
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1597
+ output_hidden_states = (
1598
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1599
+ )
1600
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1601
+
1602
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1603
+ outputs = self.model(
1604
+ input_ids=input_ids,
1605
+ attention_mask=attention_mask,
1606
+ position_ids=position_ids,
1607
+ past_key_values=past_key_values,
1608
+ inputs_embeds=inputs_embeds,
1609
+ pixel_values=pixel_values,
1610
+ image_sizes=image_sizes,
1611
+ use_cache=use_cache,
1612
+ output_attentions=output_attentions,
1613
+ output_hidden_states=output_hidden_states,
1614
+ return_dict=return_dict,
1615
+ )
1616
+
1617
+ hidden_states = outputs[0]
1618
+ logits = self.lm_head(hidden_states)
1619
+ logits = logits.float()
1620
+
1621
+ loss = None
1622
+ if labels is not None:
1623
+ # Shift so that tokens < n predict n
1624
+ shift_logits = logits[..., :-1, :].contiguous()
1625
+ shift_labels = labels[..., 1:].contiguous()
1626
+ # Flatten the tokens
1627
+ loss_fct = CrossEntropyLoss()
1628
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1629
+ shift_labels = shift_labels.view(-1)
1630
+ # Enable model parallelism
1631
+ shift_labels = shift_labels.to(shift_logits.device)
1632
+ loss = loss_fct(shift_logits, shift_labels)
1633
+
1634
+ if not return_dict:
1635
+ output = (logits,) + outputs[1:]
1636
+ return (loss,) + output if loss is not None else output
1637
+
1638
+ return CausalLMOutputWithPast(
1639
+ loss=loss,
1640
+ logits=logits,
1641
+ past_key_values=outputs.past_key_values,
1642
+ hidden_states=outputs.hidden_states,
1643
+ attentions=outputs.attentions,
1644
+ )
1645
+
1646
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1647
+ def prepare_inputs_for_generation(
1648
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, pixel_values=None, image_sizes=None, **kwargs
1649
+ ):
1650
+ if past_key_values is not None:
1651
+ if isinstance(past_key_values, Cache):
1652
+ cache_length = past_key_values.get_seq_length()
1653
+ past_length = past_key_values.seen_tokens
1654
+ max_cache_length = past_key_values.get_max_length()
1655
+ else:
1656
+ cache_length = past_length = past_key_values[0][0].shape[2]
1657
+ max_cache_length = None
1658
+
1659
+ # Keep only the unprocessed tokens:
1660
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1661
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1662
+ # input)
1663
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1664
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1665
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1666
+ # input_ids based on the past_length.
1667
+ elif past_length < input_ids.shape[1]:
1668
+ input_ids = input_ids[:, past_length:]
1669
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1670
+
1671
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1672
+ if (
1673
+ max_cache_length is not None
1674
+ and attention_mask is not None
1675
+ and cache_length + input_ids.shape[1] > max_cache_length
1676
+ ):
1677
+ attention_mask = attention_mask[:, -max_cache_length:]
1678
+
1679
+ position_ids = kwargs.get("position_ids", None)
1680
+ if attention_mask is not None and position_ids is None:
1681
+ # create position_ids on the fly for batch generation
1682
+ position_ids = attention_mask.long().cumsum(-1) - 1
1683
+ position_ids.masked_fill_(attention_mask == 0, 1)
1684
+ if past_key_values:
1685
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1686
+
1687
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1688
+ if inputs_embeds is not None and past_key_values is None:
1689
+ model_inputs = {"inputs_embeds": inputs_embeds}
1690
+ else:
1691
+ model_inputs = {"input_ids": input_ids}
1692
+
1693
+ model_inputs.update(
1694
+ {
1695
+ "position_ids": position_ids,
1696
+ "past_key_values": past_key_values,
1697
+ "use_cache": kwargs.get("use_cache"),
1698
+ "attention_mask": attention_mask,
1699
+ "pixel_values": pixel_values,
1700
+ "image_sizes": image_sizes,
1701
+ }
1702
+ )
1703
+ return model_inputs
1704
+
1705
+ @staticmethod
1706
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1707
+ def _reorder_cache(past_key_values, beam_idx):
1708
+ reordered_past = ()
1709
+ for layer_past in past_key_values:
1710
+ reordered_past += (
1711
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1712
+ )
1713
+ return reordered_past
1714
+
1715
+
1716
+ @add_start_docstrings(
1717
+ """
1718
+ The [`Phi3VModel`] with a sequence classification head on top (linear layer).
1719
+
1720
+ [`Phi3VForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1721
+ (e.g. GPT-2) do.
1722
+
1723
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1724
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1725
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1726
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1727
+ each row of the batch).
1728
+ """,
1729
+ PHI3V_START_DOCSTRING,
1730
+ )
1731
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1732
+ class Phi3VForSequenceClassification(Phi3VPreTrainedModel):
1733
+ def __init__(self, config):
1734
+ super().__init__(config)
1735
+ self.num_labels = config.num_labels
1736
+ self.model = Phi3VModel(config)
1737
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1738
+
1739
+ # Initialize weights and apply final processing
1740
+ self.post_init()
1741
+
1742
+ def get_input_embeddings(self):
1743
+ return self.model.embed_tokens
1744
+
1745
+ def set_input_embeddings(self, value):
1746
+ self.model.embed_tokens = value
1747
+
1748
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1749
+ def forward(
1750
+ self,
1751
+ input_ids: torch.LongTensor = None,
1752
+ attention_mask: Optional[torch.Tensor] = None,
1753
+ position_ids: Optional[torch.LongTensor] = None,
1754
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1755
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1756
+ pixel_values: Optional[torch.FloatTensor] = None,
1757
+ image_sizes: Optional[torch.LongTensor] = None,
1758
+ labels: Optional[torch.LongTensor] = None,
1759
+ use_cache: Optional[bool] = None,
1760
+ output_attentions: Optional[bool] = None,
1761
+ output_hidden_states: Optional[bool] = None,
1762
+ return_dict: Optional[bool] = None,
1763
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1764
+ r"""
1765
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1766
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1767
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1768
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1769
+ """
1770
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1771
+
1772
+ model_outputs = self.model(
1773
+ input_ids,
1774
+ attention_mask=attention_mask,
1775
+ position_ids=position_ids,
1776
+ past_key_values=past_key_values,
1777
+ inputs_embeds=inputs_embeds,
1778
+ pixel_values=pixel_values,
1779
+ image_sizes=image_sizes,
1780
+ use_cache=use_cache,
1781
+ output_attentions=output_attentions,
1782
+ output_hidden_states=output_hidden_states,
1783
+ return_dict=return_dict,
1784
+ )
1785
+ hidden_states = model_outputs[0]
1786
+ logits = self.score(hidden_states)
1787
+
1788
+ if input_ids is not None:
1789
+ batch_size = input_ids.shape[0]
1790
+ else:
1791
+ batch_size = inputs_embeds.shape[0]
1792
+
1793
+ if self.config.pad_token_id is None and batch_size != 1:
1794
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1795
+ if self.config.pad_token_id is None:
1796
+ sequence_lengths = -1
1797
+ else:
1798
+ if input_ids is not None:
1799
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1800
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1801
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1802
+ sequence_lengths = sequence_lengths.to(logits.device)
1803
+ else:
1804
+ sequence_lengths = -1
1805
+
1806
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1807
+
1808
+ loss = None
1809
+ if labels is not None:
1810
+ labels = labels.to(logits.device)
1811
+ if self.config.problem_type is None:
1812
+ if self.num_labels == 1:
1813
+ self.config.problem_type = "regression"
1814
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1815
+ self.config.problem_type = "single_label_classification"
1816
+ else:
1817
+ self.config.problem_type = "multi_label_classification"
1818
+
1819
+ if self.config.problem_type == "regression":
1820
+ loss_fct = MSELoss()
1821
+ if self.num_labels == 1:
1822
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1823
+ else:
1824
+ loss = loss_fct(pooled_logits, labels)
1825
+ elif self.config.problem_type == "single_label_classification":
1826
+ loss_fct = CrossEntropyLoss()
1827
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1828
+ elif self.config.problem_type == "multi_label_classification":
1829
+ loss_fct = BCEWithLogitsLoss()
1830
+ loss = loss_fct(pooled_logits, labels)
1831
+ if not return_dict:
1832
+ output = (pooled_logits,) + model_outputs[1:]
1833
+ return ((loss,) + output) if loss is not None else output
1834
+
1835
+ return SequenceClassifierOutputWithPast(
1836
+ loss=loss,
1837
+ logits=pooled_logits,
1838
+ past_key_values=model_outputs.past_key_values,
1839
+ hidden_states=model_outputs.hidden_states,
1840
+ attentions=model_outputs.attentions,
1841
+ )
1842
+
1843
+
1844
+ @add_start_docstrings(
1845
+ """
1846
+ [`Phi3VModel`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1847
+ Named-Entity-Recognition (NER) tasks.
1848
+ """,
1849
+ PHI3V_START_DOCSTRING,
1850
+ )
1851
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1852
+ class Phi3VForTokenClassification(Phi3VPreTrainedModel):
1853
+ def __init__(self, config: Phi3VConfig):
1854
+ super().__init__(config)
1855
+ self.num_labels = config.num_labels
1856
+
1857
+ self.model = Phi3VModel(config)
1858
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1859
+ classifier_dropout = config.classifier_dropout
1860
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1861
+ classifier_dropout = config.hidden_dropout
1862
+ else:
1863
+ classifier_dropout = 0.1
1864
+ self.dropout = nn.Dropout(classifier_dropout)
1865
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1866
+
1867
+ # Initialize weights and apply final processing
1868
+ self.post_init()
1869
+
1870
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1871
+ @add_code_sample_docstrings(
1872
+ checkpoint=_CHECKPOINT_FOR_DOC,
1873
+ output_type=TokenClassifierOutput,
1874
+ config_class=_CONFIG_FOR_DOC,
1875
+ )
1876
+ def forward(
1877
+ self,
1878
+ input_ids: Optional[torch.LongTensor] = None,
1879
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1880
+ attention_mask: Optional[torch.Tensor] = None,
1881
+ inputs_embeds: Optional[torch.Tensor] = None,
1882
+ pixel_values: Optional[torch.FloatTensor] = None,
1883
+ image_sizes: Optional[torch.LongTensor] = None,
1884
+ labels: Optional[torch.Tensor] = None,
1885
+ use_cache: Optional[bool] = None,
1886
+ output_attentions: Optional[bool] = None,
1887
+ output_hidden_states: Optional[bool] = None,
1888
+ return_dict: Optional[bool] = None,
1889
+ **deprecated_arguments,
1890
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1891
+ r"""
1892
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1893
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1894
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1895
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1896
+ """
1897
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1898
+
1899
+ model_outputs = self.model(
1900
+ input_ids,
1901
+ past_key_values=past_key_values,
1902
+ attention_mask=attention_mask,
1903
+ inputs_embeds=inputs_embeds,
1904
+ pixel_values=pixel_values,
1905
+ image_sizes=image_sizes,
1906
+ use_cache=use_cache,
1907
+ output_attentions=output_attentions,
1908
+ output_hidden_states=output_hidden_states,
1909
+ return_dict=return_dict,
1910
+ )
1911
+
1912
+ hidden_states = model_outputs[0]
1913
+ hidden_states = self.dropout(hidden_states)
1914
+ logits = self.classifier(hidden_states)
1915
+
1916
+ loss = None
1917
+ if labels is not None:
1918
+ # move labels to correct device to enable model parallelism
1919
+ labels = labels.to(logits.device)
1920
+ batch_size, seq_length = labels.shape
1921
+ loss_fct = CrossEntropyLoss()
1922
+ loss = loss_fct(
1923
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1924
+ )
1925
+
1926
+ if not return_dict:
1927
+ output = (logits,) + model_outputs[2:]
1928
+ return ((loss,) + output) if loss is not None else output
1929
+
1930
+ return TokenClassifierOutput(
1931
+ loss=loss,
1932
+ logits=logits,
1933
+ hidden_states=model_outputs.hidden_states,
1934
+ attentions=model_outputs.attentions,
1935
+ )
preprocessor_config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoImageProcessor": "processing_phi3_v.Phi3VImageProcessor",
4
+ "AutoProcessor": "processing_phi3_v.Phi3VProcessor"
5
+ },
6
+ "do_convert_rgb": true,
7
+ "image_mean": [
8
+ 0.48145466,
9
+ 0.4578275,
10
+ 0.40821073
11
+ ],
12
+ "image_processor_type": "Phi3VImageProcessor",
13
+ "image_std": [
14
+ 0.26862954,
15
+ 0.26130258,
16
+ 0.27577711
17
+ ],
18
+ "num_crops": 4,
19
+ "num_img_tokens": 144,
20
+ "processor_class": "Phi3VProcessor"
21
+ }
22
+
processing_phi3_v.py ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Processor class for Phi3-V.
18
+ """
19
+ import re
20
+ from typing import List, Optional, Union
21
+
22
+ import torch
23
+
24
+ import transformers
25
+ from transformers.feature_extraction_utils import BatchFeature
26
+ from transformers.image_utils import ImageInput
27
+ from transformers.processing_utils import ProcessorMixin
28
+ from transformers.tokenization_utils_base import PaddingStrategy, TextInput, TruncationStrategy
29
+ from transformers.utils import TensorType
30
+
31
+
32
+ """Image processor class for Phi3-V."""
33
+
34
+ from typing import List, Optional, Union
35
+
36
+ import numpy as np
37
+
38
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
39
+ from transformers.image_transforms import (
40
+ convert_to_rgb,
41
+ )
42
+ from transformers.image_utils import (
43
+ OPENAI_CLIP_MEAN,
44
+ OPENAI_CLIP_STD,
45
+ ImageInput,
46
+ make_list_of_images,
47
+ valid_images,
48
+ )
49
+ from transformers.utils import TensorType, is_vision_available, logging
50
+
51
+ from transformers import AutoImageProcessor
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+
56
+ if is_vision_available():
57
+ from PIL import Image
58
+
59
+ import torch
60
+ import torchvision
61
+
62
+ def padding_336(b):
63
+ width, height = b.size
64
+ tar = int(np.ceil(height / 336) * 336)
65
+ top_padding = int((tar - height)/2)
66
+ bottom_padding = tar - height - top_padding
67
+ left_padding = 0
68
+ right_padding = 0
69
+ b = torchvision.transforms.functional.pad(b, [left_padding, top_padding, right_padding, bottom_padding], fill=[255,255,255])
70
+
71
+ return b
72
+
73
+ def calc_padded_size(width, height, padding_unit=336):
74
+ target_height = int(np.ceil(height / padding_unit) * padding_unit)
75
+ top_padding = int((target_height - height) / 2)
76
+ bottom_padding = target_height - height - top_padding
77
+ left_padding = 0
78
+ right_padding = 0
79
+ padded_width = width + left_padding + right_padding
80
+ padded_height = height + top_padding + bottom_padding
81
+ return padded_width, padded_height
82
+
83
+ def HD_transform(img, hd_num=16):
84
+ width, height = img.size
85
+ trans = False
86
+ if width < height:
87
+ img = img.transpose(Image.TRANSPOSE)
88
+ trans = True
89
+ width, height = img.size
90
+ ratio = (width/ height)
91
+ scale = 1
92
+ while scale*np.ceil(scale/ratio) <= hd_num:
93
+ scale += 1
94
+ scale -= 1
95
+ new_w = int(scale * 336)
96
+ new_h = int(new_w / ratio)
97
+
98
+ img = torchvision.transforms.functional.resize(img, [new_h, new_w],)
99
+ img = padding_336(img)
100
+ width, height = img.size
101
+ if trans:
102
+ img = img.transpose(Image.TRANSPOSE)
103
+
104
+ return img
105
+
106
+ def calc_hd_transform_size(width, height, hd_num=16):
107
+ transposed = False
108
+ if width < height:
109
+ width, height = height, width
110
+ transposed = True
111
+
112
+ ratio = width / height
113
+ scale = 1
114
+ while scale * np.ceil(scale / ratio) <= hd_num:
115
+ scale += 1
116
+ scale -= 1
117
+
118
+ new_width = int(scale * 336)
119
+ new_height = int(new_width / ratio)
120
+
121
+ padded_width, padded_height = calc_padded_size(new_width, new_height)
122
+
123
+ if transposed:
124
+ padded_width, padded_height = padded_height, padded_width
125
+
126
+ return padded_width, padded_height
127
+
128
+ def pad_to_max_num_crops_tensor(images, max_crops=5):
129
+ """
130
+ images: B x 3 x H x W, B<=max_crops
131
+ """
132
+ B, _, H, W = images.shape
133
+ if B < max_crops:
134
+ pad = torch.zeros(max_crops - B, 3, H, W, dtype=images.dtype, device=images.device)
135
+ images = torch.cat([images, pad], dim=0)
136
+ return images
137
+
138
+
139
+ class Phi3VImageProcessor(BaseImageProcessor):
140
+ r"""
141
+ Constructs a Phi3 image processor. Based on [`CLIPImageProcessor`] with incorporation of additional techniques
142
+ for processing high resolution images as explained in the [InternLM-XComposer2-4KHD](https://arxiv.org/pdf/2404.06512)
143
+
144
+ Args:
145
+ image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
146
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
147
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
148
+ image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
149
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
150
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
151
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
152
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
153
+ Whether to convert the image to RGB.
154
+ """
155
+
156
+ model_input_names = ["pixel_values"]
157
+
158
+ def __init__(
159
+ self,
160
+ num_crops: int = 1,
161
+ image_mean: Optional[Union[float, List[float]]] = None,
162
+ image_std: Optional[Union[float, List[float]]] = None,
163
+ do_convert_rgb: bool = True,
164
+ **kwargs,
165
+ ) -> None:
166
+ super().__init__(**kwargs)
167
+ self.num_crops = num_crops
168
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
169
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
170
+ self.do_convert_rgb = do_convert_rgb
171
+
172
+ def calc_num_image_tokens(
173
+ self,
174
+ images: ImageInput
175
+ ):
176
+ """ Calculate the number of image tokens for each image.
177
+ Args:
178
+ images (`ImageInput`):
179
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
180
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
181
+ """
182
+ images = make_list_of_images(images)
183
+
184
+ if not valid_images(images):
185
+ raise ValueError(
186
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
187
+ "torch.Tensor, tf.Tensor or jax.ndarray."
188
+ )
189
+
190
+ images = [image.convert('RGB') for image in images]
191
+ # (H, W, C)
192
+ elems = [HD_transform(im, hd_num = self.num_crops) for im in images]
193
+ shapes = [[im.size[1], im.size[0]] for im in elems]
194
+ num_img_tokens = [int((h//336*w//336+1)*144 + 1 + (h//336+1)*12) for h, w in shapes]
195
+ return num_img_tokens
196
+
197
+ def calc_num_image_tokens_from_image_size(self, width, height):
198
+ """
199
+ Calculate the number of image tokens for a given image size.
200
+ Args:
201
+ width (`int`): Width of the image.
202
+ height (`int`): Height of the image.
203
+ """
204
+ new_width, new_height = calc_hd_transform_size(width, height, hd_num=self.num_crops)
205
+ num_img_tokens = int((new_height // 336 * new_width // 336 + 1) * 144 + 1 + (new_height // 336 + 1) * 12)
206
+ return num_img_tokens
207
+
208
+ def preprocess(
209
+ self,
210
+ images: ImageInput,
211
+ image_mean: Optional[Union[float, List[float]]] = None,
212
+ image_std: Optional[Union[float, List[float]]] = None,
213
+ do_convert_rgb: bool = None,
214
+ return_tensors: Optional[Union[str, TensorType]] = None,
215
+ ):
216
+ """
217
+ Args:
218
+ images (`ImageInput`):
219
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
220
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
221
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
222
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
223
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
224
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
225
+ `True`.
226
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
227
+ Whether to convert the image to RGB.
228
+ return_tensors (`str` or `TensorType`, *optional*):
229
+ The type of tensors to return. Can be one of:
230
+ - Unset: Return a list of `np.ndarray`.
231
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
232
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
233
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
234
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
235
+ """
236
+ image_mean = image_mean if image_mean is not None else self.image_mean
237
+ image_std = image_std if image_std is not None else self.image_std
238
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
239
+
240
+ images = make_list_of_images(images)
241
+
242
+ if not valid_images(images):
243
+ raise ValueError(
244
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
245
+ "torch.Tensor, tf.Tensor or jax.ndarray."
246
+ )
247
+
248
+ if do_convert_rgb:
249
+ images = [convert_to_rgb(image) for image in images]
250
+
251
+ image_sizes = []
252
+ img_processor = torchvision.transforms.Compose([
253
+ torchvision.transforms.ToTensor(),
254
+ torchvision.transforms.Normalize(image_mean, image_std)
255
+ ])
256
+
257
+ # PIL images
258
+ # HD_transform pad images to size of multiiply of 336, 336
259
+ # convert to RGB first
260
+ images = [image.convert('RGB') for image in images]
261
+ elems = [HD_transform(im, hd_num = self.num_crops) for im in images]
262
+ # tensor transform and normalize
263
+ hd_images = [img_processor(im) for im in elems]
264
+ # create global image
265
+ global_image = [torch.nn.functional.interpolate(im.unsqueeze(0).float(), size=(336, 336), mode='bicubic',).to(im.dtype) for im in hd_images]
266
+
267
+ # [(3, h, w)], where h, w is multiple of 336
268
+ shapes = [[im.size(1), im.size(2)] for im in hd_images]
269
+ num_img_tokens = [int(((h//336)*(w//336)+1)*144 + 1 + (h//336+1)*12) for h, w in shapes]
270
+ # reshape to channel dimension -> (num_images, num_crops, 3, 336, 336)
271
+ # (1, 3, h//336, 336, w//336, 336) -> (1, h//336, w//336, 3, 336, 336) -> (h//336*w//336, 3, 336, 336)
272
+ hd_images_reshape = [im.reshape(1, 3, h//336, 336, w//336, 336).permute(0,2,4,1,3,5).reshape(-1, 3, 336, 336).contiguous() for im, (h, w) in zip(hd_images, shapes)]
273
+ # concat global image and local image
274
+ hd_images_reshape = [torch.cat([_global_image] + [_im], dim=0) for _global_image, _im in zip(global_image, hd_images_reshape)]
275
+
276
+ # pad to max_num_crops
277
+ image_transformed = [pad_to_max_num_crops_tensor(im, self.num_crops+1) for im in hd_images_reshape]
278
+ image_transformed = torch.stack(image_transformed, dim=0)
279
+ image_sizes = [torch.LongTensor(_shapes) for _shapes in shapes]
280
+ padded_images = image_transformed
281
+ image_sizes = shapes
282
+
283
+ data = {"pixel_values": padded_images,
284
+ "image_sizes": image_sizes,
285
+ "num_img_tokens": num_img_tokens
286
+ }
287
+
288
+ return BatchFeature(data=data, tensor_type=return_tensors)
289
+
290
+ AutoImageProcessor.register("Phi3VImageProcessor", Phi3VImageProcessor)
291
+
292
+ transformers.Phi3VImageProcessor = Phi3VImageProcessor
293
+
294
+ class Phi3VProcessor(ProcessorMixin):
295
+ r"""
296
+ Constructs a Phi3-V processor which wraps a Phi3-V image processor and a LLaMa tokenizer into a single processor.
297
+
298
+ [`Phi3VProcessor`] offers all the functionalities of [`Phi3VImageProcessor`] and [`LlamaTokenizerFast`]. See the
299
+ [`~Phi3VProcessor.__call__`] and [`~Phi3VProcessor.decode`] for more information.
300
+
301
+ Args:
302
+ image_processor ([`Phi3VImageProcessor`], *optional*):
303
+ The image processor is a required input.
304
+ tokenizer ([`LlamaTokenizerFast`], *optional*):
305
+ The tokenizer is a required input.
306
+ """
307
+
308
+ attributes = ["image_processor", "tokenizer"]
309
+ image_processor_class = "Phi3VImageProcessor"
310
+ tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast")
311
+ special_image_token = "<|image|>"
312
+
313
+ def __init__(self, image_processor, tokenizer):
314
+ self.image_processor = image_processor
315
+ self.tokenizer = tokenizer
316
+ self.num_img_tokens = image_processor.num_img_tokens
317
+ self.img_tokens = [f"<|image_{i+1}|>" for i in range(1000000)]
318
+
319
+ def __call__(
320
+ self,
321
+ text: Union[TextInput, List[TextInput]],
322
+ images: ImageInput = None,
323
+ padding: Union[bool, str, PaddingStrategy] = False,
324
+ truncation: Union[bool, str, TruncationStrategy] = None,
325
+ max_length=None,
326
+ return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
327
+ ) -> BatchFeature:
328
+ """
329
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
330
+ and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
331
+ the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
332
+ Phi3ImageProcessor's [`~Phi3ImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
333
+ of the above two methods for more information.
334
+
335
+ Args:
336
+ text (`str`, `List[str]`, `List[List[str]]`):
337
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
338
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
339
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
340
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
341
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
342
+ tensor. Both channels-first and channels-last formats are supported.
343
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
344
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
345
+ index) among:
346
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
347
+ sequence if provided).
348
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
349
+ acceptable input length for the model if that argument is not provided.
350
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
351
+ lengths).
352
+ max_length (`int`, *optional*):
353
+ Maximum length of the returned list and optionally padding length (see above).
354
+ truncation (`bool`, *optional*):
355
+ Activates truncation to cut input sequences longer than `max_length` to `max_length`.
356
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
357
+ If set, will return tensors of a particular framework. Acceptable values are:
358
+
359
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
360
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
361
+ - `'np'`: Return NumPy `np.ndarray` objects.
362
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
363
+
364
+ Returns:
365
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
366
+
367
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
368
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
369
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
370
+ `None`).
371
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
372
+ """
373
+ if images is not None:
374
+ image_inputs = self.image_processor(images, return_tensors=return_tensors)
375
+ else:
376
+ image_inputs = {}
377
+ inputs = self._convert_images_texts_to_inputs(image_inputs, text, padding=padding, truncation=truncation, max_length=max_length, return_tensors=return_tensors)
378
+ return inputs
379
+
380
+ def calc_num_image_tokens(self, images: ImageInput):
381
+ """ Calculate the number of image tokens for each image.
382
+ Args:
383
+ images (`ImageInput`):
384
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
385
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
386
+ """
387
+ return self.image_processor.calc_num_image_tokens(images)
388
+
389
+ def calc_num_image_tokens_from_image_size(self, width, height):
390
+ """ Calculate the number of image token for an image with given width and height.
391
+ Args:
392
+ width (`int`):
393
+ Width of the image.
394
+ height (`int`):
395
+ Height of the image.
396
+ """
397
+ return self.image_processor.calc_num_image_tokens_from_image_size(width, height)
398
+
399
+
400
+ @property
401
+ def special_image_token_id(self):
402
+ return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
403
+
404
+ def get_special_image_token_id(self):
405
+ return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
406
+
407
+ def _convert_images_texts_to_inputs(self, images, texts, padding=False, truncation=None, max_length=None, return_tensors=None):
408
+
409
+ if not len(images):
410
+ model_inputs = self.tokenizer(texts, return_tensors=return_tensors, padding=padding, truncation=truncation, max_length=max_length)
411
+ return BatchFeature(data={**model_inputs})
412
+
413
+ pattern = r"<\|image_\d+\|>"
414
+ prompt_chunks = [self.tokenizer(chunk).input_ids for chunk in re.split(pattern, texts)]
415
+
416
+ if 'num_img_tokens' in images:
417
+ num_img_tokens = images['num_img_tokens']
418
+ else:
419
+ assert 'num_crops' in images, 'num_crops must be provided in images if num_img_tokens is not provided'
420
+ num_crops = images['num_crops']
421
+ num_img_tokens = [_num_crops * self.num_img_tokens for _num_crops in num_crops]
422
+
423
+ images, image_sizes = images['pixel_values'], images['image_sizes']
424
+
425
+ # image_tags needs to start from 1 to n
426
+ image_tags = re.findall(pattern, texts)
427
+ # image_ids = [int(s.split("|")[1].split("_")[-1]) * -1 for s in image_tags]
428
+ # image_ids_pad = [[iid]*num_img_tokens[i] for i, iid in enumerate(image_ids)]
429
+ image_ids = [int(s.split("|")[1].split("_")[-1]) for s in image_tags]
430
+ unique_image_ids = sorted(list(set(image_ids)))
431
+ # image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be [1, 4, 5]
432
+ # check the condition
433
+ assert unique_image_ids == list(range(1, len(unique_image_ids)+1)), f"image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be {unique_image_ids}"
434
+ # total images must be the same as the number of image tags
435
+ assert len(unique_image_ids) == len(images), f"total images must be the same as the number of image tags, got {len(unique_image_ids)} image tags and {len(images)} images"
436
+
437
+ image_ids_pad = [[-iid]*num_img_tokens[iid-1] for iid in image_ids]
438
+
439
+ def insert_separator(X, sep_list):
440
+ if len(X) > len(sep_list):
441
+ sep_list.append([])
442
+ return [ele for sublist in zip(X, sep_list) for ele in sublist]
443
+ input_ids = []
444
+ offset = 0
445
+ for x in insert_separator(prompt_chunks, image_ids_pad):
446
+ input_ids.extend(x[offset:])
447
+
448
+ input_ids = torch.tensor(input_ids, dtype=torch.long).unsqueeze(0)
449
+ attention_mask = (input_ids > -1000000).to(torch.long)
450
+
451
+ return BatchFeature(data={"input_ids": input_ids,
452
+ "attention_mask": attention_mask,
453
+ "pixel_values": images,
454
+ "image_sizes": image_sizes})
455
+
456
+
457
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
458
+ def batch_decode(self, *args, **kwargs):
459
+ """
460
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
461
+ refer to the docstring of this method for more information.
462
+ """
463
+ return self.tokenizer.batch_decode(*args, **kwargs)
464
+
465
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
466
+ def decode(self, *args, **kwargs):
467
+ """
468
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
469
+ the docstring of this method for more information.
470
+ """
471
+ return self.tokenizer.decode(*args, **kwargs)
472
+
473
+ @property
474
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
475
+ def model_input_names(self):
476
+ tokenizer_input_names = self.tokenizer.model_input_names
477
+ image_processor_input_names = self.image_processor.model_input_names
478
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
special_tokens_map.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|system|>",
4
+ "<|end|>",
5
+ "<|user|>",
6
+ "<|end|>"
7
+ ],
8
+ "bos_token": {
9
+ "content": "<s>",
10
+ "lstrip": false,
11
+ "normalized": false,
12
+ "rstrip": false,
13
+ "single_word": false
14
+ },
15
+ "eos_token": {
16
+ "content": "<|endoftext|>",
17
+ "lstrip": false,
18
+ "normalized": false,
19
+ "rstrip": false,
20
+ "single_word": false
21
+ },
22
+ "pad_token": {
23
+ "content": "<|endoftext|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false
28
+ },
29
+ "unk_token": {
30
+ "content": "<unk>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false
35
+ }
36
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": true,
27
+ "single_word": false,
28
+ "special": false
29
+ },
30
+ "32000": {
31
+ "content": "<|endoftext|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "32001": {
39
+ "content": "<|assistant|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": true,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "32002": {
47
+ "content": "<|placeholder1|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": true,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "32003": {
55
+ "content": "<|placeholder2|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": true,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "32004": {
63
+ "content": "<|placeholder3|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": true,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "32005": {
71
+ "content": "<|placeholder4|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": true,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "32006": {
79
+ "content": "<|system|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "32007": {
87
+ "content": "<|end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "32008": {
95
+ "content": "<|placeholder5|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": true,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "32009": {
103
+ "content": "<|placeholder6|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": true,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "32010": {
111
+ "content": "<|user|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": true
117
+ },
118
+ "32011": {
119
+ "content": "<|placeholder7|>",
120
+ "lstrip": false,
121
+ "normalized": false,
122
+ "rstrip": true,
123
+ "single_word": false,
124
+ "special": true
125
+ },
126
+ "32012": {
127
+ "content": "<|placeholder8|>",
128
+ "lstrip": false,
129
+ "normalized": false,
130
+ "rstrip": true,
131
+ "single_word": false,
132
+ "special": true
133
+ },
134
+ "32013": {
135
+ "content": "<|placeholder9|>",
136
+ "lstrip": false,
137
+ "normalized": false,
138
+ "rstrip": true,
139
+ "single_word": false,
140
+ "special": true
141
+ },
142
+ "32014": {
143
+ "content": "<|placeholder10|>",
144
+ "lstrip": false,
145
+ "normalized": false,
146
+ "rstrip": true,
147
+ "single_word": false,
148
+ "special": true
149
+ },
150
+ "32015": {
151
+ "content": "<|placeholder11|>",
152
+ "lstrip": false,
153
+ "normalized": false,
154
+ "rstrip": true,
155
+ "single_word": false,
156
+ "special": true
157
+ },
158
+ "32016": {
159
+ "content": "<|placeholder12|>",
160
+ "lstrip": false,
161
+ "normalized": false,
162
+ "rstrip": true,
163
+ "single_word": false,
164
+ "special": true
165
+ },
166
+ "32017": {
167
+ "content": "<|placeholder13|>",
168
+ "lstrip": false,
169
+ "normalized": false,
170
+ "rstrip": true,
171
+ "single_word": false,
172
+ "special": true
173
+ },
174
+ "32018": {
175
+ "content": "<|placeholder14|>",
176
+ "lstrip": false,
177
+ "normalized": false,
178
+ "rstrip": true,
179
+ "single_word": false,
180
+ "special": true
181
+ },
182
+ "32019": {
183
+ "content": "<|placeholder15|>",
184
+ "lstrip": false,
185
+ "normalized": false,
186
+ "rstrip": true,
187
+ "single_word": false,
188
+ "special": true
189
+ },
190
+ "32020": {
191
+ "content": "<|placeholder16|>",
192
+ "lstrip": false,
193
+ "normalized": false,
194
+ "rstrip": true,
195
+ "single_word": false,
196
+ "special": true
197
+ },
198
+ "32021": {
199
+ "content": "<|placeholder17|>",
200
+ "lstrip": false,
201
+ "normalized": false,
202
+ "rstrip": true,
203
+ "single_word": false,
204
+ "special": true
205
+ },
206
+ "32022": {
207
+ "content": "<|placeholder18|>",
208
+ "lstrip": false,
209
+ "normalized": false,
210
+ "rstrip": true,
211
+ "single_word": false,
212
+ "special": true
213
+ },
214
+ "32023": {
215
+ "content": "<|placeholder19|>",
216
+ "lstrip": false,
217
+ "normalized": false,
218
+ "rstrip": true,
219
+ "single_word": false,
220
+ "special": true
221
+ },
222
+ "32024": {
223
+ "content": "<|placeholder20|>",
224
+ "lstrip": false,
225
+ "normalized": false,
226
+ "rstrip": true,
227
+ "single_word": false,
228
+ "special": true
229
+ },
230
+ "32025": {
231
+ "content": "<|placeholder21|>",
232
+ "lstrip": false,
233
+ "normalized": false,
234
+ "rstrip": true,
235
+ "single_word": false,
236
+ "special": true
237
+ },
238
+ "32026": {
239
+ "content": "<|placeholder22|>",
240
+ "lstrip": false,
241
+ "normalized": false,
242
+ "rstrip": true,
243
+ "single_word": false,
244
+ "special": true
245
+ },
246
+ "32027": {
247
+ "content": "<|placeholder23|>",
248
+ "lstrip": false,
249
+ "normalized": false,
250
+ "rstrip": true,
251
+ "single_word": false,
252
+ "special": true
253
+ },
254
+ "32028": {
255
+ "content": "<|placeholder24|>",
256
+ "lstrip": false,
257
+ "normalized": false,
258
+ "rstrip": true,
259
+ "single_word": false,
260
+ "special": true
261
+ },
262
+ "32029": {
263
+ "content": "<|placeholder25|>",
264
+ "lstrip": false,
265
+ "normalized": false,
266
+ "rstrip": true,
267
+ "single_word": false,
268
+ "special": true
269
+ },
270
+ "32030": {
271
+ "content": "<|placeholder26|>",
272
+ "lstrip": false,
273
+ "normalized": false,
274
+ "rstrip": true,
275
+ "single_word": false,
276
+ "special": true
277
+ },
278
+ "32031": {
279
+ "content": "<|placeholder27|>",
280
+ "lstrip": false,
281
+ "normalized": false,
282
+ "rstrip": true,
283
+ "single_word": false,
284
+ "special": true
285
+ },
286
+ "32032": {
287
+ "content": "<|placeholder28|>",
288
+ "lstrip": false,
289
+ "normalized": false,
290
+ "rstrip": true,
291
+ "single_word": false,
292
+ "special": true
293
+ },
294
+ "32033": {
295
+ "content": "<|placeholder29|>",
296
+ "lstrip": false,
297
+ "normalized": false,
298
+ "rstrip": true,
299
+ "single_word": false,
300
+ "special": true
301
+ },
302
+ "32034": {
303
+ "content": "<|placeholder30|>",
304
+ "lstrip": false,
305
+ "normalized": false,
306
+ "rstrip": true,
307
+ "single_word": false,
308
+ "special": true
309
+ },
310
+ "32035": {
311
+ "content": "<|placeholder31|>",
312
+ "lstrip": false,
313
+ "normalized": false,
314
+ "rstrip": true,
315
+ "single_word": false,
316
+ "special": true
317
+ },
318
+ "32036": {
319
+ "content": "<|placeholder32|>",
320
+ "lstrip": false,
321
+ "normalized": false,
322
+ "rstrip": true,
323
+ "single_word": false,
324
+ "special": true
325
+ },
326
+ "32037": {
327
+ "content": "<|placeholder33|>",
328
+ "lstrip": false,
329
+ "normalized": false,
330
+ "rstrip": true,
331
+ "single_word": false,
332
+ "special": true
333
+ },
334
+ "32038": {
335
+ "content": "<|placeholder34|>",
336
+ "lstrip": false,
337
+ "normalized": false,
338
+ "rstrip": true,
339
+ "single_word": false,
340
+ "special": true
341
+ },
342
+ "32039": {
343
+ "content": "<|placeholder35|>",
344
+ "lstrip": false,
345
+ "normalized": false,
346
+ "rstrip": true,
347
+ "single_word": false,
348
+ "special": true
349
+ },
350
+ "32040": {
351
+ "content": "<|placeholder36|>",
352
+ "lstrip": false,
353
+ "normalized": false,
354
+ "rstrip": true,
355
+ "single_word": false,
356
+ "special": true
357
+ },
358
+ "32041": {
359
+ "content": "<|placeholder37|>",
360
+ "lstrip": false,
361
+ "normalized": false,
362
+ "rstrip": true,
363
+ "single_word": false,
364
+ "special": true
365
+ },
366
+ "32042": {
367
+ "content": "<|placeholder38|>",
368
+ "lstrip": false,
369
+ "normalized": false,
370
+ "rstrip": true,
371
+ "single_word": false,
372
+ "special": true
373
+ },
374
+ "32043": {
375
+ "content": "<|placeholder39|>",
376
+ "lstrip": false,
377
+ "normalized": false,
378
+ "rstrip": true,
379
+ "single_word": false,
380
+ "special": true
381
+ },
382
+ "32044": {
383
+ "content": "<|image|>",
384
+ "lstrip": false,
385
+ "normalized": false,
386
+ "rstrip": true,
387
+ "single_word": false,
388
+ "special": true
389
+ }
390
+ },
391
+ "additional_special_tokens": [
392
+ "<|system|>",
393
+ "<|end|>",
394
+ "<|user|>",
395
+ "<|end|>"
396
+ ],
397
+ "auto_map": {
398
+ "AutoProcessor": "microsoft/Phi-3.5-vision-instruct--processing_phi3_v.Phi3VProcessor"
399
+ },
400
+ "bos_token": "<s>",
401
+ "chat_template": "{% for message in messages %}{{'<|' + message['role'] + '|>' + '\n' + message['content'] + '<|end|>\n' }}{% endfor %}{% if add_generation_prompt and messages[-1]['role'] != 'assistant' %}{{- '<|assistant|>\n' -}}{% endif %}",
402
+ "clean_up_tokenization_spaces": false,
403
+ "eos_token": "<|endoftext|>",
404
+ "legacy": false,
405
+ "model_max_length": 131072,
406
+ "pad_token": "<|endoftext|>",
407
+ "padding_side": "right",
408
+ "processor_class": "Phi3VProcessor",
409
+ "sp_model_kwargs": {},
410
+ "tokenizer_class": "LlamaTokenizer",
411
+ "unk_token": "<unk>",
412
+ "use_default_system_prompt": false
413
+ }