PyTorch
English
Tevatron
phi3_v
vidore
custom_code
MrLight commited on
Commit
e08889c
1 Parent(s): c203abb

Create image_embedding_phi3_v.py

Browse files
Files changed (1) hide show
  1. image_embedding_phi3_v.py +322 -0
image_embedding_phi3_v.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import torch
17
+ from torch import nn
18
+ from transformers import CLIPVisionConfig, CLIPVisionModel, PretrainedConfig
19
+ from transformers.models.clip.modeling_clip import CLIPAttention
20
+ from transformers.utils import logging
21
+
22
+ try:
23
+ from flash_attn import flash_attn_func
24
+ except ImportError:
25
+ pass
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ MAX_INPUT_ID = int(1e9)
31
+
32
+ CLIP_VIT_LARGE_PATCH14_336_CONFIG = CLIPVisionConfig(
33
+ attention_dropout=0.0,
34
+ dropout=0.0,
35
+ hidden_act="quick_gelu",
36
+ hidden_size=1024,
37
+ image_size=336,
38
+ initializer_factor=1.0,
39
+ initializer_range=0.02,
40
+ intermediate_size=4096,
41
+ layer_norm_eps=1e-05,
42
+ num_attention_heads=16,
43
+ num_channels=3,
44
+ num_hidden_layers=24,
45
+ patch_size=14,
46
+ projection_dim=768
47
+ )
48
+
49
+ class CLIPAttentionFA2(CLIPAttention):
50
+ """Add flash attention 2 to CLIPAttention. (This is only used in the vision encoder)"""
51
+
52
+ def forward(self,
53
+ hidden_states,
54
+ attention_mask=None,
55
+ causal_attention_mask=None,
56
+ output_attentions=False,
57
+ ):
58
+ """Input shape: Batch x Time x Channel"""
59
+
60
+ assert attention_mask is None, "CLIPAttentionFA2 does not support attention_mask"
61
+ assert causal_attention_mask is None, "CLIPAttentionFA2 does not support causal_attention_mask"
62
+ assert output_attentions is False, "CLIPAttentionFA2 does not support output_attentions"
63
+
64
+ bsz, tgt_len, embed_dim = hidden_states.size()
65
+ query_states = self.q_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
66
+ key_states = self.k_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
67
+ value_states = self.v_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
68
+
69
+ attn_output = flash_attn_func(
70
+ query_states,
71
+ key_states,
72
+ value_states,
73
+ dropout_p=self.dropout if self.training else 0.0,
74
+ softmax_scale=self.scale,
75
+ causal=False,
76
+ ).reshape(bsz, tgt_len, embed_dim)
77
+
78
+ attn_output = self.out_proj(attn_output)
79
+ return attn_output, None
80
+
81
+
82
+ class Phi3ImageEmbedding(nn.Module):
83
+ """Phi3 Image embedding."""
84
+
85
+ def __init__(self, config: PretrainedConfig, wte=None, **kwargs) -> None:
86
+ super().__init__()
87
+
88
+ # n_embed or hidden_size
89
+ hidden_size = config.n_embd if hasattr(config, 'n_embd') else config.hidden_size
90
+ if hasattr(config, 'embd_pdrop') or hasattr(config, 'embed_pdrop'):
91
+ embd_drop = config.embd_pdrop if hasattr(config, 'embd_pdrop') else config.embed_pdrop
92
+ self.drop = nn.Dropout(embd_drop)
93
+ else:
94
+ self.drop = None
95
+
96
+ self.wte = wte
97
+
98
+ if isinstance(config.img_processor, dict) and config.img_processor.get('name', None) == 'clip_vision_model':
99
+ assert 'model_name' in config.img_processor, 'model_name must be provided for CLIPVisionModel'
100
+ assert 'image_dim_out' in config.img_processor, 'image_dim_out must be provided for CLIPVisionModel'
101
+ assert 'num_img_tokens' in config.img_processor, 'num_img_tokens must be provided for CLIPVisionModel'
102
+ assert config.img_processor['model_name'] == 'openai/clip-vit-large-patch14-336'
103
+ clip_config = CLIP_VIT_LARGE_PATCH14_336_CONFIG
104
+ self.img_processor = CLIPVisionModel(clip_config)
105
+ image_dim_out = config.img_processor['image_dim_out']
106
+ self.num_img_tokens = config.img_processor['num_img_tokens']
107
+
108
+ # FA2 in CLIP
109
+ if config._attn_implementation == 'flash_attention_2':
110
+ for layer in self.img_processor.vision_model.encoder.layers:
111
+ clip_fa2 = CLIPAttentionFA2(clip_config)
112
+ del layer.self_attn
113
+ layer.self_attn = clip_fa2
114
+ else:
115
+ raise NotImplementedError(f'img_processor = {config.img_processor}, not implemented')
116
+
117
+ self.image_dim_out = image_dim_out
118
+ self.img_sizes = None
119
+
120
+ # global_gn and sub_gn for hd transform, serves as line separator
121
+ self.use_hd_transform = kwargs.get('use_hd_transform', False)
122
+ self.with_learnable_separator = kwargs.get('with_learnable_separator', False)
123
+ self.hd_transform_order = kwargs.get('hd_transform_order', 'glb_sub')
124
+ # with_hd_transform and with_learnable_separator should have same value
125
+ assert self.use_hd_transform == self.with_learnable_separator, 'use_hd_transform and with_learnable_separator should have same value'
126
+ if self.with_learnable_separator:
127
+ assert self.use_hd_transform, 'learnable separator is only for hd transform'
128
+ # 1024 * 4, merge spatial to channel dimension
129
+ self.glb_GN = nn.Parameter(torch.zeros([1, 1, self.image_dim_out * 4]))
130
+ self.sub_GN = nn.Parameter(torch.zeros([1, 1, 1, self.image_dim_out * 4]))
131
+ logger.info(f'learnable separator enabled for hd transform, hd_transform_order = {self.hd_transform_order}')
132
+
133
+ projection_cls = kwargs.get('projection_cls', 'linear')
134
+ if projection_cls == 'linear':
135
+ self.img_projection = nn.Linear(image_dim_out, hidden_size)
136
+ elif projection_cls == 'mlp' and self.use_hd_transform:
137
+ dim_projection = hidden_size
138
+ depth = 2
139
+ layers = [nn.Linear(image_dim_out * 4, dim_projection)]
140
+ for _ in range(1, depth):
141
+ layers.extend([nn.GELU(),
142
+ nn.Linear(dim_projection, dim_projection)])
143
+ self.img_projection = nn.Sequential(*layers)
144
+ elif projection_cls == 'mlp':
145
+ dim_projection = hidden_size
146
+ depth = 2
147
+ layers = [nn.Linear(image_dim_out, dim_projection)]
148
+ for _ in range(1, depth):
149
+ layers.extend([nn.GELU(),
150
+ nn.Linear(dim_projection, dim_projection)])
151
+ self.img_projection = nn.Sequential(*layers)
152
+ else:
153
+ raise NotImplementedError(f'projection_cls = {projection_cls}, not implemented')
154
+
155
+ self.vocab_size = config.vocab_size
156
+ self.img_features = None
157
+
158
+ if isinstance(config.img_processor, dict):
159
+ self.layer_idx = config.img_processor.get('layer_idx', -2)
160
+ self.type_feature = config.img_processor.get('type_feature', 'patch')
161
+ else:
162
+ self.layer_idx = -2
163
+ self.type_feature = 'patch'
164
+
165
+
166
+ def set_img_features(self, img_features: torch.FloatTensor) -> None:
167
+ self.img_features = img_features
168
+
169
+ def set_img_sizes(self, img_sizes: torch.LongTensor) -> None:
170
+ self.img_sizes = img_sizes
171
+
172
+ def get_img_features(self, img_embeds: torch.FloatTensor) -> torch.FloatTensor:
173
+ LAYER_IDX = self.layer_idx
174
+ TYPE_FEATURE = self.type_feature
175
+
176
+ img_processor_output = self.img_processor(img_embeds, output_hidden_states=True)
177
+ img_feature = img_processor_output.hidden_states[LAYER_IDX]
178
+
179
+ if TYPE_FEATURE == "patch":
180
+ patch_feature = img_feature[:, 1:]
181
+ return patch_feature
182
+
183
+ raise NotImplementedError
184
+
185
+ def forward(
186
+ self, input_ids: torch.LongTensor, pixel_values: torch.FloatTensor, image_sizes=None
187
+ ) -> torch.FloatTensor:
188
+ input_shape = input_ids.size()
189
+ input_ids = input_ids.view(-1, input_shape[-1])
190
+
191
+ # positions for image tokens
192
+ positions = torch.nonzero((input_ids < 0) & (input_ids > -MAX_INPUT_ID), as_tuple=True)
193
+ has_image = len(positions[0].tolist()) > 0
194
+ input_ids = input_ids.clamp_min(0).clamp_max(self.vocab_size).detach()
195
+ hidden_states = self.wte(input_ids)
196
+
197
+ if has_image:
198
+ assert self.use_hd_transform
199
+ num_images, num_crops, c, h, w = pixel_values.shape
200
+ assert c == 3 and h == w == 336
201
+ img_features = self.get_img_features(pixel_values.flatten(0, 1)).reshape(
202
+ num_images, num_crops, -1, self.image_dim_out
203
+ )
204
+ image_features_proj = self.hd_feature_transform(img_features, image_sizes)
205
+ hidden_states = hidden_states.index_put(
206
+ positions, image_features_proj, accumulate=False
207
+ )
208
+
209
+ if self.drop is not None:
210
+ hidden_states = self.drop(hidden_states)
211
+
212
+ return hidden_states
213
+
214
+ def hd_feature_transform(self, image_features, image_sizes):
215
+ """
216
+ image_features: (num_images, num_crops+1, 24*24, 1024)
217
+ """
218
+ assert (
219
+ self.hd_transform_order == 'sub_glb'
220
+ ), f'hd_transform_order `{self.hd_transform_order}` not implemented'
221
+ if isinstance(self.img_projection, nn.Sequential):
222
+ target_device = self.img_projection[0].bias.device
223
+ target_dtype = self.img_projection[0].bias.dtype
224
+ else: # It's a single nn.Linear layer
225
+ target_device = self.img_projection.bias.device
226
+ target_dtype = self.img_projection.bias.dtype
227
+
228
+ global_image_features = image_features[:, 0] # (num_images, 24*24, 1024)
229
+ # global feature can be viewed as a special HD case with num_crops 1x1
230
+ global_image_features_hd = self.reshape_hd_patches_2x2merge(global_image_features, 1, 1)
231
+ global_image_features_hd_newline = self.add_image_newline(global_image_features_hd)
232
+
233
+ all_image_embeddings = []
234
+ # need a for loop to process each image because of different image sizes
235
+ # (patch arrangement is different for each image)
236
+ for i, img_size in enumerate(image_sizes):
237
+ h, w = img_size
238
+ h_crop = h // 336
239
+ w_crop = w // 336
240
+ num_crops = h_crop * w_crop
241
+
242
+ # NOTE: real num_crops is padded
243
+ # (num_crops, 24*24, 1024)
244
+ sub_image_features = image_features[i, 1 : 1 + num_crops]
245
+ sub_image_features_hd = self.reshape_hd_patches_2x2merge(
246
+ sub_image_features, h_crop, w_crop
247
+ )
248
+ sub_image_features_hd_newline = self.add_image_newline(sub_image_features_hd)
249
+
250
+ # [sub features, separator, global features]
251
+ all_image_embeddings.extend(
252
+ [
253
+ sub_image_features_hd_newline.squeeze(0), # (h_crop*12*(w_crop*12+1), 4096)
254
+ self.glb_GN.squeeze(0),
255
+ global_image_features_hd_newline[i],
256
+ ]
257
+ )
258
+
259
+ image_features_proj = self.img_projection(
260
+ torch.cat(all_image_embeddings, dim=0).to(target_device).to(target_dtype)
261
+ )
262
+
263
+ return image_features_proj
264
+
265
+ def reshape_hd_patches_2x2merge(self, image_features, h_crop, w_crop):
266
+ """
267
+ image_features: (num_images*num_crops, 24*24, 1024)
268
+ output: (num_images, h_crop*12, w_crop*12, 4096), h_crop*w_crop == num_crops
269
+ """
270
+ N, L, C = image_features.shape
271
+ assert L == 24 * 24 and C == 1024 and N % (h_crop * w_crop) == 0
272
+ num_images = N // (h_crop * w_crop)
273
+ H = int(L**0.5)
274
+ image_features_hd = (
275
+ image_features.reshape(N, H, H, C) # N, 24, 24, 1024
276
+ .reshape(N, H // 2, 2, H // 2, 2, C) # N, 12, 2, 12, 2, 1024
277
+ .permute(0, 1, 3, 2, 4, 5) # N, 12, 12, 2, 2, 1024
278
+ .reshape(N, -1, 4 * C) # N, 144, 4096
279
+ .reshape(
280
+ num_images, h_crop, w_crop, H // 2, H // 2, -1
281
+ ) # n_img, h_crop, w_crop, 12, 12, 4096
282
+ .permute(0, 1, 3, 2, 4, 5) # n_img, h_crop, 12, w_crop, 12, 4096
283
+ .reshape(
284
+ num_images, h_crop * H // 2, w_crop * H // 2, 4 * C
285
+ ) # n_img, h_crop*12, w_crop*12, 4096
286
+ )
287
+
288
+ # alternative implementation using einops
289
+ # from einops import rearrange
290
+ # image_features_nhwc = rearrange(
291
+ # image_features,
292
+ # 'N (H W) c -> N H W c',
293
+ # H=H,
294
+ # W=H,
295
+ # )
296
+ # image_features_2x2merge = rearrange(
297
+ # image_features_nhwc,
298
+ # 'N (h h_pool) (w w_pool) c -> N h w (h_pool w_pool c)',
299
+ # h_pool=2,
300
+ # w_pool=2,
301
+ # )
302
+ # image_features_hd = rearrange(
303
+ # image_features_2x2merge,
304
+ # '(n_img h_crop w_crop) h w C -> n_img (h_crop h) (w_crop w) C',
305
+ # h_crop=h_crop,
306
+ # w_crop=w_crop,
307
+ # )
308
+
309
+ return image_features_hd
310
+
311
+ def add_image_newline(self, image_features_hd):
312
+ """
313
+ image_features_hd: (num_images, h_crop*12, w_crop*12, 4096)
314
+ output: (num_images, (h_crop*12) * (w_crop*12+1), 4096)
315
+ """
316
+ num_images, h, w, hid_dim = image_features_hd.shape
317
+ # add the newline token to the HD image feature patches
318
+ newline_embeddings = self.sub_GN.expand(num_images, h, -1, -1) # (n_img, h, 1, hid_dim)
319
+ image_features_hd_newline = torch.cat(
320
+ [image_features_hd, newline_embeddings], dim=2
321
+ ).reshape(num_images, -1, hid_dim)
322
+ return image_features_hd_newline