teowu commited on
Commit
fe22a6f
1 Parent(s): 292d9a2

Upload modeling_mplug_owl2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_mplug_owl2.py +410 -0
modeling_mplug_owl2.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu & Qinghao Ye (Modified from LLaVA)
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
+ from abc import ABC, abstractmethod
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ from torch.nn import CrossEntropyLoss
21
+
22
+ import copy
23
+ import os
24
+ import sys
25
+ from transformers import TextStreamer
26
+
27
+ dir_path = os.path.dirname(os.path.realpath(__file__))
28
+ sys.path.insert(0, dir_path)
29
+
30
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, CLIPImageProcessor, LlamaConfig, LlamaModel, LlamaForCausalLM
31
+ from transformers.modeling_outputs import CausalLMOutputWithPast
32
+
33
+ from .configuration_mplug_owl2 import MPLUGOwl2Config, MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig
34
+ from .visual_encoder import MplugOwlVisionModel, MplugOwlVisualAbstractorModel
35
+ from .modeling_llama2 import replace_llama_modality_adaptive
36
+ IGNORE_INDEX = -100
37
+ IMAGE_TOKEN_INDEX = -200
38
+ DEFAULT_IMAGE_TOKEN = "<|image|>"
39
+ from icecream import ic
40
+
41
+ def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
42
+ prompt_chunks = [tokenizer(chunk).input_ids if len(chunk) > 0 else [] for chunk in prompt.split(DEFAULT_IMAGE_TOKEN)]
43
+
44
+ def insert_separator(X, sep):
45
+ return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1]
46
+
47
+ input_ids = []
48
+ offset = 0
49
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
50
+ offset = 1
51
+ input_ids.append(prompt_chunks[0][0])
52
+
53
+ for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
54
+ input_ids.extend(x[offset:])
55
+
56
+ if return_tensors is not None:
57
+ if return_tensors == 'pt':
58
+ return torch.tensor(input_ids, dtype=torch.long)
59
+ raise ValueError(f'Unsupported tensor type: {return_tensors}')
60
+ return input_ids
61
+
62
+ def expand2square(pil_img, background_color):
63
+ from PIL import Image
64
+ width, height = pil_img.size
65
+ if width == height:
66
+ return pil_img
67
+ elif width > height:
68
+ result = Image.new(pil_img.mode, (width, width), background_color)
69
+ result.paste(pil_img, (0, (width - height) // 2))
70
+ return result
71
+ else:
72
+ result = Image.new(pil_img.mode, (height, height), background_color)
73
+ result.paste(pil_img, ((height - width) // 2, 0))
74
+ return result
75
+
76
+ class MPLUGOwl2MetaModel:
77
+ def __init__(self, config):
78
+ super(MPLUGOwl2MetaModel, self).__init__(config)
79
+ self.vision_model = MplugOwlVisionModel(
80
+ MplugOwlVisionConfig(**config.visual_config["visual_model"])
81
+ )
82
+ self.visual_abstractor = MplugOwlVisualAbstractorModel(
83
+ MplugOwlVisualAbstractorConfig(**config.visual_config["visual_abstractor"]), config.hidden_size
84
+ )
85
+
86
+ def get_vision_tower(self):
87
+ vision_model = getattr(self, 'vision_model', None)
88
+ if type(vision_model) is list:
89
+ vision_model = vision_model[0]
90
+ return vision_model
91
+
92
+ def get_visual_abstractor(self):
93
+ visual_abstractor = getattr(self, 'visual_abstractor', None)
94
+ if type(visual_abstractor) is list:
95
+ visual_abstractor = visual_abstractor[0]
96
+ return visual_abstractor
97
+
98
+
99
+ class MPLUGOwl2MetaForCausalLM(ABC):
100
+ @abstractmethod
101
+ def get_model(self):
102
+ pass
103
+
104
+ def encode_images(self, images):
105
+ image_features = self.get_model().vision_model(images).last_hidden_state
106
+ image_features = self.get_model().visual_abstractor(encoder_hidden_states=image_features).last_hidden_state
107
+ return image_features
108
+
109
+ def prepare_inputs_labels_for_multimodal(
110
+ self, input_ids, attention_mask, past_key_values, labels, images
111
+ ):
112
+ if images is None or input_ids.shape[1] == 1:
113
+ if past_key_values is not None and images is not None and input_ids.shape[1] == 1:
114
+ attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device)
115
+ multiway_indices = torch.zeros_like(input_ids).long().to(self.device)
116
+ return input_ids, multiway_indices, attention_mask, past_key_values, None, labels
117
+
118
+ if type(images) is list or images.ndim == 5:
119
+ concat_images = torch.cat([image for image in images], dim=0)
120
+ image_features = self.encode_images(concat_images)
121
+ split_sizes = [image.shape[0] for image in images]
122
+ image_features = torch.split(image_features, split_sizes, dim=0)
123
+ image_features = [x.flatten(0, 1) for x in image_features]
124
+ else:
125
+ image_features = self.encode_images(images)
126
+
127
+ new_input_embeds = []
128
+ new_modality_indicators = []
129
+ new_labels = [] if labels is not None else None
130
+ cur_image_idx = 0
131
+ for batch_idx, cur_input_ids in enumerate(input_ids):
132
+ if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0:
133
+ # multimodal LLM, but the current sample is not multimodal
134
+ # FIXME: this is a hacky fix, for deepspeed zero3 to work
135
+ half_len = cur_input_ids.shape[0] // 2
136
+ cur_image_features = image_features[cur_image_idx]
137
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids[:half_len])
138
+ cur_input_embeds_2 = self.get_model().embed_tokens(cur_input_ids[half_len:])
139
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0], cur_input_embeds_2], dim=0)
140
+ new_input_embeds.append(cur_input_embeds)
141
+
142
+ cur_modality_indicators = torch.zeros(len(cur_input_embeds)).long().to(self.device)
143
+ new_modality_indicators.append(cur_modality_indicators)
144
+ if labels is not None:
145
+ new_labels.append(labels[batch_idx])
146
+ cur_image_idx += 1
147
+ continue
148
+ image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
149
+ cur_new_input_embeds = []
150
+ cur_modality_indicators = []
151
+ if labels is not None:
152
+ cur_labels = labels[batch_idx]
153
+ cur_new_labels = []
154
+ assert cur_labels.shape == cur_input_ids.shape
155
+ while image_token_indices.numel() > 0:
156
+ cur_image_features = image_features[cur_image_idx]
157
+ image_token_start = image_token_indices[0]
158
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start]))
159
+ cur_new_input_embeds.append(cur_image_features)
160
+
161
+ # Add modality indicator
162
+ assert image_token_start == len(cur_input_ids[:image_token_start])
163
+ cur_modality_indicators.append(torch.zeros(len(cur_input_ids[:image_token_start])).long())
164
+ cur_modality_indicators.append(torch.ones(len(cur_image_features)).long())
165
+
166
+ if labels is not None:
167
+ cur_new_labels.append(cur_labels[:image_token_start])
168
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
169
+ cur_labels = cur_labels[image_token_start+1:]
170
+ cur_image_idx += 1
171
+ cur_input_ids = cur_input_ids[image_token_start+1:]
172
+ image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
173
+ if cur_input_ids.numel() > 0:
174
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids))
175
+ cur_modality_indicators.append(torch.zeros(len(cur_input_ids)).long())
176
+ if labels is not None:
177
+ cur_new_labels.append(cur_labels)
178
+ cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds]
179
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0)
180
+ new_input_embeds.append(cur_new_input_embeds)
181
+
182
+ # Modality
183
+ cur_modality_indicators = [x.to(device=self.device) for x in cur_modality_indicators]
184
+ cur_modality_indicators = torch.cat(cur_modality_indicators, dim=0)
185
+ new_modality_indicators.append(cur_modality_indicators)
186
+
187
+
188
+ if labels is not None:
189
+ cur_new_labels = torch.cat(cur_new_labels, dim=0)
190
+ new_labels.append(cur_new_labels)
191
+
192
+ if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds):
193
+ max_len = max(x.shape[0] for x in new_input_embeds)
194
+
195
+ # Embedding
196
+ new_input_embeds_align = []
197
+ for cur_new_embed in new_input_embeds:
198
+ cur_new_embed = torch.cat((cur_new_embed, torch.zeros((max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0)
199
+ new_input_embeds_align.append(cur_new_embed)
200
+ new_input_embeds = torch.stack(new_input_embeds_align, dim=0)
201
+
202
+ # Modality
203
+ new_modality_indicators_align = []
204
+ for cur_modality_indicator in new_modality_indicators:
205
+ cur_new_embed = torch.cat((cur_modality_indicator, torch.zeros(max_len - cur_modality_indicator.shape[0], dtype=cur_modality_indicator.dtype, device=cur_modality_indicator.device)), dim=0)
206
+ new_modality_indicators_align.append(cur_new_embed)
207
+ new_modality_indicators = torch.stack(new_modality_indicators_align, dim=0)
208
+
209
+ # Label
210
+ if labels is not None:
211
+ new_labels_align = []
212
+ _new_labels = new_labels
213
+ for cur_new_label in new_labels:
214
+ cur_new_label = torch.cat((cur_new_label, torch.full((max_len - cur_new_label.shape[0],), IGNORE_INDEX, dtype=cur_new_label.dtype, device=cur_new_label.device)), dim=0)
215
+ new_labels_align.append(cur_new_label)
216
+ new_labels = torch.stack(new_labels_align, dim=0)
217
+
218
+ # Attention Mask
219
+ if attention_mask is not None:
220
+ new_attention_mask = []
221
+ for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(attention_mask, _new_labels, new_labels):
222
+ new_attn_mask_pad_left = torch.full((cur_new_labels.shape[0] - labels.shape[1],), True, dtype=attention_mask.dtype, device=attention_mask.device)
223
+ new_attn_mask_pad_right = torch.full((cur_new_labels_align.shape[0] - cur_new_labels.shape[0],), False, dtype=attention_mask.dtype, device=attention_mask.device)
224
+ cur_new_attention_mask = torch.cat((new_attn_mask_pad_left, cur_attention_mask, new_attn_mask_pad_right), dim=0)
225
+ new_attention_mask.append(cur_new_attention_mask)
226
+ attention_mask = torch.stack(new_attention_mask, dim=0)
227
+ assert attention_mask.shape == new_labels.shape
228
+ else:
229
+ new_input_embeds = torch.stack(new_input_embeds, dim=0)
230
+ new_modality_indicators = torch.stack(new_modality_indicators, dim=0)
231
+ if labels is not None:
232
+ new_labels = torch.stack(new_labels, dim=0)
233
+
234
+ if attention_mask is not None:
235
+ new_attn_mask_pad_left = torch.full((attention_mask.shape[0], new_input_embeds.shape[1] - input_ids.shape[1]), True, dtype=attention_mask.dtype, device=attention_mask.device)
236
+ attention_mask = torch.cat((new_attn_mask_pad_left, attention_mask), dim=1)
237
+ assert attention_mask.shape == new_input_embeds.shape[:2]
238
+ return None, new_modality_indicators, attention_mask, past_key_values, new_input_embeds, new_labels
239
+
240
+
241
+
242
+ class MPLUGOwl2LlamaModel(MPLUGOwl2MetaModel, LlamaModel):
243
+ config_class = MPLUGOwl2Config
244
+
245
+ def __init__(self, config: MPLUGOwl2Config):
246
+ super(MPLUGOwl2LlamaModel, self).__init__(config)
247
+
248
+
249
+ class MPLUGOwl2LlamaForCausalLM(LlamaForCausalLM, MPLUGOwl2MetaForCausalLM):
250
+ config_class = MPLUGOwl2Config
251
+
252
+ def __init__(self, config):
253
+ super(LlamaForCausalLM, self).__init__(config)
254
+ self.model = MPLUGOwl2LlamaModel(config)
255
+
256
+ self.tokenizer = AutoTokenizer.from_pretrained("q-future/co-instruct-preview")
257
+ self.image_processor = CLIPImageProcessor.from_pretrained("q-future/co-instruct-preview")
258
+ self.streamer = TextStreamer(self.tokenizer, skip_prompt=True, skip_special_tokens=True)
259
+
260
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
261
+ self.preferential_ids_ = [id_[1] for id_ in self.tokenizer(["excellent","good","fair","poor","bad"])["input_ids"]]
262
+
263
+ # Initialize weights and apply final processing
264
+ self.post_init()
265
+
266
+
267
+ def get_model(self):
268
+ return self.model
269
+
270
+ def chat(self, prompt: str, images, **generate_kwargs):
271
+ input_ids = tokenizer_image_token(prompt, self.tokenizer, -200, return_tensors='pt').unsqueeze(0).to(self.device)
272
+ images = [expand2square(img, tuple(int(x*255) for x in self.image_processor.image_mean)) for img in images]
273
+ image_tensor = self.image_processor.preprocess(images, return_tensors="pt")["pixel_values"].half().to(self.device)
274
+
275
+ return self.generate(input_ids, images=image_tensor, streamer=self.streamer, **generate_kwargs)
276
+ def score(self, images,
277
+ task_: str = "quality",
278
+ input_: str = "image",
279
+ ):
280
+ if not hasattr(self, "weight_tensor"):
281
+ self.weight_tensor = torch.Tensor([5.,4.,3.,2.,1.]).half().to(self.device)
282
+ prompt = "USER: How would you rate the {} of this {}?\n<|image|>\nASSISTANT: The {} of the {} is".format(task_, input_, input_, task_)
283
+ if input_ == "image":
284
+ images = [expand2square(img, tuple(int(x*255) for x in self.image_processor.image_mean)) for img in images]
285
+ input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device)
286
+ with torch.inference_mode():
287
+ image_tensor = self.image_processor.preprocess(images, return_tensors="pt")["pixel_values"].half().to(self.device)
288
+ output_logits = self(input_ids.repeat(image_tensor.shape[0], 1),
289
+ images=image_tensor)["logits"][:,-1, self.preferential_ids_]
290
+ return torch.softmax(output_logits, -1) @ self.weight_tensor
291
+ else:
292
+ video = [[expand2square(frame, tuple(int(x*255) for x in self.image_processor.image_mean)) for frame in vid] for vid in images]
293
+ input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device)
294
+ with torch.inference_mode():
295
+ video_tensors = [self.image_processor.preprocess(vid, return_tensors="pt")["pixel_values"].half().to(self.model.device) for vid in video]
296
+ output_logits = self(input_ids.repeat(len(video_tensors), 1),
297
+ images=video_tensors)["logits"][:,-1, self.preferential_ids_]
298
+ return torch.softmax(output_logits, -1) @ self.weight_tensor
299
+
300
+ def forward(
301
+ self,
302
+ input_ids: torch.LongTensor = None,
303
+ # modality_indicators: torch.LongTensor = None,
304
+ attention_mask: Optional[torch.Tensor] = None,
305
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
306
+ inputs_embeds: Optional[torch.FloatTensor] = None,
307
+ labels: Optional[torch.LongTensor] = None,
308
+ use_cache: Optional[bool] = None,
309
+ output_attentions: Optional[bool] = None,
310
+ output_hidden_states: Optional[bool] = None,
311
+ images: Optional[torch.FloatTensor] = None,
312
+ return_dict: Optional[bool] = None,
313
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
314
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
315
+ output_hidden_states = (
316
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
317
+ )
318
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
319
+ input_ids, modality_indicators, attention_mask, past_key_values, inputs_embeds, labels = \
320
+ self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images)
321
+
322
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
323
+ outputs = self.model(
324
+ input_ids=input_ids,
325
+ modality_indicators=modality_indicators,
326
+ attention_mask=attention_mask,
327
+ past_key_values=past_key_values,
328
+ inputs_embeds=inputs_embeds,
329
+ use_cache=use_cache,
330
+ output_attentions=output_attentions,
331
+ output_hidden_states=output_hidden_states,
332
+ return_dict=return_dict
333
+ )
334
+
335
+ hidden_states = outputs[0]
336
+ logits = self.lm_head(hidden_states)
337
+
338
+ loss = None
339
+ if labels is not None:
340
+ # Shift so that tokens < n predict n
341
+ shift_logits = logits[..., :-1, :].contiguous()
342
+ shift_labels = labels[..., 1:].contiguous()
343
+ # Flatten the tokens
344
+ loss_fct = CrossEntropyLoss()
345
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
346
+ shift_labels = shift_labels.view(-1)
347
+ # Enable model/pipeline parallelism
348
+ shift_labels = shift_labels.to(shift_logits.device)
349
+ loss = loss_fct(shift_logits, shift_labels)
350
+
351
+ if not return_dict:
352
+ output = (logits,) + outputs[1:]
353
+ return (loss,) + output if loss is not None else output
354
+
355
+ return CausalLMOutputWithPast(
356
+ loss=loss,
357
+ logits=logits,
358
+ past_key_values=outputs.past_key_values,
359
+ hidden_states=outputs.hidden_states,
360
+ attentions=outputs.attentions,
361
+ )
362
+
363
+ def prepare_inputs_for_generation(
364
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
365
+ ):
366
+ if past_key_values:
367
+ input_ids = input_ids[:, -1:]
368
+
369
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
370
+ if inputs_embeds is not None and past_key_values is None:
371
+ model_inputs = {"inputs_embeds": inputs_embeds}
372
+ else:
373
+ model_inputs = {"input_ids": input_ids}
374
+
375
+ model_inputs.update(
376
+ {
377
+ "past_key_values": past_key_values,
378
+ "use_cache": kwargs.get("use_cache"),
379
+ "attention_mask": attention_mask,
380
+ "images": kwargs.get("images", None),
381
+ }
382
+ )
383
+ return model_inputs
384
+
385
+ AutoConfig.register("mplug_owl2", MPLUGOwl2Config)
386
+ AutoModelForCausalLM.register(MPLUGOwl2Config, MPLUGOwl2LlamaForCausalLM)
387
+
388
+ replace_llama_modality_adaptive()
389
+
390
+ if __name__ == "__main__":
391
+ config = MPLUGOwl2Config.from_pretrained('q-future/one-align')
392
+ from icecream import ic
393
+ # config = MPLUGOwl2Config()
394
+ model = AutoModelForCausalLM(config)
395
+
396
+ images = torch.randn(2, 3, 448, 448)
397
+ input_ids = torch.cat([
398
+ torch.ones(8).long(), torch.tensor([-1]*1).long(), torch.ones(8).long(), torch.tensor([-1]*1).long(), torch.ones(8).long()
399
+ ], dim=0).unsqueeze(0)
400
+ labels = input_ids.clone()
401
+ labels[labels < 0] = -100
402
+
403
+ # image_feature = model.encode_images(images)
404
+ # ic(image_feature.shape)
405
+
406
+ output = model(images=images, input_ids=input_ids, labels=labels)
407
+ ic(output.loss)
408
+ ic(output.logits.shape)
409
+
410
+ model.save_pretrained('/cpfs01/shared/public/test/tmp_owl')