Commit
•
866d169
1
Parent(s):
1a87b10
Rewrite image embedding to remove the in-place op (#53)
Browse files- remove the in-place op (b185b062202fd6fc9d48b5c53fc95b320341a1d9)
Co-authored-by: Yen-Chun Chen <[email protected]>
- image_embedding_phi3_v.py +129 -153
image_embedding_phi3_v.py
CHANGED
@@ -13,8 +13,6 @@
|
|
13 |
# See the License for the specific language governing permissions and
|
14 |
# limitations under the License.
|
15 |
|
16 |
-
from datetime import datetime
|
17 |
-
|
18 |
import torch
|
19 |
from torch import nn
|
20 |
from transformers import CLIPVisionConfig, CLIPVisionModel, PretrainedConfig
|
@@ -28,6 +26,9 @@ except ImportError:
|
|
28 |
|
29 |
logger = logging.get_logger(__name__)
|
30 |
|
|
|
|
|
|
|
31 |
CLIP_VIT_LARGE_PATCH14_336_CONFIG = CLIPVisionConfig(
|
32 |
attention_dropout=0.0,
|
33 |
dropout=0.0,
|
@@ -179,32 +180,44 @@ class Phi3ImageEmbedding(nn.Module):
|
|
179 |
patch_feature = img_feature[:, 1:]
|
180 |
return patch_feature
|
181 |
|
182 |
-
if TYPE_FEATURE == "cls_patch":
|
183 |
-
return img_feature
|
184 |
-
|
185 |
raise NotImplementedError
|
186 |
|
187 |
-
def forward(
|
188 |
-
|
189 |
-
|
190 |
-
img_embeds = pixel_values
|
191 |
-
img_sizes = image_sizes
|
192 |
-
|
193 |
-
if self.img_features is not None:
|
194 |
-
img_embeds = self.img_features.clone()
|
195 |
-
self.img_features = None
|
196 |
-
|
197 |
-
if self.img_sizes is not None:
|
198 |
-
img_sizes = self.img_sizes
|
199 |
-
|
200 |
input_shape = input_ids.size()
|
201 |
input_ids = input_ids.view(-1, input_shape[-1])
|
202 |
|
203 |
-
|
204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
|
206 |
-
|
207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
208 |
if isinstance(self.img_projection, nn.Sequential):
|
209 |
target_device = self.img_projection[0].bias.device
|
210 |
target_dtype = self.img_projection[0].bias.dtype
|
@@ -212,135 +225,98 @@ class Phi3ImageEmbedding(nn.Module):
|
|
212 |
target_device = self.img_projection.bias.device
|
213 |
target_dtype = self.img_projection.bias.dtype
|
214 |
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
)
|
311 |
-
img_set_tensor = self.img_projection(tt) # adapted visual features.
|
312 |
-
else:
|
313 |
-
raise NotImplementedError
|
314 |
-
select = True
|
315 |
-
|
316 |
-
with torch.no_grad():
|
317 |
-
input_ids.clamp_min_(0).clamp_max_(self.vocab_size)
|
318 |
-
|
319 |
-
hidden_states = self.wte(input_ids)
|
320 |
-
|
321 |
-
if select:
|
322 |
-
if hd_transform:
|
323 |
-
idx = 0
|
324 |
-
for i, cnt in enumerate(num_img_tokens):
|
325 |
-
hidden_states[positions[idx, 0], positions[idx, 1] : positions[idx, 1] + cnt] = (
|
326 |
-
img_set_tensor[i]
|
327 |
-
.to(hidden_states.dtype)
|
328 |
-
.to(hidden_states.device)
|
329 |
-
)
|
330 |
-
idx += cnt
|
331 |
-
else:
|
332 |
-
idx = 0
|
333 |
-
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)}'
|
334 |
-
for i, g in enumerate(selected_g_values):
|
335 |
-
cnt = self.num_img_tokens
|
336 |
-
hidden_states[positions[idx, 0], positions[idx, 1] : positions[idx, 1] + cnt] = (
|
337 |
-
img_set_tensor[i * cnt : (i + 1) * cnt]
|
338 |
-
.to(hidden_states.dtype)
|
339 |
-
.to(hidden_states.device)
|
340 |
-
)
|
341 |
-
idx += cnt
|
342 |
-
|
343 |
-
if self.drop is not None:
|
344 |
-
hidden_states = self.drop(hidden_states)
|
345 |
-
|
346 |
-
return hidden_states
|
|
|
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
|
|
|
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,
|
|
|
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
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|