mjbuehler commited on
Commit
70e575b
1 Parent(s): f5e7ae9

Upload 6 files

Browse files
configuration_phi3_v.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 32064):
42
+ Vocabulary size of the Phi-3-V model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`Phi3VModel`].
44
+ hidden_size (`int`, *optional*, defaults to 3072):
45
+ Dimension of the hidden representations.
46
+ intermediate_size (`int`, *optional*, defaults to 8192):
47
+ Dimension of the MLP representations.
48
+ num_hidden_layers (`int`, *optional*, defaults to 32):
49
+ Number of hidden layers in the Transformer decoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 32):
51
+ Number of attention heads for each attention layer in the Transformer decoder.
52
+ num_key_value_heads (`int`, *optional*):
53
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
54
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
55
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
56
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
57
+ by meanpooling all the original heads within that group. For more details checkout [this
58
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
59
+ `num_attention_heads`.
60
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
61
+ Dropout probability for mlp outputs.
62
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
63
+ The dropout ratio for the embeddings.
64
+ attention_dropout (`float`, *optional*, defaults to 0.0):
65
+ The dropout ratio after computing the attention scores.
66
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
69
+ The maximum sequence length that this model might ever be used with.
70
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
71
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
72
+ original RoPE embeddings when using long scaling.
73
+ initializer_range (`float`, *optional*, defaults to 0.02):
74
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
75
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
76
+ The epsilon value used for the RMSNorm.
77
+ use_cache (`bool`, *optional*, defaults to `True`):
78
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
79
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
80
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
81
+ Whether to tie weight embeddings
82
+ rope_theta (`float`, *optional*, defaults to 10000.0):
83
+ The base period of the RoPE embeddings.
84
+ rope_scaling (`dict`, *optional*):
85
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
86
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be either `su` or `yarn` and
87
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
88
+ divided by the number of attention heads divided by 2.
89
+ bos_token_id (`int`, *optional*, defaults to 1):
90
+ The id of the "beginning-of-sequence" token.
91
+ eos_token_id (`int`, *optional*, defaults to 32000):
92
+ The id of the "end-of-sequence" token.
93
+ pad_token_id (`int`, *optional*, defaults to 32000):
94
+ The id of the padding token.
95
+ sliding_window (`int`, *optional*):
96
+ Sliding window attention window size. If `None`, no sliding window is applied.
97
+ embd_layer (`str`, *optional*, defaults to `"default"`):
98
+ The embedding layer to use. Can be either `"default"` or `"image"`. "default" uses the standard embedding for text.
99
+
100
+ Example:
101
+
102
+ ```python
103
+ >>> from transformers import Phi3VModel, Phi3VConfig
104
+
105
+ >>> # Initializing a Phi-3-V style configuration
106
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-vision-128k-instruct")
107
+
108
+ >>> # Initializing a model from the configuration
109
+ >>> model = Phi3VModel(configuration)
110
+
111
+ >>> # Accessing the model configuration
112
+ >>> configuration = model.config
113
+ ```"""
114
+
115
+ model_type = "phi3_v"
116
+ keys_to_ignore_at_inference = ["past_key_values"]
117
+
118
+ def __init__(
119
+ self,
120
+ vocab_size=32064,
121
+ hidden_size=3072,
122
+ intermediate_size=8192,
123
+ num_hidden_layers=32,
124
+ num_attention_heads=32,
125
+ num_key_value_heads=None,
126
+ resid_pdrop=0.0,
127
+ embd_pdrop=0.0,
128
+ attention_dropout=0.0,
129
+ hidden_act="silu",
130
+ max_position_embeddings=4096,
131
+ original_max_position_embeddings=4096,
132
+ initializer_range=0.02,
133
+ rms_norm_eps=1e-5,
134
+ use_cache=True,
135
+ tie_word_embeddings=False,
136
+ rope_theta=10000.0,
137
+ rope_scaling=None,
138
+ bos_token_id=1,
139
+ eos_token_id=32000,
140
+ pad_token_id=32000,
141
+ sliding_window=None,
142
+ embd_layer: str = "default",
143
+ **kwargs,
144
+ ):
145
+ self.vocab_size = vocab_size
146
+ self.hidden_size = hidden_size
147
+ self.intermediate_size = intermediate_size
148
+ self.num_hidden_layers = num_hidden_layers
149
+ self.num_attention_heads = num_attention_heads
150
+
151
+ if num_key_value_heads is None:
152
+ num_key_value_heads = num_attention_heads
153
+
154
+ self.num_key_value_heads = num_key_value_heads
155
+ self.resid_pdrop = resid_pdrop
156
+ self.embd_pdrop = embd_pdrop
157
+ self.attention_dropout = attention_dropout
158
+ self.hidden_act = hidden_act
159
+ self.max_position_embeddings = max_position_embeddings
160
+ self.original_max_position_embeddings = original_max_position_embeddings
161
+ self.initializer_range = initializer_range
162
+ self.rms_norm_eps = rms_norm_eps
163
+ self.use_cache = use_cache
164
+ self.rope_theta = rope_theta
165
+ self.rope_scaling = rope_scaling
166
+ self._rope_scaling_validation()
167
+ self.sliding_window = sliding_window
168
+ self.embd_layer = embd_layer
169
+
170
+
171
+ super().__init__(
172
+ bos_token_id=bos_token_id,
173
+ eos_token_id=eos_token_id,
174
+ pad_token_id=pad_token_id,
175
+ tie_word_embeddings=tie_word_embeddings,
176
+ **kwargs,
177
+ )
178
+
179
+ def _rope_scaling_validation(self):
180
+ """
181
+ Validate the `rope_scaling` configuration.
182
+ """
183
+ if self.rope_scaling is None:
184
+ return
185
+
186
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
187
+ raise ValueError(
188
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
189
+ f"got {self.rope_scaling}"
190
+ )
191
+ rope_scaling_type = self.rope_scaling.get("type", None)
192
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
193
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
194
+ if rope_scaling_type is None or rope_scaling_type not in ["su", "yarn"]:
195
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['su', 'yarn'], got {rope_scaling_type}")
196
+ if not (
197
+ isinstance(rope_scaling_short_factor, list)
198
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
199
+ ):
200
+ raise ValueError(
201
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
202
+ )
203
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
204
+ raise ValueError(
205
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
206
+ )
207
+ if not (
208
+ isinstance(rope_scaling_long_factor, list)
209
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
210
+ ):
211
+ raise ValueError(
212
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
213
+ )
214
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
215
+ raise ValueError(
216
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
217
+ )
image_embedding_phi3_v.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math
17
+ import torch
18
+ import torch.nn as nn
19
+ from transformers import CLIPVisionModel, PretrainedConfig
20
+ from transformers import CLIPVisionConfig
21
+ from transformers.utils import logging
22
+ from datetime import datetime
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ CLIP_VIT_LARGE_PATCH14_336_CONFIG = CLIPVisionConfig(
27
+ attention_dropout=0.0,
28
+ dropout=0.0,
29
+ hidden_act="quick_gelu",
30
+ hidden_size=1024,
31
+ image_size=336,
32
+ initializer_factor=1.0,
33
+ initializer_range=0.02,
34
+ intermediate_size=4096,
35
+ layer_norm_eps=1e-05,
36
+ num_attention_heads=16,
37
+ num_channels=3,
38
+ num_hidden_layers=24,
39
+ patch_size=14,
40
+ projection_dim=768
41
+ )
42
+
43
+ class Phi3ImageEmbedding(nn.Module):
44
+ """Phi3 Image embedding."""
45
+
46
+ def __init__(self, config: PretrainedConfig, wte=None, **kwargs) -> None:
47
+ super().__init__()
48
+
49
+ # n_embed or hidden_size
50
+ hidden_size = config.n_embd if hasattr(config, 'n_embd') else config.hidden_size
51
+ if hasattr(config, 'embd_pdrop') or hasattr(config, 'embed_pdrop'):
52
+ embd_drop = config.embd_pdrop if hasattr(config, 'embd_pdrop') else config.embed_pdrop
53
+ self.drop = nn.Dropout(embd_drop)
54
+ else:
55
+ self.drop = None
56
+
57
+ self.wte = wte
58
+
59
+ if isinstance(config.img_processor, dict) and config.img_processor.get('name', None) == 'clip_vision_model':
60
+ assert 'model_name' in config.img_processor, 'model_name must be provided for CLIPVisionModel'
61
+ assert 'image_dim_out' in config.img_processor, 'image_dim_out must be provided for CLIPVisionModel'
62
+ assert 'num_img_tokens' in config.img_processor, 'num_img_tokens must be provided for CLIPVisionModel'
63
+ assert config.img_processor['model_name'] == 'openai/clip-vit-large-patch14-336'
64
+ clip_config = CLIP_VIT_LARGE_PATCH14_336_CONFIG
65
+ self.img_processor = CLIPVisionModel(clip_config)
66
+ image_dim_out = config.img_processor['image_dim_out']
67
+ self.num_img_tokens = config.img_processor['num_img_tokens']
68
+ else:
69
+ raise NotImplementedError(f'img_processor = {config.img_processor}, not implemented')
70
+
71
+ self.image_dim_out = image_dim_out
72
+ self.img_sizes = None
73
+
74
+ # global_gn and sub_gn for hd transform, serves as line separator
75
+ self.use_hd_transform = kwargs.get('use_hd_transform', False)
76
+ self.with_learnable_separator = kwargs.get('with_learnable_separator', False)
77
+ self.hd_transform_order = kwargs.get('hd_transform_order', 'glb_sub')
78
+ # with_hd_transform and with_learnable_separator should have same value
79
+ assert self.use_hd_transform == self.with_learnable_separator, 'use_hd_transform and with_learnable_separator should have same value'
80
+ if self.with_learnable_separator:
81
+ assert self.use_hd_transform, 'learnable separator is only for hd transform'
82
+ # 1024 * 4, merge spatial to channel dimension
83
+ self.glb_GN = nn.Parameter(torch.zeros([1, 1, self.image_dim_out * 4]))
84
+ self.sub_GN = nn.Parameter(torch.zeros([1, 1, 1, self.image_dim_out * 4]))
85
+ logger.info(f'learnable separator enabled for hd transform, hd_transform_order = {self.hd_transform_order}')
86
+
87
+ projection_cls = kwargs.get('projection_cls', 'linear')
88
+ if projection_cls == 'linear':
89
+ self.img_projection = nn.Linear(image_dim_out, hidden_size)
90
+ elif projection_cls == 'mlp' and self.use_hd_transform:
91
+ dim_projection = hidden_size
92
+ depth = 2
93
+ layers = [nn.Linear(image_dim_out * 4, dim_projection)]
94
+ for _ in range(1, depth):
95
+ layers.extend([nn.GELU(),
96
+ nn.Linear(dim_projection, dim_projection)])
97
+ self.img_projection = nn.Sequential(*layers)
98
+ elif projection_cls == 'mlp':
99
+ dim_projection = hidden_size
100
+ depth = 2
101
+ layers = [nn.Linear(image_dim_out, dim_projection)]
102
+ for _ in range(1, depth):
103
+ layers.extend([nn.GELU(),
104
+ nn.Linear(dim_projection, dim_projection)])
105
+ self.img_projection = nn.Sequential(*layers)
106
+ else:
107
+ raise NotImplementedError(f'projection_cls = {projection_cls}, not implemented')
108
+
109
+ self.vocab_size = config.vocab_size
110
+ self.img_features = None
111
+
112
+ if isinstance(config.img_processor, dict):
113
+ self.layer_idx = config.img_processor.get('layer_idx', -2)
114
+ self.type_feature = config.img_processor.get('type_feature', 'patch')
115
+ else:
116
+ self.layer_idx = -2
117
+ self.type_feature = 'patch'
118
+
119
+
120
+ def set_img_features(self, img_features: torch.FloatTensor) -> None:
121
+ self.img_features = img_features
122
+
123
+ def set_img_sizes(self, img_sizes: torch.LongTensor) -> None:
124
+ self.img_sizes = img_sizes
125
+
126
+ def get_img_features(self, img_embeds: torch.FloatTensor) -> torch.FloatTensor:
127
+ LAYER_IDX = self.layer_idx
128
+ TYPE_FEATURE = self.type_feature
129
+
130
+ img_processor_output = self.img_processor(img_embeds, output_hidden_states=True)
131
+ img_feature = img_processor_output.hidden_states[LAYER_IDX]
132
+
133
+ if TYPE_FEATURE == "patch":
134
+ patch_feature = img_feature[:, 1:]
135
+ return patch_feature
136
+
137
+ if TYPE_FEATURE == "cls_patch":
138
+ return img_feature
139
+
140
+ raise NotImplementedError
141
+
142
+ def forward(self, input_ids: torch.LongTensor, pixel_values: torch.FloatTensor, image_sizes=None) -> torch.FloatTensor:
143
+
144
+ MAX_INPUT_ID = int(1e9)
145
+ img_embeds = pixel_values
146
+ img_sizes = image_sizes
147
+
148
+ if self.img_features is not None:
149
+ img_embeds = self.img_features.clone()
150
+ self.img_features = None
151
+
152
+ if self.img_sizes is not None:
153
+ img_sizes = self.img_sizes
154
+
155
+ input_shape = input_ids.size()
156
+ input_ids = input_ids.view(-1, input_shape[-1])
157
+
158
+ with torch.no_grad():
159
+ positions = torch.nonzero((input_ids < 0) & (input_ids > -MAX_INPUT_ID), as_tuple=False)
160
+
161
+ select = False
162
+
163
+ if isinstance(self.img_projection, nn.Sequential):
164
+ target_device = self.img_projection[0].bias.device
165
+ target_dtype = self.img_projection[0].bias.dtype
166
+ else: # It's a single nn.Linear layer
167
+ target_device = self.img_projection.bias.device
168
+ target_dtype = self.img_projection.bias.dtype
169
+
170
+ if len(positions.tolist()) > 0:
171
+ with torch.no_grad():
172
+ g_values = abs(input_ids[positions[:, 0], positions[:, 1]])
173
+
174
+ if self.use_hd_transform and img_sizes is not None and len(img_sizes):
175
+ hd_transform = True
176
+ assert img_embeds.ndim == 5, f'img_embeds size: {img_embeds.size()}, expect 5D tensor for hd transform'
177
+ # img_embeds: (num_images, max_num_crops, 3, H, W)
178
+ # img_sizes: (num_images, 2).view(1, -1)
179
+
180
+ start_time = datetime.now()
181
+ bs = img_embeds.shape[0]
182
+ # Nx(HW)xC
183
+ img_features = self.get_img_features(img_embeds.flatten(0, 1))
184
+ base_feat_height = base_feat_width = int(img_features.shape[1] ** 0.5)
185
+
186
+ assert base_feat_height == 24 and base_feat_width == 24, f'base_feat_height: {base_feat_height}, base_feat_width: {base_feat_width}, expect 24x24 features for hd transform'
187
+
188
+ # bs x max_num_crops x (24x24) x C
189
+ img_features = img_features.view(bs, -1, base_feat_height * base_feat_width, self.image_dim_out)
190
+ C = self.image_dim_out
191
+ H = base_feat_height
192
+
193
+ output_imgs = []
194
+ output_len = []
195
+ # training is tensor, inference is list
196
+ if isinstance(img_sizes, torch.Tensor):
197
+ img_sizes = img_sizes.view(-1, 2)
198
+ for _bs in range(bs):
199
+ h, w = img_sizes[_bs]
200
+ h = h // 336
201
+ w = w // 336
202
+ B_ = h * w
203
+
204
+ # 1 x (24x24) x 1024
205
+ global_img_feature = img_features[_bs, :1]
206
+
207
+ # 1 x 12 x 12 x 4096
208
+ glb_img = global_img_feature.reshape(1,H,H,C).reshape(1,H//2,2,H//2,2,C).contiguous().permute(0,1,3,2,4,5).reshape(1,H//2,H//2,4*C).contiguous()
209
+ temp_glb_GN = self.sub_GN.repeat(1, H//2, 1, 1)
210
+
211
+ # 1 x 156 x 4096
212
+ glb_img = torch.cat([glb_img, temp_glb_GN], dim=2).reshape(1,-1,4*C)
213
+
214
+ # (max_num_crops-1) x (12x12) x C
215
+ sub_img = img_features[_bs, 1:]
216
+ # 16x574x1024
217
+ # get rid of padding sub_img
218
+ sub_img = sub_img[:B_]
219
+
220
+ # (num_crops, 12, 2, 12, 2, 1024) -> (num_crops, 12, 12, 2, 2, 1024) -> (num_crops, 12*12, 4*1024)
221
+ sub_img = sub_img.reshape(B_,H,H,C).reshape(B_,H//2,2,H//2,2,C).contiguous().permute(0,1,3,2,4,5).reshape(B_,-1,4*C).contiguous()
222
+ sub_img = sub_img.reshape(1, h, w, 12, 12, -1).permute(0,1,3,2,4,5).reshape(1,h*12,w*12,4*C)
223
+ temp_sub_GN = self.sub_GN.repeat(1, h*12, 1, 1)
224
+ sub_img = torch.cat([sub_img, temp_sub_GN], dim=2).reshape(1,-1,4*C)
225
+ # (1, num_img_tokens, 1024*4)
226
+
227
+ # glb + sub
228
+ if self.hd_transform_order == 'glb_sub':
229
+ output_imgs.append(torch.cat([glb_img, self.glb_GN, sub_img], dim=1))
230
+ elif self.hd_transform_order == 'sub_glb':
231
+ output_imgs.append(torch.cat([sub_img, self.glb_GN, glb_img], dim=1))
232
+ else:
233
+ raise NotImplementedError(f'hd_transform_order = {self.hd_transform_order}, not implemented')
234
+
235
+ temp_len = int((h*w+1)*144 + 1 + (h+1)*12)
236
+ assert temp_len == output_imgs[-1].shape[1], f'temp_len: {temp_len}, output_imgs[-1].shape[1]: {output_imgs[-1].shape[1]}'
237
+ output_len.append(temp_len)
238
+
239
+ num_img_tokens = output_len
240
+ img_set_tensor = []
241
+ for _output_img in output_imgs:
242
+ img_feature_proj = self.img_projection(_output_img.to(target_device).to(target_dtype))
243
+ img_set_tensor.append(img_feature_proj)
244
+ logger.info(f'img_embeds size: {img_embeds.size()}, image sizes: {img_sizes} loading time {datetime.now() - start_time}')
245
+ elif img_embeds.ndim == 4:
246
+ selected_g_values = g_values[::self.num_img_tokens]
247
+ assert len(img_embeds) == len(selected_g_values), f'img_embeds size: {img_embeds.size()}, selected_g_values size: {len(selected_g_values)}, selected_g_value {selected_g_values}'
248
+ start_time = datetime.now()
249
+ tt = (
250
+ self.get_img_features(img_embeds)
251
+ .to(target_device)
252
+ .to(target_dtype)
253
+ .reshape(-1, self.image_dim_out)
254
+ )
255
+ logger.info(f'img_embeds size: {img_embeds.size()}, loading time {datetime.now() - start_time}')
256
+ img_set_tensor = self.img_projection(tt) # adapted visual features.
257
+ elif img_embeds.ndim == 3:
258
+ selected_g_values = g_values[::self.num_img_tokens]
259
+ assert len(img_embeds) == len(selected_g_values), f'img_embeds size: {img_embeds.size()}, selected_g_values size: {len(selected_g_values)}, selected_g_value {selected_g_values}'
260
+ tt = (
261
+ img_embeds
262
+ .to(target_device)
263
+ .to(target_dtype)
264
+ .view(-1, self.image_dim_out)
265
+ )
266
+ img_set_tensor = self.img_projection(tt) # adapted visual features.
267
+ else:
268
+ raise NotImplementedError
269
+ select = True
270
+
271
+ with torch.no_grad():
272
+ input_ids.clamp_min_(0).clamp_max_(self.vocab_size)
273
+
274
+ hidden_states = self.wte(input_ids)
275
+
276
+ if select:
277
+ if hd_transform:
278
+ idx = 0
279
+ for i, cnt in enumerate(num_img_tokens):
280
+ hidden_states[positions[idx, 0], positions[idx, 1] : positions[idx, 1] + cnt] = (
281
+ img_set_tensor[i]
282
+ .to(hidden_states.dtype)
283
+ .to(hidden_states.device)
284
+ )
285
+ idx += cnt
286
+ else:
287
+ idx = 0
288
+ assert len(selected_g_values) * self.num_img_tokens == len(img_set_tensor), f'len(selected_g_values) * self.num_img_tokens = {len(selected_g_values) * self.num_img_tokens}, len(img_set_tensor) = {len(img_set_tensor)}'
289
+ for i, g in enumerate(selected_g_values):
290
+ cnt = self.num_img_tokens
291
+ hidden_states[positions[idx, 0], positions[idx, 1] : positions[idx, 1] + cnt] = (
292
+ img_set_tensor[i * cnt : (i + 1) * cnt]
293
+ .to(hidden_states.dtype)
294
+ .to(hidden_states.device)
295
+ )
296
+ idx += cnt
297
+
298
+ if self.drop is not None:
299
+ hidden_states = self.drop(hidden_states)
300
+
301
+ return hidden_states
image_processing_phi3_v.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
128
+ Args:
129
+ image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
130
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
131
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
132
+ image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
133
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
134
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
135
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
136
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
137
+ Whether to convert the image to RGB.
138
+ """
139
+
140
+ model_input_names = ["pixel_values"]
141
+
142
+ def __init__(
143
+ self,
144
+ num_crops: int = 1,
145
+ image_mean: Optional[Union[float, List[float]]] = None,
146
+ image_std: Optional[Union[float, List[float]]] = None,
147
+ do_convert_rgb: bool = True,
148
+ **kwargs,
149
+ ) -> None:
150
+ super().__init__(**kwargs)
151
+ self.num_crops = num_crops
152
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
153
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
154
+ self.do_convert_rgb = do_convert_rgb
155
+
156
+ def calc_num_image_tokens(
157
+ self,
158
+ images: ImageInput
159
+ ):
160
+ """ Calculate the number of image tokens for each image.
161
+ Args:
162
+ images (`ImageInput`):
163
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
164
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
165
+ """
166
+ images = make_list_of_images(images)
167
+
168
+ if not valid_images(images):
169
+ raise ValueError(
170
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
171
+ "torch.Tensor, tf.Tensor or jax.ndarray."
172
+ )
173
+
174
+ images = [image.convert('RGB') for image in images]
175
+ # (H, W, C)
176
+ elems = [HD_transform(im, hd_num = self.num_crops) for im in images]
177
+ shapes = [[im.size[1], im.size[0]] for im in elems]
178
+ num_img_tokens = [int((h//336*w//336+1)*144 + 1 + (h//336+1)*12) for h, w in shapes]
179
+ return num_img_tokens
180
+
181
+ def calc_num_image_tokens_from_image_size(self, width, height):
182
+ """
183
+ Calculate the number of image tokens for a given image size.
184
+ Args:
185
+ width (`int`): Width of the image.
186
+ height (`int`): Height of the image.
187
+ """
188
+ new_width, new_height = calc_hd_transform_size(width, height, hd_num=self.num_crops)
189
+ num_img_tokens = int((new_height // 336 * new_width // 336 + 1) * 144 + 1 + (new_height // 336 + 1) * 12)
190
+ return num_img_tokens
191
+
192
+ def preprocess(
193
+ self,
194
+ images: ImageInput,
195
+ image_mean: Optional[Union[float, List[float]]] = None,
196
+ image_std: Optional[Union[float, List[float]]] = None,
197
+ do_convert_rgb: bool = None,
198
+ return_tensors: Optional[Union[str, TensorType]] = None,
199
+ ):
200
+ """
201
+ Args:
202
+ images (`ImageInput`):
203
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
204
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
205
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
206
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
207
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
208
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
209
+ `True`.
210
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
211
+ Whether to convert the image to RGB.
212
+ return_tensors (`str` or `TensorType`, *optional*):
213
+ The type of tensors to return. Can be one of:
214
+ - Unset: Return a list of `np.ndarray`.
215
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
216
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
217
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
218
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
219
+ """
220
+ image_mean = image_mean if image_mean is not None else self.image_mean
221
+ image_std = image_std if image_std is not None else self.image_std
222
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
223
+
224
+ images = make_list_of_images(images)
225
+
226
+ if not valid_images(images):
227
+ raise ValueError(
228
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
229
+ "torch.Tensor, tf.Tensor or jax.ndarray."
230
+ )
231
+
232
+ if do_convert_rgb:
233
+ images = [convert_to_rgb(image) for image in images]
234
+
235
+ image_sizes = []
236
+ img_processor = torchvision.transforms.Compose([
237
+ torchvision.transforms.ToTensor(),
238
+ torchvision.transforms.Normalize(image_mean, image_std)
239
+ ])
240
+
241
+ # PIL images
242
+ # HD_transform pad images to size of multiiply of 336, 336
243
+ # convert to RGB first
244
+ images = [image.convert('RGB') for image in images]
245
+ elems = [HD_transform(im, hd_num = self.num_crops) for im in images]
246
+ # tensor transform and normalize
247
+ hd_images = [img_processor(im) for im in elems]
248
+ # create global image
249
+ global_image = [torch.nn.functional.interpolate(im.unsqueeze(0).float(), size=(336, 336), mode='bicubic',).to(im.dtype) for im in hd_images]
250
+
251
+ # [(3, h, w)], where h, w is multiple of 336
252
+ shapes = [[im.size(1), im.size(2)] for im in hd_images]
253
+ num_img_tokens = [int((h//336*w//336+1)*144 + 1 + (h//336+1)*12) for h, w in shapes]
254
+ # reshape to channel dimension -> (num_images, num_crops, 3, 336, 336)
255
+ # (1, 3, h//336, 336, w//336, 336) -> (1, h//336, w//336, 3, 336, 336) -> (h//336*w//336, 3, 336, 336)
256
+ 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)]
257
+ # concat global image and local image
258
+ hd_images_reshape = [torch.cat([_global_image] + [_im], dim=0) for _global_image, _im in zip(global_image, hd_images_reshape)]
259
+
260
+ # pad to max_num_crops
261
+ image_transformed = [pad_to_max_num_crops_tensor(im, self.num_crops+1) for im in hd_images_reshape]
262
+ image_transformed = torch.stack(image_transformed, dim=0)
263
+ image_sizes = [torch.LongTensor(_shapes) for _shapes in shapes]
264
+ padded_images = image_transformed
265
+ image_sizes = shapes
266
+
267
+ data = {"pixel_values": padded_images,
268
+ "image_sizes": image_sizes,
269
+ "num_img_tokens": num_img_tokens
270
+ }
271
+
272
+ return BatchFeature(data=data, tensor_type=return_tensors)
273
+
274
+ AutoImageProcessor.register("Phi3VImageProcessor", Phi3VImageProcessor)
modeling_phi3_v.py ADDED
@@ -0,0 +1,1632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from .configuration_phi3_v import Phi3VConfig
49
+ from .image_embedding_phi3_v import Phi3ImageEmbedding
50
+
51
+
52
+ if is_flash_attn_2_available():
53
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
54
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
55
+
56
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-vision-128k-instruct"
61
+ _CONFIG_FOR_DOC = "Phi3VConfig"
62
+
63
+ PHI3V_PRETRAINED_MODEL_ARCHIVE_LIST = [
64
+ "microsoft/Phi-3-vision-128k-instruct",
65
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
66
+ ]
67
+
68
+
69
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
70
+ class Phi3RMSNorm(nn.Module):
71
+ def __init__(self, hidden_size, eps=1e-6):
72
+ """
73
+ Phi3RMSNorm is equivalent to T5LayerNorm
74
+ """
75
+ super().__init__()
76
+ self.weight = nn.Parameter(torch.ones(hidden_size))
77
+ self.variance_epsilon = eps
78
+
79
+ def forward(self, hidden_states):
80
+ input_dtype = hidden_states.dtype
81
+ hidden_states = hidden_states.to(torch.float32)
82
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
83
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
84
+ return self.weight * hidden_states.to(input_dtype)
85
+
86
+
87
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
88
+ def _get_unpad_data(attention_mask):
89
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
90
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
91
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
92
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
93
+ return (
94
+ indices,
95
+ cu_seqlens,
96
+ max_seqlen_in_batch,
97
+ )
98
+
99
+
100
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
101
+ class Phi3RotaryEmbedding(nn.Module):
102
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
103
+ super().__init__()
104
+
105
+ self.dim = dim
106
+ self.max_position_embeddings = max_position_embeddings
107
+ self.base = base
108
+ self.register_buffer("inv_freq", None, persistent=False)
109
+
110
+ @torch.no_grad()
111
+ def forward(self, x, position_ids, seq_len=None):
112
+ # x: [bs, num_attention_heads, seq_len, head_size]
113
+ if self.inv_freq is None:
114
+ self.inv_freq = 1.0 / (
115
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
116
+ )
117
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
118
+ position_ids_expanded = position_ids[:, None, :].float()
119
+ # Force float32 since bfloat16 loses precision on long contexts
120
+ # See https://github.com/huggingface/transformers/pull/29285
121
+ device_type = x.device.type
122
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
123
+ with torch.autocast(device_type=device_type, enabled=False):
124
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
125
+ emb = torch.cat((freqs, freqs), dim=-1)
126
+ cos = emb.cos()
127
+ sin = emb.sin()
128
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
129
+
130
+
131
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
132
+ def __init__(self, dim, config, device=None):
133
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
134
+
135
+ self.short_factor = config.rope_scaling["short_factor"]
136
+ self.long_factor = config.rope_scaling["long_factor"]
137
+ self.original_max_position_embeddings = config.original_max_position_embeddings
138
+
139
+ @torch.no_grad()
140
+ def forward(self, x, position_ids, seq_len=None):
141
+ seq_len = torch.max(position_ids) + 1
142
+ if seq_len > self.original_max_position_embeddings:
143
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
144
+ else:
145
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
146
+
147
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
148
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
149
+
150
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
151
+ position_ids_expanded = position_ids[:, None, :].float()
152
+
153
+ # Force float32 since bfloat16 loses precision on long contexts
154
+ # See https://github.com/huggingface/transformers/pull/29285
155
+ device_type = x.device.type
156
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
157
+ with torch.autocast(device_type=device_type, enabled=False):
158
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
159
+ emb = torch.cat((freqs, freqs), dim=-1)
160
+
161
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
162
+ if scale <= 1.0:
163
+ scaling_factor = 1.0
164
+ else:
165
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
166
+
167
+ cos = emb.cos() * scaling_factor
168
+ sin = emb.sin() * scaling_factor
169
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
170
+
171
+
172
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
173
+ def __init__(self, dim, config, device=None):
174
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
175
+
176
+ self.short_factor = config.rope_scaling["short_factor"]
177
+ self.long_factor = config.rope_scaling["long_factor"]
178
+ self.original_max_position_embeddings = config.original_max_position_embeddings
179
+
180
+ @torch.no_grad()
181
+ def forward(self, x, position_ids, seq_len=None):
182
+ seq_len = torch.max(position_ids) + 1
183
+ if seq_len > self.original_max_position_embeddings:
184
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
185
+ else:
186
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
187
+
188
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
189
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
190
+
191
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
192
+ position_ids_expanded = position_ids[:, None, :].float()
193
+
194
+ # Force float32 since bfloat16 loses precision on long contexts
195
+ # See https://github.com/huggingface/transformers/pull/29285
196
+ device_type = x.device.type
197
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
198
+ with torch.autocast(device_type=device_type, enabled=False):
199
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
200
+ emb = torch.cat((freqs, freqs), dim=-1)
201
+
202
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
203
+ if scale <= 1.0:
204
+ scaling_factor = 1.0
205
+ else:
206
+ scaling_factor = 0.1 * math.log(scale) + 1.0
207
+
208
+ cos = emb.cos() * scaling_factor
209
+ sin = emb.sin() * scaling_factor
210
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
211
+
212
+
213
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
214
+ def rotate_half(x):
215
+ """Rotates half the hidden dims of the input."""
216
+ x1 = x[..., : x.shape[-1] // 2]
217
+ x2 = x[..., x.shape[-1] // 2 :]
218
+ return torch.cat((-x2, x1), dim=-1)
219
+
220
+
221
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
222
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
223
+ """Applies Rotary Position Embedding to the query and key tensors.
224
+
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
+
596
+ Args:
597
+ query_states (`torch.Tensor`):
598
+ Input query states to be passed to Flash Attention API
599
+ key_states (`torch.Tensor`):
600
+ Input key states to be passed to Flash Attention API
601
+ value_states (`torch.Tensor`):
602
+ Input value states to be passed to Flash Attention API
603
+ attention_mask (`torch.Tensor`):
604
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
605
+ position of padding tokens and 1 for the position of non-padding tokens.
606
+ dropout (`float`):
607
+ Attention dropout
608
+ softmax_scale (`float`, *optional*):
609
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
610
+ use_sliding_windows (`bool`, *optional*):
611
+ Whether to activate sliding window attention.
612
+ """
613
+ if not self._flash_attn_uses_top_left_mask:
614
+ causal = self.is_causal
615
+ else:
616
+ # 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__.
617
+ causal = self.is_causal and query_length != 1
618
+
619
+ # Contains at least one padding token in the sequence
620
+ if attention_mask is not None:
621
+ batch_size = query_states.shape[0]
622
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
623
+ query_states, key_states, value_states, attention_mask, query_length
624
+ )
625
+
626
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
627
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
628
+
629
+ if not use_sliding_windows:
630
+ attn_output_unpad = flash_attn_varlen_func(
631
+ query_states,
632
+ key_states,
633
+ value_states,
634
+ cu_seqlens_q=cu_seqlens_q,
635
+ cu_seqlens_k=cu_seqlens_k,
636
+ max_seqlen_q=max_seqlen_in_batch_q,
637
+ max_seqlen_k=max_seqlen_in_batch_k,
638
+ dropout_p=dropout,
639
+ softmax_scale=softmax_scale,
640
+ causal=causal,
641
+ )
642
+ else:
643
+ attn_output_unpad = flash_attn_varlen_func(
644
+ query_states,
645
+ key_states,
646
+ value_states,
647
+ cu_seqlens_q=cu_seqlens_q,
648
+ cu_seqlens_k=cu_seqlens_k,
649
+ max_seqlen_q=max_seqlen_in_batch_q,
650
+ max_seqlen_k=max_seqlen_in_batch_k,
651
+ dropout_p=dropout,
652
+ softmax_scale=softmax_scale,
653
+ causal=causal,
654
+ window_size=(self.config.sliding_window, self.config.sliding_window),
655
+ )
656
+
657
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
658
+ else:
659
+ if not use_sliding_windows:
660
+ attn_output = flash_attn_func(
661
+ query_states,
662
+ key_states,
663
+ value_states,
664
+ dropout,
665
+ softmax_scale=softmax_scale,
666
+ causal=causal,
667
+ )
668
+ else:
669
+ attn_output = flash_attn_func(
670
+ query_states,
671
+ key_states,
672
+ value_states,
673
+ dropout,
674
+ softmax_scale=softmax_scale,
675
+ causal=causal,
676
+ window_size=(self.config.sliding_window, self.config.sliding_window),
677
+ )
678
+
679
+ return attn_output
680
+
681
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
682
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
683
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
684
+
685
+ # On the first iteration we need to properly re-create the padding mask
686
+ # by slicing it on the proper place
687
+ if kv_seq_len != attention_mask.shape[-1]:
688
+ attention_mask_num_tokens = attention_mask.shape[-1]
689
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
690
+
691
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
692
+
693
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
694
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
695
+
696
+ if query_length == kv_seq_len:
697
+ query_layer = index_first_axis(
698
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
699
+ )
700
+ cu_seqlens_q = cu_seqlens_k
701
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
702
+ indices_q = indices_k
703
+ elif query_length == 1:
704
+ max_seqlen_in_batch_q = 1
705
+ cu_seqlens_q = torch.arange(
706
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
707
+ ) # There is a memcpy here, that is very bad.
708
+ indices_q = cu_seqlens_q[:-1]
709
+ query_layer = query_layer.squeeze(1)
710
+ else:
711
+ # The -q_len: slice assumes left padding.
712
+ attention_mask = attention_mask[:, -query_length:]
713
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
714
+
715
+ return (
716
+ query_layer,
717
+ key_layer,
718
+ value_layer,
719
+ indices_q,
720
+ (cu_seqlens_q, cu_seqlens_k),
721
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
722
+ )
723
+
724
+
725
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
726
+ # TODO @Arthur no longer copied from LLama after static cache
727
+ class Phi3SdpaAttention(Phi3Attention):
728
+ """
729
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
730
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
731
+ SDPA API.
732
+ """
733
+
734
+ # Adapted from Phi3Attention.forward
735
+ def forward(
736
+ self,
737
+ hidden_states: torch.Tensor,
738
+ attention_mask: Optional[torch.Tensor] = None,
739
+ position_ids: Optional[torch.LongTensor] = None,
740
+ past_key_value: Optional[Cache] = None,
741
+ output_attentions: bool = False,
742
+ use_cache: bool = False,
743
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
744
+ if output_attentions:
745
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
746
+ logger.warning_once(
747
+ "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, "
748
+ '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.'
749
+ )
750
+ return super().forward(
751
+ hidden_states=hidden_states,
752
+ attention_mask=attention_mask,
753
+ position_ids=position_ids,
754
+ past_key_value=past_key_value,
755
+ output_attentions=output_attentions,
756
+ use_cache=use_cache,
757
+ )
758
+
759
+ bsz, q_len, _ = hidden_states.size()
760
+
761
+ qkv = self.qkv_proj(hidden_states)
762
+ query_pos = self.num_heads * self.head_dim
763
+ query_states = qkv[..., :query_pos]
764
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
765
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
766
+
767
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
768
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
769
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
770
+
771
+ kv_seq_len = key_states.shape[-2]
772
+ if past_key_value is not None:
773
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
774
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
775
+
776
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
777
+
778
+ if past_key_value is not None:
779
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
780
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
781
+
782
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
783
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
784
+
785
+ if attention_mask is not None:
786
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
787
+ raise ValueError(
788
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
789
+ )
790
+
791
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
792
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
793
+ if query_states.device.type == "cuda" and attention_mask is not None:
794
+ query_states = query_states.contiguous()
795
+ key_states = key_states.contiguous()
796
+ value_states = value_states.contiguous()
797
+
798
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
799
+ query_states,
800
+ key_states,
801
+ value_states,
802
+ attn_mask=attention_mask,
803
+ dropout_p=self.attention_dropout if self.training else 0.0,
804
+ # 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.
805
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
806
+ )
807
+
808
+ attn_output = attn_output.transpose(1, 2).contiguous()
809
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
810
+
811
+ attn_output = self.o_proj(attn_output)
812
+
813
+ return attn_output, None, past_key_value
814
+
815
+
816
+ PHI3_ATTENTION_CLASSES = {
817
+ "eager": Phi3Attention,
818
+ "flash_attention_2": Phi3FlashAttention2,
819
+ "sdpa": Phi3SdpaAttention,
820
+ }
821
+
822
+
823
+ class Phi3DecoderLayer(nn.Module):
824
+ def __init__(self, config: Phi3VConfig, layer_idx: int):
825
+ super().__init__()
826
+
827
+ self.config = config
828
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
829
+
830
+ self.mlp = Phi3MLP(config)
831
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
832
+
833
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
834
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
835
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
836
+
837
+ def forward(
838
+ self,
839
+ hidden_states: torch.Tensor,
840
+ attention_mask: Optional[torch.Tensor] = None,
841
+ position_ids: Optional[torch.LongTensor] = None,
842
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
843
+ output_attentions: Optional[bool] = False,
844
+ use_cache: Optional[bool] = False,
845
+ **kwargs,
846
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
847
+ if "padding_mask" in kwargs:
848
+ warnings.warn(
849
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
850
+ )
851
+ """
852
+ Args:
853
+ hidden_states (`torch.FloatTensor`):
854
+ input to the layer of shape `(batch, seq_len, embed_dim)`
855
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
856
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
857
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
858
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
859
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
860
+ output_attentions (`bool`, *optional*):
861
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
862
+ returned tensors for more detail.
863
+ use_cache (`bool`, *optional*):
864
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
865
+ (see `past_key_values`).
866
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
867
+ """
868
+
869
+ residual = hidden_states
870
+
871
+ hidden_states = self.input_layernorm(hidden_states)
872
+
873
+ # Self Attention
874
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
875
+ hidden_states=hidden_states,
876
+ attention_mask=attention_mask,
877
+ position_ids=position_ids,
878
+ past_key_value=past_key_value,
879
+ output_attentions=output_attentions,
880
+ use_cache=use_cache,
881
+ )
882
+
883
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
884
+
885
+ residual = hidden_states
886
+ hidden_states = self.post_attention_layernorm(hidden_states)
887
+ hidden_states = self.mlp(hidden_states)
888
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
889
+
890
+ outputs = (hidden_states,)
891
+
892
+ if output_attentions:
893
+ outputs += (self_attn_weights,)
894
+
895
+ if use_cache:
896
+ outputs += (present_key_value,)
897
+
898
+ return outputs
899
+
900
+
901
+ PHI3V_START_DOCSTRING = r"""
902
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
903
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
904
+ etc.)
905
+
906
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
907
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
908
+ and behavior.
909
+
910
+ Parameters:
911
+ config ([`Phi3VConfig`]):
912
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
913
+ load the weights associated with the model, only the configuration. Check out the
914
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
915
+ """
916
+
917
+
918
+ @add_start_docstrings(
919
+ "The bare Phi-3-V model outputting raw hidden-states without any specific head on top.",
920
+ PHI3V_START_DOCSTRING,
921
+ )
922
+ class Phi3VPreTrainedModel(PreTrainedModel):
923
+ config_class = Phi3VConfig
924
+ base_model_prefix = "model"
925
+ supports_gradient_checkpointing = True
926
+ _no_split_modules = ["Phi3DecoderLayer"]
927
+ _skip_keys_device_placement = "past_key_values"
928
+ _supports_flash_attn_2 = True
929
+ _supports_sdpa = False
930
+ _supports_cache_class = True
931
+
932
+ _version = "0.0.5"
933
+
934
+ def _init_weights(self, module):
935
+ std = self.config.initializer_range
936
+ if isinstance(module, nn.Linear):
937
+ module.weight.data.normal_(mean=0.0, std=std)
938
+ if module.bias is not None:
939
+ module.bias.data.zero_()
940
+ elif isinstance(module, nn.Embedding):
941
+ module.weight.data.normal_(mean=0.0, std=std)
942
+ if module.padding_idx is not None:
943
+ module.weight.data[module.padding_idx].zero_()
944
+
945
+
946
+ PHI3V_INPUTS_DOCSTRING = r"""
947
+ Args:
948
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
949
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
950
+ it.
951
+
952
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
953
+ [`PreTrainedTokenizer.__call__`] for details.
954
+
955
+ [What are input IDs?](../glossary#input-ids)
956
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
957
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
958
+
959
+ - 1 for tokens that are **not masked**,
960
+ - 0 for tokens that are **masked**.
961
+
962
+ [What are attention masks?](../glossary#attention-mask)
963
+
964
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
965
+ [`PreTrainedTokenizer.__call__`] for details.
966
+
967
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
968
+ `past_key_values`).
969
+
970
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
971
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
972
+ information on the default strategy.
973
+
974
+ - 1 indicates the head is **not masked**,
975
+ - 0 indicates the head is **masked**.
976
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
977
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
978
+ config.n_positions - 1]`.
979
+
980
+ [What are position IDs?](../glossary#position-ids)
981
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
982
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
983
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
984
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
985
+
986
+ Two formats are allowed:
987
+ - a [`~cache_utils.Cache`] instance;
988
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
989
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
990
+ cache format.
991
+
992
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
993
+ legacy cache format will be returned.
994
+
995
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
996
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
997
+ of shape `(batch_size, sequence_length)`.
998
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
999
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1000
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1001
+ model's internal embedding lookup matrix.
1002
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
1003
+ The tensors corresponding to the input images. Pixel values can be obtained using [`AutoImageProcessor`].
1004
+ See [`Phi3ImageProcessor.__call__`] for details.
1005
+ image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`, *optional*):
1006
+ The sizes of the images in the batch, being (height, width) for each image.
1007
+ use_cache (`bool`, *optional*):
1008
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1009
+ `past_key_values`).
1010
+ output_attentions (`bool`, *optional*):
1011
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1012
+ tensors for more detail.
1013
+ output_hidden_states (`bool`, *optional*):
1014
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1015
+ more detail.
1016
+ return_dict (`bool`, *optional*):
1017
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1018
+ """
1019
+
1020
+
1021
+ @add_start_docstrings(
1022
+ "The bare Phi-3-V model outputting raw hidden-states without any specific head on top.",
1023
+ PHI3V_START_DOCSTRING,
1024
+ )
1025
+ class Phi3VModel(Phi3VPreTrainedModel):
1026
+ """
1027
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
1028
+
1029
+ Args:
1030
+ config: Phi3Config
1031
+ """
1032
+
1033
+ def __init__(self, config: Phi3VConfig):
1034
+ super().__init__(config)
1035
+ self.padding_idx = config.pad_token_id
1036
+ self.vocab_size = config.vocab_size
1037
+
1038
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1039
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1040
+
1041
+ self.vision_embed_tokens = None
1042
+ if isinstance(config.embd_layer, dict):
1043
+ # vision embedding layer
1044
+ embedding_config = {
1045
+ 'embedding_cls': config.embd_layer['embedding_cls'],
1046
+ **config.embd_layer
1047
+ }
1048
+ self.vision_embed_tokens = Phi3ImageEmbedding(config, wte=self.embed_tokens, **embedding_config)
1049
+ # # set wte the same for vision embedding
1050
+ # self.vision_embed_tokens.wte.weight = self.embed_tokens.weight
1051
+
1052
+ self.layers = nn.ModuleList(
1053
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1054
+ )
1055
+ self._attn_implementation = config._attn_implementation
1056
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1057
+
1058
+ self.gradient_checkpointing = False
1059
+ # Initialize weights and apply final processing
1060
+ self.post_init()
1061
+
1062
+ def get_input_embeddings(self):
1063
+ return self.embed_tokens
1064
+
1065
+ def set_input_embeddings(self, value):
1066
+ self.embed_tokens = value
1067
+
1068
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1069
+ def forward(
1070
+ self,
1071
+ input_ids: torch.LongTensor = None,
1072
+ attention_mask: Optional[torch.Tensor] = None,
1073
+ position_ids: Optional[torch.LongTensor] = None,
1074
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1075
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1076
+ pixel_values: Optional[torch.FloatTensor] = None,
1077
+ image_sizes: Optional[torch.LongTensor] = None,
1078
+ use_cache: Optional[bool] = None,
1079
+ output_attentions: Optional[bool] = None,
1080
+ output_hidden_states: Optional[bool] = None,
1081
+ return_dict: Optional[bool] = None,
1082
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1083
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1084
+ output_hidden_states = (
1085
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1086
+ )
1087
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1088
+
1089
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1090
+
1091
+ # retrieve input_ids and inputs_embeds
1092
+ if input_ids is not None and inputs_embeds is not None:
1093
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1094
+ elif input_ids is not None:
1095
+ batch_size, seq_length = input_ids.shape[:2]
1096
+ elif inputs_embeds is not None:
1097
+ batch_size, seq_length = inputs_embeds.shape[:2]
1098
+ else:
1099
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1100
+
1101
+ past_key_values_length = 0
1102
+
1103
+ if self.gradient_checkpointing and self.training:
1104
+ if use_cache:
1105
+ logger.warning_once(
1106
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1107
+ )
1108
+ use_cache = False
1109
+
1110
+ if use_cache:
1111
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1112
+ if use_legacy_cache:
1113
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1114
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1115
+
1116
+ if position_ids is None:
1117
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1118
+ position_ids = torch.arange(
1119
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1120
+ )
1121
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1122
+ else:
1123
+ position_ids = position_ids.view(-1, seq_length).long()
1124
+
1125
+ if inputs_embeds is None:
1126
+ if pixel_values is not None and image_sizes is not None:
1127
+ assert self.vision_embed_tokens is not None, "Vision embedding layer is not defined"
1128
+ inputs_embeds = self.vision_embed_tokens(input_ids, pixel_values=pixel_values, image_sizes=image_sizes)
1129
+ else:
1130
+ inputs_embeds = self.embed_tokens(input_ids)
1131
+
1132
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1133
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1134
+ if is_padding_right:
1135
+ raise ValueError(
1136
+ "You are attempting to perform batched generation with padding_side='right'"
1137
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1138
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1139
+ )
1140
+
1141
+ if self._attn_implementation == "flash_attention_2":
1142
+ # 2d mask is passed through the layers
1143
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1144
+ else:
1145
+ # 4d mask is passed through the layers
1146
+ attention_mask = _prepare_4d_causal_attention_mask(
1147
+ attention_mask,
1148
+ (batch_size, seq_length),
1149
+ inputs_embeds,
1150
+ past_key_values_length,
1151
+ sliding_window=self.config.sliding_window,
1152
+ )
1153
+
1154
+ hidden_states = inputs_embeds
1155
+
1156
+ # decoder layers
1157
+ all_hidden_states = () if output_hidden_states else None
1158
+ all_self_attns = () if output_attentions else None
1159
+ next_decoder_cache = None
1160
+
1161
+ for decoder_layer in self.layers:
1162
+ if output_hidden_states:
1163
+ all_hidden_states += (hidden_states,)
1164
+
1165
+ if self.gradient_checkpointing and self.training:
1166
+ layer_outputs = self._gradient_checkpointing_func(
1167
+ decoder_layer.__call__,
1168
+ hidden_states,
1169
+ attention_mask,
1170
+ position_ids,
1171
+ past_key_values,
1172
+ output_attentions,
1173
+ use_cache,
1174
+ )
1175
+ else:
1176
+ layer_outputs = decoder_layer(
1177
+ hidden_states,
1178
+ attention_mask=attention_mask,
1179
+ position_ids=position_ids,
1180
+ past_key_value=past_key_values,
1181
+ output_attentions=output_attentions,
1182
+ use_cache=use_cache,
1183
+ )
1184
+
1185
+ hidden_states = layer_outputs[0]
1186
+
1187
+ if use_cache:
1188
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1189
+
1190
+ if output_attentions:
1191
+ all_self_attns += (layer_outputs[1],)
1192
+
1193
+ hidden_states = self.norm(hidden_states)
1194
+
1195
+ # add hidden states from the last decoder layer
1196
+ if output_hidden_states:
1197
+ all_hidden_states += (hidden_states,)
1198
+
1199
+ next_cache = None
1200
+ if use_cache:
1201
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1202
+ if not return_dict:
1203
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1204
+ return BaseModelOutputWithPast(
1205
+ last_hidden_state=hidden_states,
1206
+ past_key_values=next_cache,
1207
+ hidden_states=all_hidden_states,
1208
+ attentions=all_self_attns,
1209
+ )
1210
+
1211
+
1212
+ class Phi3VForCausalLM(Phi3VPreTrainedModel):
1213
+ _tied_weights_keys = ["lm_head.weight"]
1214
+
1215
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1216
+ def __init__(self, config):
1217
+ super().__init__(config)
1218
+ self.model = Phi3VModel(config)
1219
+ self.vocab_size = config.vocab_size
1220
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1221
+
1222
+ # Initialize weights and apply final processing
1223
+ self.post_init()
1224
+
1225
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1226
+ def get_input_embeddings(self):
1227
+ return self.model.embed_tokens
1228
+
1229
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1230
+ def set_input_embeddings(self, value):
1231
+ self.model.embed_tokens = value
1232
+
1233
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1234
+ def get_output_embeddings(self):
1235
+ return self.lm_head
1236
+
1237
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1238
+ def set_output_embeddings(self, new_embeddings):
1239
+ self.lm_head = new_embeddings
1240
+
1241
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1242
+ def set_decoder(self, decoder):
1243
+ self.model = decoder
1244
+
1245
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1246
+ def get_decoder(self):
1247
+ return self.model
1248
+
1249
+ # Ignore copy
1250
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1251
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1252
+ def forward(
1253
+ self,
1254
+ input_ids: torch.LongTensor = None,
1255
+ attention_mask: Optional[torch.Tensor] = None,
1256
+ position_ids: Optional[torch.LongTensor] = None,
1257
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1258
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1259
+ pixel_values: Optional[torch.FloatTensor] = None,
1260
+ image_sizes: Optional[torch.LongTensor] = None,
1261
+ labels: Optional[torch.LongTensor] = None,
1262
+ use_cache: Optional[bool] = None,
1263
+ output_attentions: Optional[bool] = None,
1264
+ output_hidden_states: Optional[bool] = None,
1265
+ return_dict: Optional[bool] = None,
1266
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1267
+ r"""
1268
+ Args:
1269
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1270
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1271
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1272
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1273
+
1274
+ Returns:
1275
+
1276
+ Example:
1277
+
1278
+ ```python
1279
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1280
+
1281
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1282
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1283
+
1284
+ >>> prompt = "This is an example script ."
1285
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1286
+
1287
+ >>> # Generate
1288
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1289
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1290
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1291
+ ```"""
1292
+
1293
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1294
+ output_hidden_states = (
1295
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1296
+ )
1297
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1298
+
1299
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1300
+ outputs = self.model(
1301
+ input_ids=input_ids,
1302
+ attention_mask=attention_mask,
1303
+ position_ids=position_ids,
1304
+ past_key_values=past_key_values,
1305
+ inputs_embeds=inputs_embeds,
1306
+ pixel_values=pixel_values,
1307
+ image_sizes=image_sizes,
1308
+ use_cache=use_cache,
1309
+ output_attentions=output_attentions,
1310
+ output_hidden_states=output_hidden_states,
1311
+ return_dict=return_dict,
1312
+ )
1313
+
1314
+ hidden_states = outputs[0]
1315
+ logits = self.lm_head(hidden_states)
1316
+ logits = logits.float()
1317
+
1318
+ loss = None
1319
+ if labels is not None:
1320
+ # Shift so that tokens < n predict n
1321
+ shift_logits = logits[..., :-1, :].contiguous()
1322
+ shift_labels = labels[..., 1:].contiguous()
1323
+ # Flatten the tokens
1324
+ loss_fct = CrossEntropyLoss()
1325
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1326
+ shift_labels = shift_labels.view(-1)
1327
+ # Enable model parallelism
1328
+ shift_labels = shift_labels.to(shift_logits.device)
1329
+ loss = loss_fct(shift_logits, shift_labels)
1330
+
1331
+ if not return_dict:
1332
+ output = (logits,) + outputs[1:]
1333
+ return (loss,) + output if loss is not None else output
1334
+
1335
+ return CausalLMOutputWithPast(
1336
+ loss=loss,
1337
+ logits=logits,
1338
+ past_key_values=outputs.past_key_values,
1339
+ hidden_states=outputs.hidden_states,
1340
+ attentions=outputs.attentions,
1341
+ )
1342
+
1343
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1344
+ def prepare_inputs_for_generation(
1345
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, pixel_values=None, image_sizes=None, **kwargs
1346
+ ):
1347
+ if past_key_values is not None:
1348
+ if isinstance(past_key_values, Cache):
1349
+ cache_length = past_key_values.get_seq_length()
1350
+ past_length = past_key_values.seen_tokens
1351
+ max_cache_length = past_key_values.get_max_length()
1352
+ else:
1353
+ cache_length = past_length = past_key_values[0][0].shape[2]
1354
+ max_cache_length = None
1355
+
1356
+ # Keep only the unprocessed tokens:
1357
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1358
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1359
+ # input)
1360
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1361
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1362
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1363
+ # input_ids based on the past_length.
1364
+ elif past_length < input_ids.shape[1]:
1365
+ input_ids = input_ids[:, past_length:]
1366
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1367
+
1368
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1369
+ if (
1370
+ max_cache_length is not None
1371
+ and attention_mask is not None
1372
+ and cache_length + input_ids.shape[1] > max_cache_length
1373
+ ):
1374
+ attention_mask = attention_mask[:, -max_cache_length:]
1375
+
1376
+ position_ids = kwargs.get("position_ids", None)
1377
+ if attention_mask is not None and position_ids is None:
1378
+ # create position_ids on the fly for batch generation
1379
+ position_ids = attention_mask.long().cumsum(-1) - 1
1380
+ position_ids.masked_fill_(attention_mask == 0, 1)
1381
+ if past_key_values:
1382
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1383
+
1384
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1385
+ if inputs_embeds is not None and past_key_values is None:
1386
+ model_inputs = {"inputs_embeds": inputs_embeds}
1387
+ else:
1388
+ model_inputs = {"input_ids": input_ids}
1389
+
1390
+ model_inputs.update(
1391
+ {
1392
+ "position_ids": position_ids,
1393
+ "past_key_values": past_key_values,
1394
+ "use_cache": kwargs.get("use_cache"),
1395
+ "attention_mask": attention_mask,
1396
+ "pixel_values": pixel_values,
1397
+ "image_sizes": image_sizes,
1398
+ }
1399
+ )
1400
+ return model_inputs
1401
+
1402
+ @staticmethod
1403
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1404
+ def _reorder_cache(past_key_values, beam_idx):
1405
+ reordered_past = ()
1406
+ for layer_past in past_key_values:
1407
+ reordered_past += (
1408
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1409
+ )
1410
+ return reordered_past
1411
+
1412
+
1413
+ @add_start_docstrings(
1414
+ """
1415
+ The [`Phi3VModel`] with a sequence classification head on top (linear layer).
1416
+
1417
+ [`Phi3VForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1418
+ (e.g. GPT-2) do.
1419
+
1420
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1421
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1422
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1423
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1424
+ each row of the batch).
1425
+ """,
1426
+ PHI3V_START_DOCSTRING,
1427
+ )
1428
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1429
+ class Phi3VForSequenceClassification(Phi3VPreTrainedModel):
1430
+ def __init__(self, config):
1431
+ super().__init__(config)
1432
+ self.num_labels = config.num_labels
1433
+ self.model = Phi3VModel(config)
1434
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1435
+
1436
+ # Initialize weights and apply final processing
1437
+ self.post_init()
1438
+
1439
+ def get_input_embeddings(self):
1440
+ return self.model.embed_tokens
1441
+
1442
+ def set_input_embeddings(self, value):
1443
+ self.model.embed_tokens = value
1444
+
1445
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1446
+ def forward(
1447
+ self,
1448
+ input_ids: torch.LongTensor = None,
1449
+ attention_mask: Optional[torch.Tensor] = None,
1450
+ position_ids: Optional[torch.LongTensor] = None,
1451
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1452
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1453
+ pixel_values: Optional[torch.FloatTensor] = None,
1454
+ image_sizes: Optional[torch.LongTensor] = None,
1455
+ labels: Optional[torch.LongTensor] = None,
1456
+ use_cache: Optional[bool] = None,
1457
+ output_attentions: Optional[bool] = None,
1458
+ output_hidden_states: Optional[bool] = None,
1459
+ return_dict: Optional[bool] = None,
1460
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1461
+ r"""
1462
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1463
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1464
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1465
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1466
+ """
1467
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1468
+
1469
+ model_outputs = self.model(
1470
+ input_ids,
1471
+ attention_mask=attention_mask,
1472
+ position_ids=position_ids,
1473
+ past_key_values=past_key_values,
1474
+ inputs_embeds=inputs_embeds,
1475
+ pixel_values=pixel_values,
1476
+ image_sizes=image_sizes,
1477
+ use_cache=use_cache,
1478
+ output_attentions=output_attentions,
1479
+ output_hidden_states=output_hidden_states,
1480
+ return_dict=return_dict,
1481
+ )
1482
+ hidden_states = model_outputs[0]
1483
+ logits = self.score(hidden_states)
1484
+
1485
+ if input_ids is not None:
1486
+ batch_size = input_ids.shape[0]
1487
+ else:
1488
+ batch_size = inputs_embeds.shape[0]
1489
+
1490
+ if self.config.pad_token_id is None and batch_size != 1:
1491
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1492
+ if self.config.pad_token_id is None:
1493
+ sequence_lengths = -1
1494
+ else:
1495
+ if input_ids is not None:
1496
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1497
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1498
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1499
+ sequence_lengths = sequence_lengths.to(logits.device)
1500
+ else:
1501
+ sequence_lengths = -1
1502
+
1503
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1504
+
1505
+ loss = None
1506
+ if labels is not None:
1507
+ labels = labels.to(logits.device)
1508
+ if self.config.problem_type is None:
1509
+ if self.num_labels == 1:
1510
+ self.config.problem_type = "regression"
1511
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1512
+ self.config.problem_type = "single_label_classification"
1513
+ else:
1514
+ self.config.problem_type = "multi_label_classification"
1515
+
1516
+ if self.config.problem_type == "regression":
1517
+ loss_fct = MSELoss()
1518
+ if self.num_labels == 1:
1519
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1520
+ else:
1521
+ loss = loss_fct(pooled_logits, labels)
1522
+ elif self.config.problem_type == "single_label_classification":
1523
+ loss_fct = CrossEntropyLoss()
1524
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1525
+ elif self.config.problem_type == "multi_label_classification":
1526
+ loss_fct = BCEWithLogitsLoss()
1527
+ loss = loss_fct(pooled_logits, labels)
1528
+ if not return_dict:
1529
+ output = (pooled_logits,) + model_outputs[1:]
1530
+ return ((loss,) + output) if loss is not None else output
1531
+
1532
+ return SequenceClassifierOutputWithPast(
1533
+ loss=loss,
1534
+ logits=pooled_logits,
1535
+ past_key_values=model_outputs.past_key_values,
1536
+ hidden_states=model_outputs.hidden_states,
1537
+ attentions=model_outputs.attentions,
1538
+ )
1539
+
1540
+
1541
+ @add_start_docstrings(
1542
+ """
1543
+ [`Phi3VModel`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1544
+ Named-Entity-Recognition (NER) tasks.
1545
+ """,
1546
+ PHI3V_START_DOCSTRING,
1547
+ )
1548
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1549
+ class Phi3VForTokenClassification(Phi3VPreTrainedModel):
1550
+ def __init__(self, config: Phi3VConfig):
1551
+ super().__init__(config)
1552
+ self.num_labels = config.num_labels
1553
+
1554
+ self.model = Phi3VModel(config)
1555
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1556
+ classifier_dropout = config.classifier_dropout
1557
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1558
+ classifier_dropout = config.hidden_dropout
1559
+ else:
1560
+ classifier_dropout = 0.1
1561
+ self.dropout = nn.Dropout(classifier_dropout)
1562
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1563
+
1564
+ # Initialize weights and apply final processing
1565
+ self.post_init()
1566
+
1567
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1568
+ @add_code_sample_docstrings(
1569
+ checkpoint=_CHECKPOINT_FOR_DOC,
1570
+ output_type=TokenClassifierOutput,
1571
+ config_class=_CONFIG_FOR_DOC,
1572
+ )
1573
+ def forward(
1574
+ self,
1575
+ input_ids: Optional[torch.LongTensor] = None,
1576
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1577
+ attention_mask: Optional[torch.Tensor] = None,
1578
+ inputs_embeds: Optional[torch.Tensor] = None,
1579
+ pixel_values: Optional[torch.FloatTensor] = None,
1580
+ image_sizes: Optional[torch.LongTensor] = None,
1581
+ labels: Optional[torch.Tensor] = None,
1582
+ use_cache: Optional[bool] = None,
1583
+ output_attentions: Optional[bool] = None,
1584
+ output_hidden_states: Optional[bool] = None,
1585
+ return_dict: Optional[bool] = None,
1586
+ **deprecated_arguments,
1587
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1588
+ r"""
1589
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1590
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1591
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1592
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1593
+ """
1594
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1595
+
1596
+ model_outputs = self.model(
1597
+ input_ids,
1598
+ past_key_values=past_key_values,
1599
+ attention_mask=attention_mask,
1600
+ inputs_embeds=inputs_embeds,
1601
+ pixel_values=pixel_values,
1602
+ image_sizes=image_sizes,
1603
+ use_cache=use_cache,
1604
+ output_attentions=output_attentions,
1605
+ output_hidden_states=output_hidden_states,
1606
+ return_dict=return_dict,
1607
+ )
1608
+
1609
+ hidden_states = model_outputs[0]
1610
+ hidden_states = self.dropout(hidden_states)
1611
+ logits = self.classifier(hidden_states)
1612
+
1613
+ loss = None
1614
+ if labels is not None:
1615
+ # move labels to correct device to enable model parallelism
1616
+ labels = labels.to(logits.device)
1617
+ batch_size, seq_length = labels.shape
1618
+ loss_fct = CrossEntropyLoss()
1619
+ loss = loss_fct(
1620
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1621
+ )
1622
+
1623
+ if not return_dict:
1624
+ output = (logits,) + model_outputs[2:]
1625
+ return ((loss,) + output) if loss is not None else output
1626
+
1627
+ return TokenClassifierOutput(
1628
+ loss=loss,
1629
+ logits=logits,
1630
+ hidden_states=model_outputs.hidden_states,
1631
+ attentions=model_outputs.attentions,
1632
+ )
moe_phi3_v.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tqdm.notebook import tqdm
2
+ import torch
3
+ import torch.nn as nn
4
+ import copy
5
+
6
+ from .modeling_phi3_v import Phi3VForCausalLM, Phi3MLP
7
+ from .configuration_phi3_v import Phi3VConfig
8
+
9
+ from torch.optim import Adam
10
+ from typing import Optional, Tuple
11
+
12
+ from transformers import (
13
+ PreTrainedModel,
14
+ AutoConfig,
15
+ )
16
+
17
+
18
+ # Define the Gating Layer
19
+ class GatingLayer(nn.Module):
20
+ def __init__(self, input_dim, num_experts, k, layer_dtype=torch.float16):
21
+ super(GatingLayer, self).__init__()
22
+ self.num_experts = num_experts
23
+ self.k = k
24
+ self.gate = nn.Linear(input_dim, num_experts).to(dtype=layer_dtype)
25
+
26
+ def forward(self, x):
27
+ gate_scores = torch.softmax(self.gate(x), dim=-1)
28
+ topk_values, topk_indices = torch.topk(gate_scores, self.k, dim=-1)
29
+ return topk_values, topk_indices
30
+
31
+
32
+ class MoE(nn.Module):
33
+ def __init__(self, input_dim, experts, gating_layer, config):
34
+ super(MoE, self).__init__()
35
+ self.experts = nn.ModuleList(experts)
36
+ self.gating_layer = gating_layer
37
+ self.output_dim = config.hidden_size
38
+
39
+ def forward(self, x):
40
+ with torch.autocast(device_type="cuda", dtype=torch.float16):
41
+ gate_values, gate_indices = self.gating_layer(x)
42
+ batch_size, seq_length, _ = x.size()
43
+
44
+ moe_output = torch.zeros(
45
+ batch_size,
46
+ seq_length,
47
+ self.output_dim,
48
+ dtype=self.gating_layer.gate.weight.dtype,
49
+ device=x.device,
50
+ )
51
+
52
+ for i in range(self.gating_layer.k):
53
+ expert_outputs = []
54
+ for b in range(batch_size):
55
+ for s in range(seq_length):
56
+ expert_index = gate_indices[b, s, i]
57
+ expert = self.experts[expert_index]
58
+ up_states = expert.gate_up_proj(x[b, s].unsqueeze(0))
59
+ gate, up_states = up_states.chunk(2, dim=-1)
60
+ up_states = up_states * expert.activation_fn(gate)
61
+ expert_output = expert.down_proj(up_states)
62
+ expert_outputs.append(expert_output)
63
+
64
+ expert_outputs = torch.stack(expert_outputs, dim=0).view(
65
+ batch_size, seq_length, -1
66
+ )
67
+ gate_values_i = (
68
+ gate_values[:, :, i].unsqueeze(-1).expand_as(expert_outputs)
69
+ )
70
+ moe_output += gate_values_i * expert_outputs
71
+
72
+ return moe_output
73
+
74
+ # Define the ModifiedPhi3DecoderLayer Layer
75
+ class ModifiedPhi3DecoderLayer(nn.Module):
76
+ def __init__(self, original_layer, moe_layer):
77
+ super(ModifiedPhi3DecoderLayer, self).__init__()
78
+ self.self_attn = original_layer.self_attn
79
+ self.mlp = moe_layer
80
+ self.input_layernorm = original_layer.input_layernorm
81
+ self.resid_attn_dropout = original_layer.resid_attn_dropout
82
+ self.resid_mlp_dropout = original_layer.resid_mlp_dropout
83
+ self.post_attention_layernorm = original_layer.post_attention_layernorm
84
+
85
+ def forward(
86
+ self,
87
+ hidden_states: torch.Tensor,
88
+ attention_mask: Optional[torch.Tensor] = None,
89
+ position_ids: Optional[torch.LongTensor] = None,
90
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
91
+ output_attentions: Optional[bool] = False,
92
+ use_cache: Optional[bool] = False,
93
+ ) -> Tuple[
94
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
95
+ ]:
96
+ residual = hidden_states
97
+
98
+ with torch.autocast(device_type="cuda", dtype=hidden_states.dtype):
99
+ hidden_states = self.input_layernorm(hidden_states)
100
+
101
+ # Self Attention
102
+ attn_outputs = self.self_attn(
103
+ hidden_states=hidden_states,
104
+ attention_mask=attention_mask,
105
+ position_ids=position_ids,
106
+ past_key_value=past_key_value,
107
+ output_attentions=output_attentions,
108
+ use_cache=use_cache,
109
+ )
110
+ attn_output = attn_outputs[0]
111
+ hidden_states = residual + self.resid_attn_dropout(attn_output)
112
+
113
+ residual = hidden_states
114
+ hidden_states = self.post_attention_layernorm(hidden_states)
115
+ hidden_states = self.mlp(hidden_states)
116
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
117
+
118
+ outputs = (hidden_states,)
119
+
120
+ if output_attentions:
121
+ outputs += (attn_outputs[1],)
122
+
123
+ if use_cache:
124
+ outputs += (attn_outputs[2],)
125
+
126
+ return outputs
127
+
128
+
129
+ #Define Phi3VForCausalLMMoEConfig
130
+ class Phi3VForCausalLMMoEConfig(Phi3VConfig):
131
+ model_type = "phi3_v_moe"
132
+
133
+ def __init__(self, config=None, k=1, num_expert_models=2, **kwargs):
134
+ if config is not None:
135
+ kwargs.update(config.to_dict())
136
+ super().__init__(**kwargs)
137
+ self.k = k
138
+ self.num_expert_models = num_expert_models
139
+ self.architectures = "Phi3VForCausalLMMoE"
140
+ self.auto_map = {
141
+ "AutoConfig": "moe_phi3_v.Phi3VForCausalLMMoEConfig",
142
+ "AutoModelForCausalLM": "moe_phi3_v.Phi3VForCausalLMMoE",
143
+ }
144
+
145
+ #Define MoE Model
146
+ class Phi3VForCausalLMMoE(Phi3VForCausalLM):
147
+ config_class = Phi3VForCausalLMMoEConfig
148
+
149
+ def __init__(
150
+ self,
151
+ config,
152
+ base_model=None,
153
+ expert_models=None,
154
+ layer_dtype=torch.bfloat16,
155
+ **kwargs,
156
+ ):
157
+ super().__init__(config)
158
+
159
+ self.layer_dtype = layer_dtype
160
+ self.custom_device = torch.device(
161
+ "cuda" if torch.cuda.is_available() else "cpu"
162
+ )
163
+ k = self.config.k
164
+ self.num_layers = len(base_model.model.layers) if base_model else 0
165
+
166
+ self.config.auto_map = {
167
+ "AutoConfig": "moe_phi3_v.Phi3VForCausalLMMoEConfig",
168
+ "AutoModelForCausalLM": "moe_phi3_v.Phi3VForCausalLMMoE",
169
+ }
170
+
171
+ self.model = base_model or Phi3VForCausalLM(
172
+ self.config
173
+ )
174
+
175
+ if base_model and expert_models:
176
+ self.num_expert_models = len(expert_models)
177
+ self._init_moe_layers(base_model, expert_models, k, layer_dtype)
178
+ else:
179
+ print(
180
+ "Init function called and generating dummy experts: k=",
181
+ k,
182
+ "experts=",
183
+ self.config.num_expert_models,
184
+ )
185
+ num_dummy_experts = self.config.num_expert_models
186
+ self._init_moe_layers_with_dummy_experts(
187
+ self.model, k, num_dummy_experts, layer_dtype
188
+ )
189
+
190
+ self.config.model_type = "phi3_v_moe"
191
+
192
+ def _init_base_model(self):
193
+ return PreTrainedModel(self.config)
194
+
195
+ def _init_moe_layers(self, base_model, expert_models, k, layer_dtype):
196
+ self.num_layers = len(base_model.model.layers)
197
+ for i in tqdm(range(self.num_layers)):
198
+ experts = []
199
+ for expert_model in expert_models:
200
+ expert = copy.deepcopy(expert_model.model.layers[i].mlp).to(
201
+ dtype=layer_dtype
202
+ )
203
+ experts.append(expert)
204
+
205
+ gating_layer = GatingLayer(
206
+ input_dim=self.config.hidden_size,
207
+ num_experts=len(experts),
208
+ k=k,
209
+ layer_dtype=layer_dtype,
210
+ )
211
+ moe_layer = MoE(
212
+ input_dim=self.config.hidden_size,
213
+ experts=experts,
214
+ gating_layer=gating_layer,
215
+ config=self.config,
216
+ ).to(dtype=layer_dtype)
217
+
218
+ self.model.model.layers[i] = ModifiedPhi3DecoderLayer(
219
+ self.model.model.layers[i], moe_layer
220
+ ).to(dtype=layer_dtype)
221
+
222
+ def _init_moe_layers_with_dummy_experts(
223
+ self, base_model, k, num_dummy_experts, layer_dtype
224
+ ):
225
+ self.num_layers = len(base_model.model.layers)
226
+
227
+ for i in tqdm(range(self.num_layers)):
228
+ experts = []
229
+ for _ in range(num_dummy_experts):
230
+ dummy_expert = Phi3MLP(self.config).to(dtype=layer_dtype)
231
+ experts.append(dummy_expert)
232
+
233
+ gating_layer = GatingLayer(
234
+ input_dim=self.config.hidden_size,
235
+ num_experts=len(experts),
236
+ k=k,
237
+ layer_dtype=layer_dtype,
238
+ )
239
+ moe_layer = MoE(
240
+ input_dim=self.config.hidden_size,
241
+ experts=experts,
242
+ gating_layer=gating_layer,
243
+ config=self.config,
244
+ ).to(dtype=layer_dtype)
245
+
246
+ self.model.model.layers[i] = ModifiedPhi3DecoderLayer(
247
+ self.model.model.layers[i], moe_layer
248
+ ).to(dtype=layer_dtype)
249
+
250
+ def forward(self, *args, **kwargs):
251
+ return self.model.forward(*args, **kwargs)
252
+
253
+ def generate(self, *args, **kwargs):
254
+ return self.model.generate(*args, **kwargs)
255
+
256
+ @classmethod
257
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
258
+ # Initialize the model using the superclass method
259
+ model = super(Phi3VForCausalLMMoE, cls).from_pretrained(
260
+ pretrained_model_name_or_path, *model_args, **kwargs
261
+ )
262
+
263
+ return model
264
+
265
+ def preselect_gating_layer_params(self, processor, prompts_per_expert, epochs = 1000):
266
+ self.to(self.custom_device)
267
+ self.eval()
268
+
269
+ all_gating_layer_params = []
270
+
271
+ for layer_idx in tqdm(range(self.num_layers)):
272
+ print(f"Training gating layer parameters for layer {layer_idx}")
273
+
274
+ expert_embeddings = []
275
+ for prompts in prompts_per_expert:
276
+ embeddings = []
277
+ for prompt in prompts:
278
+ inputs = processor(
279
+ text=prompt["text"], images=prompt["image"], return_tensors="pt"
280
+ ).to(self.custom_device)
281
+ with torch.no_grad():
282
+ if (
283
+ inputs.pixel_values is not None
284
+ and inputs.image_sizes is not None
285
+ ):
286
+ outputs = self.model.model.vision_embed_tokens(
287
+ inputs.input_ids,
288
+ pixel_values=inputs.pixel_values,
289
+ image_sizes=inputs.image_sizes,
290
+ ).mean(dim=1)
291
+ else:
292
+ outputs = self.model.model.embed_tokens(
293
+ inputs.input_ids
294
+ ).mean(dim=1)
295
+ embeddings.append(outputs)
296
+ expert_embeddings.append(torch.stack(embeddings).mean(dim=0))
297
+ expert_embeddings = torch.stack(expert_embeddings).to(self.layer_dtype)
298
+
299
+ class SimpleGatingLayer(nn.Module):
300
+ def __init__(self, input_dim, num_experts, layer_dtype=torch.float16):
301
+ super(SimpleGatingLayer, self).__init__()
302
+ self.gate = nn.Linear(input_dim, num_experts).to(dtype=layer_dtype)
303
+
304
+ def forward(self, x):
305
+ return self.gate(x)
306
+
307
+ input_dim = expert_embeddings.shape[2]
308
+ num_experts = len(prompts_per_expert)
309
+ gating_layer = SimpleGatingLayer(
310
+ input_dim, num_experts, layer_dtype=self.layer_dtype
311
+ ).to(self.custom_device)
312
+
313
+ criterion = nn.CrossEntropyLoss()
314
+ optimizer = Adam(gating_layer.parameters(), lr=1e-3)
315
+
316
+ for epoch in tqdm(range(epochs), desc=f"Training Gating Layer {layer_idx}"):
317
+ optimizer.zero_grad()
318
+ expert_embeddings_reshaped = expert_embeddings.view(
319
+ num_experts, input_dim
320
+ )
321
+ outputs = gating_layer(expert_embeddings_reshaped)
322
+ labels = torch.arange(num_experts).to(self.custom_device)
323
+ loss = criterion(outputs, labels)
324
+ loss.backward()
325
+ optimizer.step()
326
+
327
+ all_gating_layer_params.append(gating_layer.state_dict())
328
+
329
+ return all_gating_layer_params
330
+
331
+ def set_gating_layer_params(self, gating_layer_params):
332
+ for layer_idx, params in enumerate(gating_layer_params):
333
+ self.model.model.layers[layer_idx].mlp.gating_layer.load_state_dict(params)
334
+
335
+
336
+ def freeze_except_gating_layers(model):
337
+ # freeze_except_gating_layers(moe_model)
338
+
339
+ # Freeze all parameters
340
+ for param in model.parameters():
341
+ param.requires_grad = False
342
+
343
+ # Unfreeze gating layer parameters
344
+ for layer in model.model.model.layers:
345
+ for name, param in layer.mlp.gating_layer.named_parameters():
346
+ param.requires_grad = True
347
+
348
+
349
+ def un_freeze_all(model):
350
+ # freeze_except_gating_layers(moe_model)
351
+
352
+ # Freeze all parameters
353
+ for param in model.parameters():
354
+ param.requires_grad = True
355
+
356
+
357
+ from transformers import AutoConfig
358
+
359
+ AutoConfig.register("phi3_v_moe", Phi3VForCausalLMMoEConfig)
360
+
361
+ from transformers.models.auto.modeling_auto import MODEL_MAPPING
362
+
363
+ MODEL_MAPPING.update({"phi3_v_moe": Phi3VForCausalLMMoE})
processing_phi3_v.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ prompt_chunks = [self.tokenizer(chunk).input_ids for chunk in re.split(pattern, texts)]
154
+
155
+ if 'num_img_tokens' in images:
156
+ num_img_tokens = images['num_img_tokens']
157
+ else:
158
+ assert 'num_crops' in images, 'num_crops must be provided in images if num_img_tokens is not provided'
159
+ num_crops = images['num_crops']
160
+ num_img_tokens = [_num_crops * self.num_img_tokens for _num_crops in num_crops]
161
+
162
+ images, image_sizes = images['pixel_values'], images['image_sizes']
163
+
164
+ # image_tags needs to start from 1 to n
165
+ image_tags = re.findall(pattern, texts)
166
+ # image_ids = [int(s.split("|")[1].split("_")[-1]) * -1 for s in image_tags]
167
+ # image_ids_pad = [[iid]*num_img_tokens[i] for i, iid in enumerate(image_ids)]
168
+ image_ids = [int(s.split("|")[1].split("_")[-1]) for s in image_tags]
169
+ unique_image_ids = sorted(list(set(image_ids)))
170
+ # image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be [1, 4, 5]
171
+ # check the condition
172
+ 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}"
173
+ # total images must be the same as the number of image tags
174
+ 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"
175
+
176
+ image_ids_pad = [[-iid]*num_img_tokens[iid-1] for iid in image_ids]
177
+
178
+ def insert_separator(X, sep_list):
179
+ if len(X) > len(sep_list):
180
+ sep_list.append([])
181
+ return [ele for sublist in zip(X, sep_list) for ele in sublist]
182
+ input_ids = []
183
+ offset = 0
184
+ for x in insert_separator(prompt_chunks, image_ids_pad):
185
+ input_ids.extend(x[offset:])
186
+
187
+ input_ids = torch.tensor(input_ids, dtype=torch.long).unsqueeze(0)
188
+ attention_mask = (input_ids > -1000000).to(torch.long)
189
+
190
+ return BatchFeature(data={"input_ids": input_ids,
191
+ "attention_mask": attention_mask,
192
+ "pixel_values": images,
193
+ "image_sizes": image_sizes})
194
+
195
+
196
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
197
+ def batch_decode(self, *args, **kwargs):
198
+ """
199
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
200
+ refer to the docstring of this method for more information.
201
+ """
202
+ return self.tokenizer.batch_decode(*args, **kwargs)
203
+
204
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
205
+ def decode(self, *args, **kwargs):
206
+ """
207
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
208
+ the docstring of this method for more information.
209
+ """
210
+ return self.tokenizer.decode(*args, **kwargs)
211
+
212
+ @property
213
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
214
+ def model_input_names(self):
215
+ tokenizer_input_names = self.tokenizer.model_input_names
216
+ image_processor_input_names = self.image_processor.model_input_names
217
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))