fix_import (#1)
Browse files- fix import (b330978e4027db0529fd11c72c013fba5145c917)
- fix import (6ff8b355df43fecb64be8fb9c1ad700765b38fd3)
Co-authored-by: Haiping Wu <[email protected]>
- image_embedding_phi3_v.py +0 -322
- image_processing_phi3_v.py +0 -274
- modeling_phi3_v.py +304 -2
- processing_phi3_v.py +262 -1
image_embedding_phi3_v.py
DELETED
@@ -1,322 +0,0 @@
|
|
1 |
-
# coding=utf-8
|
2 |
-
# Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
|
3 |
-
#
|
4 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
-
# you may not use this file except in compliance with the License.
|
6 |
-
# You may obtain a copy of the License at
|
7 |
-
#
|
8 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
-
#
|
10 |
-
# Unless required by applicable law or agreed to in writing, software
|
11 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
-
# See the License for the specific language governing permissions and
|
14 |
-
# limitations under the License.
|
15 |
-
|
16 |
-
import torch
|
17 |
-
from torch import nn
|
18 |
-
from transformers import CLIPVisionConfig, CLIPVisionModel, PretrainedConfig
|
19 |
-
from transformers.models.clip.modeling_clip import CLIPAttention
|
20 |
-
from transformers.utils import logging
|
21 |
-
|
22 |
-
try:
|
23 |
-
from flash_attn import flash_attn_func
|
24 |
-
except ImportError:
|
25 |
-
pass
|
26 |
-
|
27 |
-
logger = logging.get_logger(__name__)
|
28 |
-
|
29 |
-
|
30 |
-
MAX_INPUT_ID = int(1e9)
|
31 |
-
|
32 |
-
CLIP_VIT_LARGE_PATCH14_336_CONFIG = CLIPVisionConfig(
|
33 |
-
attention_dropout=0.0,
|
34 |
-
dropout=0.0,
|
35 |
-
hidden_act="quick_gelu",
|
36 |
-
hidden_size=1024,
|
37 |
-
image_size=336,
|
38 |
-
initializer_factor=1.0,
|
39 |
-
initializer_range=0.02,
|
40 |
-
intermediate_size=4096,
|
41 |
-
layer_norm_eps=1e-05,
|
42 |
-
num_attention_heads=16,
|
43 |
-
num_channels=3,
|
44 |
-
num_hidden_layers=24,
|
45 |
-
patch_size=14,
|
46 |
-
projection_dim=768
|
47 |
-
)
|
48 |
-
|
49 |
-
class CLIPAttentionFA2(CLIPAttention):
|
50 |
-
"""Add flash attention 2 to CLIPAttention. (This is only used in the vision encoder)"""
|
51 |
-
|
52 |
-
def forward(self,
|
53 |
-
hidden_states,
|
54 |
-
attention_mask=None,
|
55 |
-
causal_attention_mask=None,
|
56 |
-
output_attentions=False,
|
57 |
-
):
|
58 |
-
"""Input shape: Batch x Time x Channel"""
|
59 |
-
|
60 |
-
assert attention_mask is None, "CLIPAttentionFA2 does not support attention_mask"
|
61 |
-
assert causal_attention_mask is None, "CLIPAttentionFA2 does not support causal_attention_mask"
|
62 |
-
assert output_attentions is False, "CLIPAttentionFA2 does not support output_attentions"
|
63 |
-
|
64 |
-
bsz, tgt_len, embed_dim = hidden_states.size()
|
65 |
-
query_states = self.q_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
|
66 |
-
key_states = self.k_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
|
67 |
-
value_states = self.v_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
|
68 |
-
|
69 |
-
attn_output = flash_attn_func(
|
70 |
-
query_states,
|
71 |
-
key_states,
|
72 |
-
value_states,
|
73 |
-
dropout_p=self.dropout if self.training else 0.0,
|
74 |
-
softmax_scale=self.scale,
|
75 |
-
causal=False,
|
76 |
-
).reshape(bsz, tgt_len, embed_dim)
|
77 |
-
|
78 |
-
attn_output = self.out_proj(attn_output)
|
79 |
-
return attn_output, None
|
80 |
-
|
81 |
-
|
82 |
-
class Phi3ImageEmbedding(nn.Module):
|
83 |
-
"""Phi3 Image embedding."""
|
84 |
-
|
85 |
-
def __init__(self, config: PretrainedConfig, wte=None, **kwargs) -> None:
|
86 |
-
super().__init__()
|
87 |
-
|
88 |
-
# n_embed or hidden_size
|
89 |
-
hidden_size = config.n_embd if hasattr(config, 'n_embd') else config.hidden_size
|
90 |
-
if hasattr(config, 'embd_pdrop') or hasattr(config, 'embed_pdrop'):
|
91 |
-
embd_drop = config.embd_pdrop if hasattr(config, 'embd_pdrop') else config.embed_pdrop
|
92 |
-
self.drop = nn.Dropout(embd_drop)
|
93 |
-
else:
|
94 |
-
self.drop = None
|
95 |
-
|
96 |
-
self.wte = wte
|
97 |
-
|
98 |
-
if isinstance(config.img_processor, dict) and config.img_processor.get('name', None) == 'clip_vision_model':
|
99 |
-
assert 'model_name' in config.img_processor, 'model_name must be provided for CLIPVisionModel'
|
100 |
-
assert 'image_dim_out' in config.img_processor, 'image_dim_out must be provided for CLIPVisionModel'
|
101 |
-
assert 'num_img_tokens' in config.img_processor, 'num_img_tokens must be provided for CLIPVisionModel'
|
102 |
-
assert config.img_processor['model_name'] == 'openai/clip-vit-large-patch14-336'
|
103 |
-
clip_config = CLIP_VIT_LARGE_PATCH14_336_CONFIG
|
104 |
-
self.img_processor = CLIPVisionModel(clip_config)
|
105 |
-
image_dim_out = config.img_processor['image_dim_out']
|
106 |
-
self.num_img_tokens = config.img_processor['num_img_tokens']
|
107 |
-
|
108 |
-
# FA2 in CLIP
|
109 |
-
if config._attn_implementation == 'flash_attention_2':
|
110 |
-
for layer in self.img_processor.vision_model.encoder.layers:
|
111 |
-
clip_fa2 = CLIPAttentionFA2(clip_config)
|
112 |
-
del layer.self_attn
|
113 |
-
layer.self_attn = clip_fa2
|
114 |
-
else:
|
115 |
-
raise NotImplementedError(f'img_processor = {config.img_processor}, not implemented')
|
116 |
-
|
117 |
-
self.image_dim_out = image_dim_out
|
118 |
-
self.img_sizes = None
|
119 |
-
|
120 |
-
# global_gn and sub_gn for hd transform, serves as line separator
|
121 |
-
self.use_hd_transform = kwargs.get('use_hd_transform', False)
|
122 |
-
self.with_learnable_separator = kwargs.get('with_learnable_separator', False)
|
123 |
-
self.hd_transform_order = kwargs.get('hd_transform_order', 'glb_sub')
|
124 |
-
# with_hd_transform and with_learnable_separator should have same value
|
125 |
-
assert self.use_hd_transform == self.with_learnable_separator, 'use_hd_transform and with_learnable_separator should have same value'
|
126 |
-
if self.with_learnable_separator:
|
127 |
-
assert self.use_hd_transform, 'learnable separator is only for hd transform'
|
128 |
-
# 1024 * 4, merge spatial to channel dimension
|
129 |
-
self.glb_GN = nn.Parameter(torch.zeros([1, 1, self.image_dim_out * 4]))
|
130 |
-
self.sub_GN = nn.Parameter(torch.zeros([1, 1, 1, self.image_dim_out * 4]))
|
131 |
-
logger.info(f'learnable separator enabled for hd transform, hd_transform_order = {self.hd_transform_order}')
|
132 |
-
|
133 |
-
projection_cls = kwargs.get('projection_cls', 'linear')
|
134 |
-
if projection_cls == 'linear':
|
135 |
-
self.img_projection = nn.Linear(image_dim_out, hidden_size)
|
136 |
-
elif projection_cls == 'mlp' and self.use_hd_transform:
|
137 |
-
dim_projection = hidden_size
|
138 |
-
depth = 2
|
139 |
-
layers = [nn.Linear(image_dim_out * 4, dim_projection)]
|
140 |
-
for _ in range(1, depth):
|
141 |
-
layers.extend([nn.GELU(),
|
142 |
-
nn.Linear(dim_projection, dim_projection)])
|
143 |
-
self.img_projection = nn.Sequential(*layers)
|
144 |
-
elif projection_cls == 'mlp':
|
145 |
-
dim_projection = hidden_size
|
146 |
-
depth = 2
|
147 |
-
layers = [nn.Linear(image_dim_out, dim_projection)]
|
148 |
-
for _ in range(1, depth):
|
149 |
-
layers.extend([nn.GELU(),
|
150 |
-
nn.Linear(dim_projection, dim_projection)])
|
151 |
-
self.img_projection = nn.Sequential(*layers)
|
152 |
-
else:
|
153 |
-
raise NotImplementedError(f'projection_cls = {projection_cls}, not implemented')
|
154 |
-
|
155 |
-
self.vocab_size = config.vocab_size
|
156 |
-
self.img_features = None
|
157 |
-
|
158 |
-
if isinstance(config.img_processor, dict):
|
159 |
-
self.layer_idx = config.img_processor.get('layer_idx', -2)
|
160 |
-
self.type_feature = config.img_processor.get('type_feature', 'patch')
|
161 |
-
else:
|
162 |
-
self.layer_idx = -2
|
163 |
-
self.type_feature = 'patch'
|
164 |
-
|
165 |
-
|
166 |
-
def set_img_features(self, img_features: torch.FloatTensor) -> None:
|
167 |
-
self.img_features = img_features
|
168 |
-
|
169 |
-
def set_img_sizes(self, img_sizes: torch.LongTensor) -> None:
|
170 |
-
self.img_sizes = img_sizes
|
171 |
-
|
172 |
-
def get_img_features(self, img_embeds: torch.FloatTensor) -> torch.FloatTensor:
|
173 |
-
LAYER_IDX = self.layer_idx
|
174 |
-
TYPE_FEATURE = self.type_feature
|
175 |
-
|
176 |
-
img_processor_output = self.img_processor(img_embeds, output_hidden_states=True)
|
177 |
-
img_feature = img_processor_output.hidden_states[LAYER_IDX]
|
178 |
-
|
179 |
-
if TYPE_FEATURE == "patch":
|
180 |
-
patch_feature = img_feature[:, 1:]
|
181 |
-
return patch_feature
|
182 |
-
|
183 |
-
raise NotImplementedError
|
184 |
-
|
185 |
-
def forward(
|
186 |
-
self, input_ids: torch.LongTensor, pixel_values: torch.FloatTensor, image_sizes=None
|
187 |
-
) -> torch.FloatTensor:
|
188 |
-
input_shape = input_ids.size()
|
189 |
-
input_ids = input_ids.view(-1, input_shape[-1])
|
190 |
-
|
191 |
-
# positions for image tokens
|
192 |
-
positions = torch.nonzero((input_ids < 0) & (input_ids > -MAX_INPUT_ID), as_tuple=True)
|
193 |
-
has_image = len(positions[0].tolist()) > 0
|
194 |
-
input_ids = input_ids.clamp_min(0).clamp_max(self.vocab_size).detach()
|
195 |
-
hidden_states = self.wte(input_ids)
|
196 |
-
|
197 |
-
if has_image:
|
198 |
-
assert self.use_hd_transform
|
199 |
-
num_images, num_crops, c, h, w = pixel_values.shape
|
200 |
-
assert c == 3 and h == w == 336
|
201 |
-
img_features = self.get_img_features(pixel_values.flatten(0, 1)).reshape(
|
202 |
-
num_images, num_crops, -1, self.image_dim_out
|
203 |
-
)
|
204 |
-
image_features_proj = self.hd_feature_transform(img_features, image_sizes)
|
205 |
-
hidden_states = hidden_states.index_put(
|
206 |
-
positions, image_features_proj, accumulate=False
|
207 |
-
)
|
208 |
-
|
209 |
-
if self.drop is not None:
|
210 |
-
hidden_states = self.drop(hidden_states)
|
211 |
-
|
212 |
-
return hidden_states
|
213 |
-
|
214 |
-
def hd_feature_transform(self, image_features, image_sizes):
|
215 |
-
"""
|
216 |
-
image_features: (num_images, num_crops+1, 24*24, 1024)
|
217 |
-
"""
|
218 |
-
assert (
|
219 |
-
self.hd_transform_order == 'sub_glb'
|
220 |
-
), f'hd_transform_order `{self.hd_transform_order}` not implemented'
|
221 |
-
if isinstance(self.img_projection, nn.Sequential):
|
222 |
-
target_device = self.img_projection[0].bias.device
|
223 |
-
target_dtype = self.img_projection[0].bias.dtype
|
224 |
-
else: # It's a single nn.Linear layer
|
225 |
-
target_device = self.img_projection.bias.device
|
226 |
-
target_dtype = self.img_projection.bias.dtype
|
227 |
-
|
228 |
-
global_image_features = image_features[:, 0] # (num_images, 24*24, 1024)
|
229 |
-
# global feature can be viewed as a special HD case with num_crops 1x1
|
230 |
-
global_image_features_hd = self.reshape_hd_patches_2x2merge(global_image_features, 1, 1)
|
231 |
-
global_image_features_hd_newline = self.add_image_newline(global_image_features_hd)
|
232 |
-
|
233 |
-
all_image_embeddings = []
|
234 |
-
# need a for loop to process each image because of different image sizes
|
235 |
-
# (patch arrangement is different for each image)
|
236 |
-
for i, img_size in enumerate(image_sizes):
|
237 |
-
h, w = img_size
|
238 |
-
h_crop = h // 336
|
239 |
-
w_crop = w // 336
|
240 |
-
num_crops = h_crop * w_crop
|
241 |
-
|
242 |
-
# NOTE: real num_crops is padded
|
243 |
-
# (num_crops, 24*24, 1024)
|
244 |
-
sub_image_features = image_features[i, 1 : 1 + num_crops]
|
245 |
-
sub_image_features_hd = self.reshape_hd_patches_2x2merge(
|
246 |
-
sub_image_features, h_crop, w_crop
|
247 |
-
)
|
248 |
-
sub_image_features_hd_newline = self.add_image_newline(sub_image_features_hd)
|
249 |
-
|
250 |
-
# [sub features, separator, global features]
|
251 |
-
all_image_embeddings.extend(
|
252 |
-
[
|
253 |
-
sub_image_features_hd_newline.squeeze(0), # (h_crop*12*(w_crop*12+1), 4096)
|
254 |
-
self.glb_GN.squeeze(0),
|
255 |
-
global_image_features_hd_newline[i],
|
256 |
-
]
|
257 |
-
)
|
258 |
-
|
259 |
-
image_features_proj = self.img_projection(
|
260 |
-
torch.cat(all_image_embeddings, dim=0).to(target_device).to(target_dtype)
|
261 |
-
)
|
262 |
-
|
263 |
-
return image_features_proj
|
264 |
-
|
265 |
-
def reshape_hd_patches_2x2merge(self, image_features, h_crop, w_crop):
|
266 |
-
"""
|
267 |
-
image_features: (num_images*num_crops, 24*24, 1024)
|
268 |
-
output: (num_images, h_crop*12, w_crop*12, 4096), h_crop*w_crop == num_crops
|
269 |
-
"""
|
270 |
-
N, L, C = image_features.shape
|
271 |
-
assert L == 24 * 24 and C == 1024 and N % (h_crop * w_crop) == 0
|
272 |
-
num_images = N // (h_crop * w_crop)
|
273 |
-
H = int(L**0.5)
|
274 |
-
image_features_hd = (
|
275 |
-
image_features.reshape(N, H, H, C) # N, 24, 24, 1024
|
276 |
-
.reshape(N, H // 2, 2, H // 2, 2, C) # N, 12, 2, 12, 2, 1024
|
277 |
-
.permute(0, 1, 3, 2, 4, 5) # N, 12, 12, 2, 2, 1024
|
278 |
-
.reshape(N, -1, 4 * C) # N, 144, 4096
|
279 |
-
.reshape(
|
280 |
-
num_images, h_crop, w_crop, H // 2, H // 2, -1
|
281 |
-
) # n_img, h_crop, w_crop, 12, 12, 4096
|
282 |
-
.permute(0, 1, 3, 2, 4, 5) # n_img, h_crop, 12, w_crop, 12, 4096
|
283 |
-
.reshape(
|
284 |
-
num_images, h_crop * H // 2, w_crop * H // 2, 4 * C
|
285 |
-
) # n_img, h_crop*12, w_crop*12, 4096
|
286 |
-
)
|
287 |
-
|
288 |
-
# alternative implementation using einops
|
289 |
-
# from einops import rearrange
|
290 |
-
# image_features_nhwc = rearrange(
|
291 |
-
# image_features,
|
292 |
-
# 'N (H W) c -> N H W c',
|
293 |
-
# H=H,
|
294 |
-
# W=H,
|
295 |
-
# )
|
296 |
-
# image_features_2x2merge = rearrange(
|
297 |
-
# image_features_nhwc,
|
298 |
-
# 'N (h h_pool) (w w_pool) c -> N h w (h_pool w_pool c)',
|
299 |
-
# h_pool=2,
|
300 |
-
# w_pool=2,
|
301 |
-
# )
|
302 |
-
# image_features_hd = rearrange(
|
303 |
-
# image_features_2x2merge,
|
304 |
-
# '(n_img h_crop w_crop) h w C -> n_img (h_crop h) (w_crop w) C',
|
305 |
-
# h_crop=h_crop,
|
306 |
-
# w_crop=w_crop,
|
307 |
-
# )
|
308 |
-
|
309 |
-
return image_features_hd
|
310 |
-
|
311 |
-
def add_image_newline(self, image_features_hd):
|
312 |
-
"""
|
313 |
-
image_features_hd: (num_images, h_crop*12, w_crop*12, 4096)
|
314 |
-
output: (num_images, (h_crop*12) * (w_crop*12+1), 4096)
|
315 |
-
"""
|
316 |
-
num_images, h, w, hid_dim = image_features_hd.shape
|
317 |
-
# add the newline token to the HD image feature patches
|
318 |
-
newline_embeddings = self.sub_GN.expand(num_images, h, -1, -1) # (n_img, h, 1, hid_dim)
|
319 |
-
image_features_hd_newline = torch.cat(
|
320 |
-
[image_features_hd, newline_embeddings], dim=2
|
321 |
-
).reshape(num_images, -1, hid_dim)
|
322 |
-
return image_features_hd_newline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
image_processing_phi3_v.py
DELETED
@@ -1,274 +0,0 @@
|
|
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
CHANGED
@@ -45,8 +45,6 @@ from transformers.utils import (
|
|
45 |
replace_return_docstrings,
|
46 |
)
|
47 |
from .configuration_phi3_v import Phi3VConfig
|
48 |
-
from .image_embedding_phi3_v import Phi3ImageEmbedding
|
49 |
-
|
50 |
|
51 |
try:
|
52 |
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
@@ -56,6 +54,310 @@ try:
|
|
56 |
except ImportError:
|
57 |
pass
|
58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
logger = logging.get_logger(__name__)
|
60 |
|
61 |
_CHECKPOINT_FOR_DOC = "microsoft/Phi-3-vision-128k-instruct"
|
|
|
45 |
replace_return_docstrings,
|
46 |
)
|
47 |
from .configuration_phi3_v import Phi3VConfig
|
|
|
|
|
48 |
|
49 |
try:
|
50 |
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
|
|
54 |
except ImportError:
|
55 |
pass
|
56 |
|
57 |
+
import torch
|
58 |
+
from torch import nn
|
59 |
+
from transformers import CLIPVisionConfig, CLIPVisionModel, PretrainedConfig
|
60 |
+
from transformers.models.clip.modeling_clip import CLIPAttention
|
61 |
+
from transformers.utils import logging
|
62 |
+
|
63 |
+
logger = logging.get_logger(__name__)
|
64 |
+
|
65 |
+
|
66 |
+
MAX_INPUT_ID = int(1e9)
|
67 |
+
|
68 |
+
CLIP_VIT_LARGE_PATCH14_336_CONFIG = CLIPVisionConfig(
|
69 |
+
attention_dropout=0.0,
|
70 |
+
dropout=0.0,
|
71 |
+
hidden_act="quick_gelu",
|
72 |
+
hidden_size=1024,
|
73 |
+
image_size=336,
|
74 |
+
initializer_factor=1.0,
|
75 |
+
initializer_range=0.02,
|
76 |
+
intermediate_size=4096,
|
77 |
+
layer_norm_eps=1e-05,
|
78 |
+
num_attention_heads=16,
|
79 |
+
num_channels=3,
|
80 |
+
num_hidden_layers=24,
|
81 |
+
patch_size=14,
|
82 |
+
projection_dim=768
|
83 |
+
)
|
84 |
+
|
85 |
+
class CLIPAttentionFA2(CLIPAttention):
|
86 |
+
"""Add flash attention 2 to CLIPAttention. (This is only used in the vision encoder)"""
|
87 |
+
|
88 |
+
def forward(self,
|
89 |
+
hidden_states,
|
90 |
+
attention_mask=None,
|
91 |
+
causal_attention_mask=None,
|
92 |
+
output_attentions=False,
|
93 |
+
):
|
94 |
+
"""Input shape: Batch x Time x Channel"""
|
95 |
+
|
96 |
+
assert attention_mask is None, "CLIPAttentionFA2 does not support attention_mask"
|
97 |
+
assert causal_attention_mask is None, "CLIPAttentionFA2 does not support causal_attention_mask"
|
98 |
+
assert output_attentions is False, "CLIPAttentionFA2 does not support output_attentions"
|
99 |
+
|
100 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
101 |
+
query_states = self.q_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
|
102 |
+
key_states = self.k_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
|
103 |
+
value_states = self.v_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
|
104 |
+
|
105 |
+
attn_output = flash_attn_func(
|
106 |
+
query_states,
|
107 |
+
key_states,
|
108 |
+
value_states,
|
109 |
+
dropout_p=self.dropout if self.training else 0.0,
|
110 |
+
softmax_scale=self.scale,
|
111 |
+
causal=False,
|
112 |
+
).reshape(bsz, tgt_len, embed_dim)
|
113 |
+
|
114 |
+
attn_output = self.out_proj(attn_output)
|
115 |
+
return attn_output, None
|
116 |
+
|
117 |
+
|
118 |
+
class Phi3ImageEmbedding(nn.Module):
|
119 |
+
"""Phi3 Image embedding."""
|
120 |
+
|
121 |
+
def __init__(self, config: PretrainedConfig, wte=None, **kwargs) -> None:
|
122 |
+
super().__init__()
|
123 |
+
|
124 |
+
# n_embed or hidden_size
|
125 |
+
hidden_size = config.n_embd if hasattr(config, 'n_embd') else config.hidden_size
|
126 |
+
if hasattr(config, 'embd_pdrop') or hasattr(config, 'embed_pdrop'):
|
127 |
+
embd_drop = config.embd_pdrop if hasattr(config, 'embd_pdrop') else config.embed_pdrop
|
128 |
+
self.drop = nn.Dropout(embd_drop)
|
129 |
+
else:
|
130 |
+
self.drop = None
|
131 |
+
|
132 |
+
self.wte = wte
|
133 |
+
|
134 |
+
if isinstance(config.img_processor, dict) and config.img_processor.get('name', None) == 'clip_vision_model':
|
135 |
+
assert 'model_name' in config.img_processor, 'model_name must be provided for CLIPVisionModel'
|
136 |
+
assert 'image_dim_out' in config.img_processor, 'image_dim_out must be provided for CLIPVisionModel'
|
137 |
+
assert 'num_img_tokens' in config.img_processor, 'num_img_tokens must be provided for CLIPVisionModel'
|
138 |
+
assert config.img_processor['model_name'] == 'openai/clip-vit-large-patch14-336'
|
139 |
+
clip_config = CLIP_VIT_LARGE_PATCH14_336_CONFIG
|
140 |
+
self.img_processor = CLIPVisionModel(clip_config)
|
141 |
+
image_dim_out = config.img_processor['image_dim_out']
|
142 |
+
self.num_img_tokens = config.img_processor['num_img_tokens']
|
143 |
+
|
144 |
+
# FA2 in CLIP
|
145 |
+
if config._attn_implementation == 'flash_attention_2':
|
146 |
+
for layer in self.img_processor.vision_model.encoder.layers:
|
147 |
+
clip_fa2 = CLIPAttentionFA2(clip_config)
|
148 |
+
del layer.self_attn
|
149 |
+
layer.self_attn = clip_fa2
|
150 |
+
else:
|
151 |
+
raise NotImplementedError(f'img_processor = {config.img_processor}, not implemented')
|
152 |
+
|
153 |
+
self.image_dim_out = image_dim_out
|
154 |
+
self.img_sizes = None
|
155 |
+
|
156 |
+
# global_gn and sub_gn for hd transform, serves as line separator
|
157 |
+
self.use_hd_transform = kwargs.get('use_hd_transform', False)
|
158 |
+
self.with_learnable_separator = kwargs.get('with_learnable_separator', False)
|
159 |
+
self.hd_transform_order = kwargs.get('hd_transform_order', 'glb_sub')
|
160 |
+
# with_hd_transform and with_learnable_separator should have same value
|
161 |
+
assert self.use_hd_transform == self.with_learnable_separator, 'use_hd_transform and with_learnable_separator should have same value'
|
162 |
+
if self.with_learnable_separator:
|
163 |
+
assert self.use_hd_transform, 'learnable separator is only for hd transform'
|
164 |
+
# 1024 * 4, merge spatial to channel dimension
|
165 |
+
self.glb_GN = nn.Parameter(torch.zeros([1, 1, self.image_dim_out * 4]))
|
166 |
+
self.sub_GN = nn.Parameter(torch.zeros([1, 1, 1, self.image_dim_out * 4]))
|
167 |
+
logger.info(f'learnable separator enabled for hd transform, hd_transform_order = {self.hd_transform_order}')
|
168 |
+
|
169 |
+
projection_cls = kwargs.get('projection_cls', 'linear')
|
170 |
+
if projection_cls == 'linear':
|
171 |
+
self.img_projection = nn.Linear(image_dim_out, hidden_size)
|
172 |
+
elif projection_cls == 'mlp' and self.use_hd_transform:
|
173 |
+
dim_projection = hidden_size
|
174 |
+
depth = 2
|
175 |
+
layers = [nn.Linear(image_dim_out * 4, dim_projection)]
|
176 |
+
for _ in range(1, depth):
|
177 |
+
layers.extend([nn.GELU(),
|
178 |
+
nn.Linear(dim_projection, dim_projection)])
|
179 |
+
self.img_projection = nn.Sequential(*layers)
|
180 |
+
elif projection_cls == 'mlp':
|
181 |
+
dim_projection = hidden_size
|
182 |
+
depth = 2
|
183 |
+
layers = [nn.Linear(image_dim_out, dim_projection)]
|
184 |
+
for _ in range(1, depth):
|
185 |
+
layers.extend([nn.GELU(),
|
186 |
+
nn.Linear(dim_projection, dim_projection)])
|
187 |
+
self.img_projection = nn.Sequential(*layers)
|
188 |
+
else:
|
189 |
+
raise NotImplementedError(f'projection_cls = {projection_cls}, not implemented')
|
190 |
+
|
191 |
+
self.vocab_size = config.vocab_size
|
192 |
+
self.img_features = None
|
193 |
+
|
194 |
+
if isinstance(config.img_processor, dict):
|
195 |
+
self.layer_idx = config.img_processor.get('layer_idx', -2)
|
196 |
+
self.type_feature = config.img_processor.get('type_feature', 'patch')
|
197 |
+
else:
|
198 |
+
self.layer_idx = -2
|
199 |
+
self.type_feature = 'patch'
|
200 |
+
|
201 |
+
|
202 |
+
def set_img_features(self, img_features: torch.FloatTensor) -> None:
|
203 |
+
self.img_features = img_features
|
204 |
+
|
205 |
+
def set_img_sizes(self, img_sizes: torch.LongTensor) -> None:
|
206 |
+
self.img_sizes = img_sizes
|
207 |
+
|
208 |
+
def get_img_features(self, img_embeds: torch.FloatTensor) -> torch.FloatTensor:
|
209 |
+
LAYER_IDX = self.layer_idx
|
210 |
+
TYPE_FEATURE = self.type_feature
|
211 |
+
|
212 |
+
img_processor_output = self.img_processor(img_embeds, output_hidden_states=True)
|
213 |
+
img_feature = img_processor_output.hidden_states[LAYER_IDX]
|
214 |
+
|
215 |
+
if TYPE_FEATURE == "patch":
|
216 |
+
patch_feature = img_feature[:, 1:]
|
217 |
+
return patch_feature
|
218 |
+
|
219 |
+
raise NotImplementedError
|
220 |
+
|
221 |
+
def forward(
|
222 |
+
self, input_ids: torch.LongTensor, pixel_values: torch.FloatTensor, image_sizes=None
|
223 |
+
) -> torch.FloatTensor:
|
224 |
+
input_shape = input_ids.size()
|
225 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
226 |
+
|
227 |
+
# positions for image tokens
|
228 |
+
positions = torch.nonzero((input_ids < 0) & (input_ids > -MAX_INPUT_ID), as_tuple=True)
|
229 |
+
has_image = len(positions[0].tolist()) > 0
|
230 |
+
input_ids = input_ids.clamp_min(0).clamp_max(self.vocab_size).detach()
|
231 |
+
hidden_states = self.wte(input_ids)
|
232 |
+
|
233 |
+
if has_image:
|
234 |
+
assert self.use_hd_transform
|
235 |
+
num_images, num_crops, c, h, w = pixel_values.shape
|
236 |
+
assert c == 3 and h == w == 336
|
237 |
+
img_features = self.get_img_features(pixel_values.flatten(0, 1)).reshape(
|
238 |
+
num_images, num_crops, -1, self.image_dim_out
|
239 |
+
)
|
240 |
+
image_features_proj = self.hd_feature_transform(img_features, image_sizes)
|
241 |
+
hidden_states = hidden_states.index_put(
|
242 |
+
positions, image_features_proj, accumulate=False
|
243 |
+
)
|
244 |
+
|
245 |
+
if self.drop is not None:
|
246 |
+
hidden_states = self.drop(hidden_states)
|
247 |
+
|
248 |
+
return hidden_states
|
249 |
+
|
250 |
+
def hd_feature_transform(self, image_features, image_sizes):
|
251 |
+
"""
|
252 |
+
image_features: (num_images, num_crops+1, 24*24, 1024)
|
253 |
+
"""
|
254 |
+
assert (
|
255 |
+
self.hd_transform_order == 'sub_glb'
|
256 |
+
), f'hd_transform_order `{self.hd_transform_order}` not implemented'
|
257 |
+
if isinstance(self.img_projection, nn.Sequential):
|
258 |
+
target_device = self.img_projection[0].bias.device
|
259 |
+
target_dtype = self.img_projection[0].bias.dtype
|
260 |
+
else: # It's a single nn.Linear layer
|
261 |
+
target_device = self.img_projection.bias.device
|
262 |
+
target_dtype = self.img_projection.bias.dtype
|
263 |
+
|
264 |
+
global_image_features = image_features[:, 0] # (num_images, 24*24, 1024)
|
265 |
+
# global feature can be viewed as a special HD case with num_crops 1x1
|
266 |
+
global_image_features_hd = self.reshape_hd_patches_2x2merge(global_image_features, 1, 1)
|
267 |
+
global_image_features_hd_newline = self.add_image_newline(global_image_features_hd)
|
268 |
+
|
269 |
+
all_image_embeddings = []
|
270 |
+
# need a for loop to process each image because of different image sizes
|
271 |
+
# (patch arrangement is different for each image)
|
272 |
+
for i, img_size in enumerate(image_sizes):
|
273 |
+
h, w = img_size
|
274 |
+
h_crop = h // 336
|
275 |
+
w_crop = w // 336
|
276 |
+
num_crops = h_crop * w_crop
|
277 |
+
|
278 |
+
# NOTE: real num_crops is padded
|
279 |
+
# (num_crops, 24*24, 1024)
|
280 |
+
sub_image_features = image_features[i, 1 : 1 + num_crops]
|
281 |
+
sub_image_features_hd = self.reshape_hd_patches_2x2merge(
|
282 |
+
sub_image_features, h_crop, w_crop
|
283 |
+
)
|
284 |
+
sub_image_features_hd_newline = self.add_image_newline(sub_image_features_hd)
|
285 |
+
|
286 |
+
# [sub features, separator, global features]
|
287 |
+
all_image_embeddings.extend(
|
288 |
+
[
|
289 |
+
sub_image_features_hd_newline.squeeze(0), # (h_crop*12*(w_crop*12+1), 4096)
|
290 |
+
self.glb_GN.squeeze(0),
|
291 |
+
global_image_features_hd_newline[i],
|
292 |
+
]
|
293 |
+
)
|
294 |
+
|
295 |
+
image_features_proj = self.img_projection(
|
296 |
+
torch.cat(all_image_embeddings, dim=0).to(target_device).to(target_dtype)
|
297 |
+
)
|
298 |
+
|
299 |
+
return image_features_proj
|
300 |
+
|
301 |
+
def reshape_hd_patches_2x2merge(self, image_features, h_crop, w_crop):
|
302 |
+
"""
|
303 |
+
image_features: (num_images*num_crops, 24*24, 1024)
|
304 |
+
output: (num_images, h_crop*12, w_crop*12, 4096), h_crop*w_crop == num_crops
|
305 |
+
"""
|
306 |
+
N, L, C = image_features.shape
|
307 |
+
assert L == 24 * 24 and C == 1024 and N % (h_crop * w_crop) == 0
|
308 |
+
num_images = N // (h_crop * w_crop)
|
309 |
+
H = int(L**0.5)
|
310 |
+
image_features_hd = (
|
311 |
+
image_features.reshape(N, H, H, C) # N, 24, 24, 1024
|
312 |
+
.reshape(N, H // 2, 2, H // 2, 2, C) # N, 12, 2, 12, 2, 1024
|
313 |
+
.permute(0, 1, 3, 2, 4, 5) # N, 12, 12, 2, 2, 1024
|
314 |
+
.reshape(N, -1, 4 * C) # N, 144, 4096
|
315 |
+
.reshape(
|
316 |
+
num_images, h_crop, w_crop, H // 2, H // 2, -1
|
317 |
+
) # n_img, h_crop, w_crop, 12, 12, 4096
|
318 |
+
.permute(0, 1, 3, 2, 4, 5) # n_img, h_crop, 12, w_crop, 12, 4096
|
319 |
+
.reshape(
|
320 |
+
num_images, h_crop * H // 2, w_crop * H // 2, 4 * C
|
321 |
+
) # n_img, h_crop*12, w_crop*12, 4096
|
322 |
+
)
|
323 |
+
|
324 |
+
# alternative implementation using einops
|
325 |
+
# from einops import rearrange
|
326 |
+
# image_features_nhwc = rearrange(
|
327 |
+
# image_features,
|
328 |
+
# 'N (H W) c -> N H W c',
|
329 |
+
# H=H,
|
330 |
+
# W=H,
|
331 |
+
# )
|
332 |
+
# image_features_2x2merge = rearrange(
|
333 |
+
# image_features_nhwc,
|
334 |
+
# 'N (h h_pool) (w w_pool) c -> N h w (h_pool w_pool c)',
|
335 |
+
# h_pool=2,
|
336 |
+
# w_pool=2,
|
337 |
+
# )
|
338 |
+
# image_features_hd = rearrange(
|
339 |
+
# image_features_2x2merge,
|
340 |
+
# '(n_img h_crop w_crop) h w C -> n_img (h_crop h) (w_crop w) C',
|
341 |
+
# h_crop=h_crop,
|
342 |
+
# w_crop=w_crop,
|
343 |
+
# )
|
344 |
+
|
345 |
+
return image_features_hd
|
346 |
+
|
347 |
+
def add_image_newline(self, image_features_hd):
|
348 |
+
"""
|
349 |
+
image_features_hd: (num_images, h_crop*12, w_crop*12, 4096)
|
350 |
+
output: (num_images, (h_crop*12) * (w_crop*12+1), 4096)
|
351 |
+
"""
|
352 |
+
num_images, h, w, hid_dim = image_features_hd.shape
|
353 |
+
# add the newline token to the HD image feature patches
|
354 |
+
newline_embeddings = self.sub_GN.expand(num_images, h, -1, -1) # (n_img, h, 1, hid_dim)
|
355 |
+
image_features_hd_newline = torch.cat(
|
356 |
+
[image_features_hd, newline_embeddings], dim=2
|
357 |
+
).reshape(num_images, -1, hid_dim)
|
358 |
+
return image_features_hd_newline
|
359 |
+
|
360 |
+
|
361 |
logger = logging.get_logger(__name__)
|
362 |
|
363 |
_CHECKPOINT_FOR_DOC = "microsoft/Phi-3-vision-128k-instruct"
|
processing_phi3_v.py
CHANGED
@@ -27,7 +27,268 @@ from transformers.image_utils import ImageInput
|
|
27 |
from transformers.processing_utils import ProcessorMixin
|
28 |
from transformers.tokenization_utils_base import PaddingStrategy, TextInput, TruncationStrategy
|
29 |
from transformers.utils import TensorType
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
transformers.Phi3VImageProcessor = Phi3VImageProcessor
|
32 |
|
33 |
class Phi3VProcessor(ProcessorMixin):
|
|
|
27 |
from transformers.processing_utils import ProcessorMixin
|
28 |
from transformers.tokenization_utils_base import PaddingStrategy, TextInput, TruncationStrategy
|
29 |
from transformers.utils import TensorType
|
30 |
+
|
31 |
+
|
32 |
+
"""Image processor class for Phi3-V."""
|
33 |
+
|
34 |
+
from typing import List, Optional, Union
|
35 |
+
|
36 |
+
import numpy as np
|
37 |
+
|
38 |
+
from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
|
39 |
+
from transformers.image_transforms import (
|
40 |
+
convert_to_rgb,
|
41 |
+
)
|
42 |
+
from transformers.image_utils import (
|
43 |
+
OPENAI_CLIP_MEAN,
|
44 |
+
OPENAI_CLIP_STD,
|
45 |
+
ImageInput,
|
46 |
+
make_list_of_images,
|
47 |
+
valid_images,
|
48 |
+
)
|
49 |
+
from transformers.utils import TensorType, is_vision_available, logging
|
50 |
+
|
51 |
+
from transformers import AutoImageProcessor
|
52 |
+
|
53 |
+
logger = logging.get_logger(__name__)
|
54 |
+
|
55 |
+
|
56 |
+
if is_vision_available():
|
57 |
+
from PIL import Image
|
58 |
+
|
59 |
+
import torch
|
60 |
+
import torchvision
|
61 |
+
|
62 |
+
def padding_336(b):
|
63 |
+
width, height = b.size
|
64 |
+
tar = int(np.ceil(height / 336) * 336)
|
65 |
+
top_padding = int((tar - height)/2)
|
66 |
+
bottom_padding = tar - height - top_padding
|
67 |
+
left_padding = 0
|
68 |
+
right_padding = 0
|
69 |
+
b = torchvision.transforms.functional.pad(b, [left_padding, top_padding, right_padding, bottom_padding], fill=[255,255,255])
|
70 |
+
|
71 |
+
return b
|
72 |
+
|
73 |
+
def calc_padded_size(width, height, padding_unit=336):
|
74 |
+
target_height = int(np.ceil(height / padding_unit) * padding_unit)
|
75 |
+
top_padding = int((target_height - height) / 2)
|
76 |
+
bottom_padding = target_height - height - top_padding
|
77 |
+
left_padding = 0
|
78 |
+
right_padding = 0
|
79 |
+
padded_width = width + left_padding + right_padding
|
80 |
+
padded_height = height + top_padding + bottom_padding
|
81 |
+
return padded_width, padded_height
|
82 |
+
|
83 |
+
def HD_transform(img, hd_num=16):
|
84 |
+
width, height = img.size
|
85 |
+
trans = False
|
86 |
+
if width < height:
|
87 |
+
img = img.transpose(Image.TRANSPOSE)
|
88 |
+
trans = True
|
89 |
+
width, height = img.size
|
90 |
+
ratio = (width/ height)
|
91 |
+
scale = 1
|
92 |
+
while scale*np.ceil(scale/ratio) <= hd_num:
|
93 |
+
scale += 1
|
94 |
+
scale -= 1
|
95 |
+
new_w = int(scale * 336)
|
96 |
+
new_h = int(new_w / ratio)
|
97 |
+
|
98 |
+
img = torchvision.transforms.functional.resize(img, [new_h, new_w],)
|
99 |
+
img = padding_336(img)
|
100 |
+
width, height = img.size
|
101 |
+
if trans:
|
102 |
+
img = img.transpose(Image.TRANSPOSE)
|
103 |
+
|
104 |
+
return img
|
105 |
+
|
106 |
+
def calc_hd_transform_size(width, height, hd_num=16):
|
107 |
+
transposed = False
|
108 |
+
if width < height:
|
109 |
+
width, height = height, width
|
110 |
+
transposed = True
|
111 |
+
|
112 |
+
ratio = width / height
|
113 |
+
scale = 1
|
114 |
+
while scale * np.ceil(scale / ratio) <= hd_num:
|
115 |
+
scale += 1
|
116 |
+
scale -= 1
|
117 |
+
|
118 |
+
new_width = int(scale * 336)
|
119 |
+
new_height = int(new_width / ratio)
|
120 |
+
|
121 |
+
padded_width, padded_height = calc_padded_size(new_width, new_height)
|
122 |
+
|
123 |
+
if transposed:
|
124 |
+
padded_width, padded_height = padded_height, padded_width
|
125 |
+
|
126 |
+
return padded_width, padded_height
|
127 |
+
|
128 |
+
def pad_to_max_num_crops_tensor(images, max_crops=5):
|
129 |
+
"""
|
130 |
+
images: B x 3 x H x W, B<=max_crops
|
131 |
+
"""
|
132 |
+
B, _, H, W = images.shape
|
133 |
+
if B < max_crops:
|
134 |
+
pad = torch.zeros(max_crops - B, 3, H, W, dtype=images.dtype, device=images.device)
|
135 |
+
images = torch.cat([images, pad], dim=0)
|
136 |
+
return images
|
137 |
+
|
138 |
+
|
139 |
+
class Phi3VImageProcessor(BaseImageProcessor):
|
140 |
+
r"""
|
141 |
+
Constructs a Phi3 image processor. Based on [`CLIPImageProcessor`] with incorporation of additional techniques
|
142 |
+
for processing high resolution images as explained in the [InternLM-XComposer2-4KHD](https://arxiv.org/pdf/2404.06512)
|
143 |
+
|
144 |
+
Args:
|
145 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
|
146 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
147 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
148 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
|
149 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
150 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
151 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
152 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
153 |
+
Whether to convert the image to RGB.
|
154 |
+
"""
|
155 |
+
|
156 |
+
model_input_names = ["pixel_values"]
|
157 |
+
|
158 |
+
def __init__(
|
159 |
+
self,
|
160 |
+
num_crops: int = 1,
|
161 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
162 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
163 |
+
do_convert_rgb: bool = True,
|
164 |
+
**kwargs,
|
165 |
+
) -> None:
|
166 |
+
super().__init__(**kwargs)
|
167 |
+
self.num_crops = num_crops
|
168 |
+
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
|
169 |
+
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
|
170 |
+
self.do_convert_rgb = do_convert_rgb
|
171 |
+
|
172 |
+
def calc_num_image_tokens(
|
173 |
+
self,
|
174 |
+
images: ImageInput
|
175 |
+
):
|
176 |
+
""" Calculate the number of image tokens for each image.
|
177 |
+
Args:
|
178 |
+
images (`ImageInput`):
|
179 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
180 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
181 |
+
"""
|
182 |
+
images = make_list_of_images(images)
|
183 |
+
|
184 |
+
if not valid_images(images):
|
185 |
+
raise ValueError(
|
186 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
187 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
188 |
+
)
|
189 |
+
|
190 |
+
images = [image.convert('RGB') for image in images]
|
191 |
+
# (H, W, C)
|
192 |
+
elems = [HD_transform(im, hd_num = self.num_crops) for im in images]
|
193 |
+
shapes = [[im.size[1], im.size[0]] for im in elems]
|
194 |
+
num_img_tokens = [int((h//336*w//336+1)*144 + 1 + (h//336+1)*12) for h, w in shapes]
|
195 |
+
return num_img_tokens
|
196 |
+
|
197 |
+
def calc_num_image_tokens_from_image_size(self, width, height):
|
198 |
+
"""
|
199 |
+
Calculate the number of image tokens for a given image size.
|
200 |
+
Args:
|
201 |
+
width (`int`): Width of the image.
|
202 |
+
height (`int`): Height of the image.
|
203 |
+
"""
|
204 |
+
new_width, new_height = calc_hd_transform_size(width, height, hd_num=self.num_crops)
|
205 |
+
num_img_tokens = int((new_height // 336 * new_width // 336 + 1) * 144 + 1 + (new_height // 336 + 1) * 12)
|
206 |
+
return num_img_tokens
|
207 |
+
|
208 |
+
def preprocess(
|
209 |
+
self,
|
210 |
+
images: ImageInput,
|
211 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
212 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
213 |
+
do_convert_rgb: bool = None,
|
214 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
215 |
+
):
|
216 |
+
"""
|
217 |
+
Args:
|
218 |
+
images (`ImageInput`):
|
219 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
220 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
221 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
222 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
223 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
224 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
225 |
+
`True`.
|
226 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
227 |
+
Whether to convert the image to RGB.
|
228 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
229 |
+
The type of tensors to return. Can be one of:
|
230 |
+
- Unset: Return a list of `np.ndarray`.
|
231 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
232 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
233 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
234 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
235 |
+
"""
|
236 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
237 |
+
image_std = image_std if image_std is not None else self.image_std
|
238 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
239 |
+
|
240 |
+
images = make_list_of_images(images)
|
241 |
+
|
242 |
+
if not valid_images(images):
|
243 |
+
raise ValueError(
|
244 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
245 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
246 |
+
)
|
247 |
+
|
248 |
+
if do_convert_rgb:
|
249 |
+
images = [convert_to_rgb(image) for image in images]
|
250 |
+
|
251 |
+
image_sizes = []
|
252 |
+
img_processor = torchvision.transforms.Compose([
|
253 |
+
torchvision.transforms.ToTensor(),
|
254 |
+
torchvision.transforms.Normalize(image_mean, image_std)
|
255 |
+
])
|
256 |
+
|
257 |
+
# PIL images
|
258 |
+
# HD_transform pad images to size of multiiply of 336, 336
|
259 |
+
# convert to RGB first
|
260 |
+
images = [image.convert('RGB') for image in images]
|
261 |
+
elems = [HD_transform(im, hd_num = self.num_crops) for im in images]
|
262 |
+
# tensor transform and normalize
|
263 |
+
hd_images = [img_processor(im) for im in elems]
|
264 |
+
# create global image
|
265 |
+
global_image = [torch.nn.functional.interpolate(im.unsqueeze(0).float(), size=(336, 336), mode='bicubic',).to(im.dtype) for im in hd_images]
|
266 |
+
|
267 |
+
# [(3, h, w)], where h, w is multiple of 336
|
268 |
+
shapes = [[im.size(1), im.size(2)] for im in hd_images]
|
269 |
+
num_img_tokens = [int(((h//336)*(w//336)+1)*144 + 1 + (h//336+1)*12) for h, w in shapes]
|
270 |
+
# reshape to channel dimension -> (num_images, num_crops, 3, 336, 336)
|
271 |
+
# (1, 3, h//336, 336, w//336, 336) -> (1, h//336, w//336, 3, 336, 336) -> (h//336*w//336, 3, 336, 336)
|
272 |
+
hd_images_reshape = [im.reshape(1, 3, h//336, 336, w//336, 336).permute(0,2,4,1,3,5).reshape(-1, 3, 336, 336).contiguous() for im, (h, w) in zip(hd_images, shapes)]
|
273 |
+
# concat global image and local image
|
274 |
+
hd_images_reshape = [torch.cat([_global_image] + [_im], dim=0) for _global_image, _im in zip(global_image, hd_images_reshape)]
|
275 |
+
|
276 |
+
# pad to max_num_crops
|
277 |
+
image_transformed = [pad_to_max_num_crops_tensor(im, self.num_crops+1) for im in hd_images_reshape]
|
278 |
+
image_transformed = torch.stack(image_transformed, dim=0)
|
279 |
+
image_sizes = [torch.LongTensor(_shapes) for _shapes in shapes]
|
280 |
+
padded_images = image_transformed
|
281 |
+
image_sizes = shapes
|
282 |
+
|
283 |
+
data = {"pixel_values": padded_images,
|
284 |
+
"image_sizes": image_sizes,
|
285 |
+
"num_img_tokens": num_img_tokens
|
286 |
+
}
|
287 |
+
|
288 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
289 |
+
|
290 |
+
AutoImageProcessor.register("Phi3VImageProcessor", Phi3VImageProcessor)
|
291 |
+
|
292 |
transformers.Phi3VImageProcessor = Phi3VImageProcessor
|
293 |
|
294 |
class Phi3VProcessor(ProcessorMixin):
|