mjbuehler commited on
Commit
d047c49
1 Parent(s): e881400

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/abs/2401.16420)
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 @@