BenkHel commited on
Commit
2edf11e
·
verified ·
1 Parent(s): be7612d

Upload llava_arch.py

Browse files
Files changed (1) hide show
  1. llava_arch.py +381 -0
llava_arch.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ------------------------------------------------------------------------
15
+ # Modified from LLaVA (https://github.com/haotian-liu/LLaVA)
16
+ # Copyright 2024 Jiachen Li
17
+ # ------------------------------------------------------------------------
18
+
19
+ from abc import ABC, abstractmethod
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+
24
+ from .multimodal_encoder.builder import build_vision_tower
25
+ from .multimodal_projector.builder import build_vision_projector
26
+
27
+ from cumo.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
28
+
29
+ from cumo.mm_utils import get_anyres_image_grid_shape
30
+
31
+ class LlavaMetaModel:
32
+
33
+ def __init__(self, config):
34
+ super(LlavaMetaModel, self).__init__(config)
35
+
36
+ if hasattr(config, "mm_vision_tower"):
37
+ self.vision_tower = build_vision_tower(config, delay_load=True)
38
+ self.mm_projector = build_vision_projector(config)
39
+
40
+ if 'unpad' in getattr(config, 'mm_patch_merge_type', ''):
41
+ self.image_newline = nn.Parameter(
42
+ torch.empty(config.hidden_size, dtype=self.dtype)
43
+ )
44
+
45
+ def get_vision_tower(self):
46
+ vision_tower = getattr(self, 'vision_tower', None)
47
+ if type(vision_tower) is list:
48
+ vision_tower = vision_tower[0]
49
+ return vision_tower
50
+
51
+ def initialize_vision_modules(self, model_args, fsdp=None):
52
+ vision_tower = model_args.vision_tower
53
+ mm_vision_select_layer = model_args.mm_vision_select_layer
54
+ mm_vision_select_feature = model_args.mm_vision_select_feature
55
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
56
+ vision_tower_dir = model_args.vision_tower_dir
57
+ mm_patch_merge_type = model_args.mm_patch_merge_type
58
+
59
+ self.config.mm_vision_tower = vision_tower
60
+ self.config.scales = model_args.scales
61
+
62
+ vision_tower = build_vision_tower(model_args)
63
+
64
+ if fsdp is not None and len(fsdp) > 0:
65
+ self.vision_tower = [vision_tower]
66
+ else:
67
+ self.vision_tower = vision_tower
68
+
69
+ self.config.use_mm_proj = True
70
+ self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
71
+ self.config.mm_hidden_size = vision_tower.hidden_size
72
+ self.config.mm_vision_select_layer = mm_vision_select_layer
73
+ self.config.mm_vision_select_feature = mm_vision_select_feature
74
+ self.config.mm_patch_merge_type = mm_patch_merge_type
75
+ self.config.num_experts = model_args.num_experts
76
+ self.config.num_selected = model_args.num_selected
77
+ self.config.num_layers = model_args.num_layers
78
+ self.config.dropout = model_args.dropout
79
+ self.config.mlp_smoe = model_args.mlp_smoe
80
+ self.config.clip_smoe = model_args.clip_smoe
81
+
82
+ self.mm_projector = build_vision_projector(self.config)
83
+
84
+ if 'unpad' in mm_patch_merge_type:
85
+ embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
86
+ self.image_newline = nn.Parameter(
87
+ torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std
88
+ )
89
+
90
+ if pretrain_mm_mlp_adapter is not None:
91
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
92
+ def get_w(weights, keyword):
93
+ return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
94
+
95
+ if self.config.mlp_smoe:
96
+ for i in range(model_args.num_experts):
97
+ self.mm_projector.experts[i].load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
98
+ else:
99
+ self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
100
+
101
+ if vision_tower_dir is not None:
102
+ vision_tower_weights = torch.load(vision_tower_dir, map_location='cpu')
103
+ self.vision_tower.load_state_dict(vision_tower_weights, strict=False)
104
+ if self.config.clip_smoe:
105
+ current_staet_dict = self.vision_tower.state_dict()
106
+ for key, value in current_staet_dict.items():
107
+ if 'experts' in key:
108
+ key_splits = key.split('.')
109
+ new_key = [key_splits[0], key_splits[1], key_splits[2], key_splits[3], 'mlp', key_splits[6], key_splits[7]]
110
+ current_staet_dict[key] = vision_tower_weights['.'.join(new_key)]
111
+ self.vision_tower.load_state_dict(current_staet_dict, strict=True)
112
+
113
+ def unpad_image(tensor, original_size):
114
+ """
115
+ Unpads a PyTorch tensor of a padded and resized image.
116
+
117
+ Args:
118
+ tensor (torch.Tensor): The image tensor, assumed to be in CxHxW format.
119
+ original_size (tuple): The original size of the image (height, width).
120
+
121
+ Returns:
122
+ torch.Tensor: The unpadded image tensor.
123
+ """
124
+ original_width, original_height = original_size
125
+ current_height, current_width = tensor.shape[1:]
126
+
127
+ original_aspect_ratio = original_width / original_height
128
+ current_aspect_ratio = current_width / current_height
129
+
130
+ if original_aspect_ratio > current_aspect_ratio:
131
+ scale_factor = current_width / original_width
132
+ new_height = int(original_height * scale_factor)
133
+ padding = (current_height - new_height) // 2
134
+ unpadded_tensor = tensor[:, padding:current_height - padding, :]
135
+ else:
136
+ scale_factor = current_height / original_height
137
+ new_width = int(original_width * scale_factor)
138
+ padding = (current_width - new_width) // 2
139
+ unpadded_tensor = tensor[:, :, padding:current_width - padding]
140
+
141
+ return unpadded_tensor
142
+
143
+
144
+ class LlavaMetaForCausalLM(ABC):
145
+
146
+ @abstractmethod
147
+ def get_model(self):
148
+ pass
149
+
150
+ def get_vision_tower(self):
151
+ return self.get_model().get_vision_tower()
152
+
153
+ def prepare_inputs_labels_for_multimodal(
154
+ self, input_ids, position_ids, attention_mask, past_key_values, labels,
155
+ images, image_sizes=None
156
+ ):
157
+ clip_balanced_loss = None
158
+ clip_router_z_loss = None
159
+ mlp_balanced_loss = None
160
+ mlp_router_z_loss = None
161
+ vision_tower = self.get_vision_tower()
162
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
163
+ return input_ids, position_ids, attention_mask, past_key_values, None, labels, clip_balanced_loss, clip_router_z_loss, mlp_balanced_loss, mlp_router_z_loss
164
+
165
+ if type(images) is list or images.ndim == 5:
166
+ if type(images) is list:
167
+ images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]
168
+ concat_images = torch.cat([image for image in images], dim=0)
169
+ image_features, clip_balanced_loss, clip_router_z_loss = self.get_model().get_vision_tower()(images)
170
+ image_features, mlp_balanced_loss, mlp_router_z_loss = self.get_model().mm_projector(image_features)
171
+ split_sizes = [image.shape[0] for image in images]
172
+ image_features = torch.split(image_features, split_sizes, dim=0)
173
+ mm_patch_merge_type = getattr(self.config, 'mm_patch_merge_type', 'flat')
174
+ image_aspect_ratio = getattr(self.config, 'image_aspect_ratio', 'square')
175
+ if mm_patch_merge_type == 'flat':
176
+ image_features = [x.flatten(0, 1) for x in image_features]
177
+ elif mm_patch_merge_type.startswith('spatial'):
178
+ new_image_features = []
179
+ for image_idx, image_feature in enumerate(image_features):
180
+ if image_feature.shape[0] > 1:
181
+ base_image_feature = image_feature[0]
182
+ image_feature = image_feature[1:]
183
+ height = width = self.get_vision_tower().num_patches_per_side
184
+ assert height * width == base_image_feature.shape[0]
185
+ if image_aspect_ratio == 'anyres':
186
+ num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, self.get_vision_tower().config.image_size)
187
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
188
+ else:
189
+ raise NotImplementedError
190
+ if 'unpad' in mm_patch_merge_type:
191
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
192
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
193
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
194
+ image_feature = torch.cat((
195
+ image_feature,
196
+ self.model.image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.device)
197
+ ), dim=-1)
198
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
199
+ else:
200
+ image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
201
+ image_feature = image_feature.flatten(0, 3)
202
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
203
+ else:
204
+ image_feature = image_feature[0]
205
+ if 'unpad' in mm_patch_merge_type:
206
+ image_feature = torch.cat((
207
+ image_feature,
208
+ self.model.image_newline[None].to(image_feature.device)
209
+ ), dim=0)
210
+ new_image_features.append(image_feature)
211
+ image_features = new_image_features
212
+ else:
213
+ raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")
214
+ else:
215
+ image_features, clip_balanced_loss, clip_router_z_loss = self.get_model().get_vision_tower()(images)
216
+ if self.config.mlp_smoe:
217
+ image_features, mlp_balanced_loss, mlp_router_z_loss = self.get_model().mm_projector(image_features)
218
+ else:
219
+ image_features = self.get_model().mm_projector(image_features)
220
+ if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
221
+ raise NotImplementedError
222
+ # Let's just add dummy tensors if they do not exist,
223
+ # it is a headache to deal with None all the time.
224
+ # But it is not ideal, and if you have a better idea,
225
+ # please open an issue / submit a PR, thanks.
226
+ _labels = labels
227
+ _position_ids = position_ids
228
+ _attention_mask = attention_mask
229
+ if attention_mask is None:
230
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
231
+ else:
232
+ attention_mask = attention_mask.bool()
233
+ if position_ids is None:
234
+ position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
235
+ if labels is None:
236
+ labels = torch.full_like(input_ids, IGNORE_INDEX)
237
+
238
+ # remove the padding using attention_mask -- FIXME
239
+ _input_ids = input_ids
240
+ input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
241
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
242
+
243
+ new_input_embeds = []
244
+ new_labels = []
245
+ cur_image_idx = 0
246
+ for batch_idx, cur_input_ids in enumerate(input_ids):
247
+ num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
248
+ if num_images == 0:
249
+ cur_image_features = image_features[cur_image_idx]
250
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
251
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
252
+ new_input_embeds.append(cur_input_embeds)
253
+ new_labels.append(labels[batch_idx])
254
+ cur_image_idx += 1
255
+ continue
256
+
257
+ image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
258
+ cur_input_ids_noim = []
259
+ cur_labels = labels[batch_idx]
260
+ cur_labels_noim = []
261
+ for i in range(len(image_token_indices) - 1):
262
+ cur_input_ids_noim.append(cur_input_ids[image_token_indices[i]+1:image_token_indices[i+1]])
263
+ cur_labels_noim.append(cur_labels[image_token_indices[i]+1:image_token_indices[i+1]])
264
+ split_sizes = [x.shape[0] for x in cur_labels_noim]
265
+ cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
266
+ cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
267
+ cur_new_input_embeds = []
268
+ cur_new_labels = []
269
+
270
+ for i in range(num_images + 1):
271
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
272
+ cur_new_labels.append(cur_labels_noim[i])
273
+ if i < num_images:
274
+ cur_image_features = image_features[cur_image_idx]
275
+ cur_image_idx += 1
276
+ cur_new_input_embeds.append(cur_image_features)
277
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
278
+
279
+ cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]
280
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
281
+ cur_new_labels = torch.cat(cur_new_labels)
282
+
283
+ new_input_embeds.append(cur_new_input_embeds)
284
+ new_labels.append(cur_new_labels)
285
+
286
+ # Truncate sequences to max length as image embeddings can make the sequence longer
287
+ tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None)
288
+ if tokenizer_model_max_length is not None:
289
+ new_input_embeds = [x[:tokenizer_model_max_length] for x in new_input_embeds]
290
+ new_labels = [x[:tokenizer_model_max_length] for x in new_labels]
291
+
292
+ # Combine them
293
+ max_len = max(x.shape[0] for x in new_input_embeds)
294
+ batch_size = len(new_input_embeds)
295
+
296
+ new_input_embeds_padded = []
297
+ new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
298
+ attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
299
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
300
+
301
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
302
+ cur_len = cur_new_embed.shape[0]
303
+ if getattr(self.config, 'tokenizer_padding_side', 'right') == "left":
304
+ new_input_embeds_padded.append(torch.cat((
305
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device),
306
+ cur_new_embed
307
+ ), dim=0))
308
+ if cur_len > 0:
309
+ new_labels_padded[i, -cur_len:] = cur_new_labels
310
+ attention_mask[i, -cur_len:] = True
311
+ position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
312
+ else:
313
+ new_input_embeds_padded.append(torch.cat((
314
+ cur_new_embed,
315
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)
316
+ ), dim=0))
317
+ if cur_len > 0:
318
+ new_labels_padded[i, :cur_len] = cur_new_labels
319
+ attention_mask[i, :cur_len] = True
320
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
321
+
322
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
323
+
324
+ if _labels is None:
325
+ new_labels = None
326
+ else:
327
+ new_labels = new_labels_padded
328
+
329
+ if _attention_mask is None:
330
+ attention_mask = None
331
+ else:
332
+ attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
333
+
334
+ if _position_ids is None:
335
+ position_ids = None
336
+
337
+ return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels, clip_balanced_loss, clip_router_z_loss, mlp_balanced_loss, mlp_router_z_loss
338
+
339
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
340
+ if model_args.mm_use_im_patch_token:
341
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
342
+ self.resize_token_embeddings(len(tokenizer))
343
+
344
+ if model_args.mm_use_im_start_end:
345
+ num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
346
+ self.resize_token_embeddings(len(tokenizer))
347
+
348
+ if num_new_tokens > 0:
349
+ input_embeddings = self.get_input_embeddings().weight.data
350
+ output_embeddings = self.get_output_embeddings().weight.data
351
+
352
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
353
+ dim=0, keepdim=True)
354
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
355
+ dim=0, keepdim=True)
356
+
357
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
358
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
359
+
360
+ if model_args.tune_mm_mlp_adapter:
361
+ for p in self.get_input_embeddings().parameters():
362
+ p.requires_grad = True
363
+ for p in self.get_output_embeddings().parameters():
364
+ p.requires_grad = False
365
+
366
+ if model_args.pretrain_mm_mlp_adapter:
367
+ mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location='cpu')
368
+ embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight']
369
+ assert num_new_tokens == 2
370
+ if input_embeddings.shape == embed_tokens_weight.shape:
371
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
372
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
373
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
374
+ else:
375
+ raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
376
+ elif model_args.mm_use_im_patch_token:
377
+ if model_args.tune_mm_mlp_adapter:
378
+ for p in self.get_input_embeddings().parameters():
379
+ p.requires_grad = False
380
+ for p in self.get_output_embeddings().parameters():
381
+ p.requires_grad = False