MrLight commited on
Commit
37fd73d
1 Parent(s): bdca8d4

Upload folder using huggingface_hub

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