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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from transformers import AutoConfig, AutoModelForCausalLM, LlamaConfig, LlamaModel, LlamaForCausalLM
|
23 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
24 |
+
|
25 |
+
from .configuration_mplug_owl2 import MPLUGOwl2Config, MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig
|
26 |
+
from .visual_encoder import MplugOwlVisionModel, MplugOwlVisualAbstractorModel
|
27 |
+
from .modeling_llama2 import replace_llama_modality_adaptive
|
28 |
+
IGNORE_INDEX = -100
|
29 |
+
IMAGE_TOKEN_INDEX = -200
|
30 |
+
DEFAULT_IMAGE_TOKEN = "<|image|>"
|
31 |
+
from icecream import ic
|
32 |
+
|
33 |
+
class MPLUGOwl2MetaModel:
|
34 |
+
def __init__(self, config):
|
35 |
+
super(MPLUGOwl2MetaModel, self).__init__(config)
|
36 |
+
self.vision_model = MplugOwlVisionModel(
|
37 |
+
MplugOwlVisionConfig(**config.visual_config["visual_model"])
|
38 |
+
)
|
39 |
+
self.visual_abstractor = MplugOwlVisualAbstractorModel(
|
40 |
+
MplugOwlVisualAbstractorConfig(**config.visual_config["visual_abstractor"]), config.hidden_size
|
41 |
+
)
|
42 |
+
|
43 |
+
def get_vision_tower(self):
|
44 |
+
vision_model = getattr(self, 'vision_model', None)
|
45 |
+
if type(vision_model) is list:
|
46 |
+
vision_model = vision_model[0]
|
47 |
+
return vision_model
|
48 |
+
|
49 |
+
def get_visual_abstractor(self):
|
50 |
+
visual_abstractor = getattr(self, 'visual_abstractor', None)
|
51 |
+
if type(visual_abstractor) is list:
|
52 |
+
visual_abstractor = visual_abstractor[0]
|
53 |
+
return visual_abstractor
|
54 |
+
|
55 |
+
|
56 |
+
class MPLUGOwl2MetaForCausalLM(ABC):
|
57 |
+
@abstractmethod
|
58 |
+
def get_model(self):
|
59 |
+
pass
|
60 |
+
|
61 |
+
def encode_images(self, images):
|
62 |
+
image_features = self.get_model().vision_model(images).last_hidden_state
|
63 |
+
image_features = self.get_model().visual_abstractor(encoder_hidden_states=image_features).last_hidden_state
|
64 |
+
return image_features
|
65 |
+
|
66 |
+
def prepare_inputs_labels_for_multimodal(
|
67 |
+
self, input_ids, attention_mask, past_key_values, labels, images
|
68 |
+
):
|
69 |
+
if images is None or input_ids.shape[1] == 1:
|
70 |
+
if past_key_values is not None and images is not None and input_ids.shape[1] == 1:
|
71 |
+
attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device)
|
72 |
+
multiway_indices = torch.zeros_like(input_ids).long().to(self.device)
|
73 |
+
return input_ids, multiway_indices, attention_mask, past_key_values, None, labels
|
74 |
+
|
75 |
+
if type(images) is list or images.ndim == 5:
|
76 |
+
concat_images = torch.cat([image for image in images], dim=0)
|
77 |
+
image_features = self.encode_images(concat_images)
|
78 |
+
split_sizes = [image.shape[0] for image in images]
|
79 |
+
image_features = torch.split(image_features, split_sizes, dim=0)
|
80 |
+
image_features = [x.flatten(0, 1) for x in image_features]
|
81 |
+
else:
|
82 |
+
image_features = self.encode_images(images)
|
83 |
+
|
84 |
+
new_input_embeds = []
|
85 |
+
new_modality_indicators = []
|
86 |
+
new_labels = [] if labels is not None else None
|
87 |
+
cur_image_idx = 0
|
88 |
+
for batch_idx, cur_input_ids in enumerate(input_ids):
|
89 |
+
if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0:
|
90 |
+
# multimodal LLM, but the current sample is not multimodal
|
91 |
+
# FIXME: this is a hacky fix, for deepspeed zero3 to work
|
92 |
+
half_len = cur_input_ids.shape[0] // 2
|
93 |
+
cur_image_features = image_features[cur_image_idx]
|
94 |
+
cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids[:half_len])
|
95 |
+
cur_input_embeds_2 = self.get_model().embed_tokens(cur_input_ids[half_len:])
|
96 |
+
cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0], cur_input_embeds_2], dim=0)
|
97 |
+
new_input_embeds.append(cur_input_embeds)
|
98 |
+
|
99 |
+
cur_modality_indicators = torch.zeros(len(cur_input_embeds)).long().to(self.device)
|
100 |
+
new_modality_indicators.append(cur_modality_indicators)
|
101 |
+
if labels is not None:
|
102 |
+
new_labels.append(labels[batch_idx])
|
103 |
+
cur_image_idx += 1
|
104 |
+
continue
|
105 |
+
image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
|
106 |
+
cur_new_input_embeds = []
|
107 |
+
cur_modality_indicators = []
|
108 |
+
if labels is not None:
|
109 |
+
cur_labels = labels[batch_idx]
|
110 |
+
cur_new_labels = []
|
111 |
+
assert cur_labels.shape == cur_input_ids.shape
|
112 |
+
while image_token_indices.numel() > 0:
|
113 |
+
cur_image_features = image_features[cur_image_idx]
|
114 |
+
image_token_start = image_token_indices[0]
|
115 |
+
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start]))
|
116 |
+
cur_new_input_embeds.append(cur_image_features)
|
117 |
+
|
118 |
+
# Add modality indicator
|
119 |
+
assert image_token_start == len(cur_input_ids[:image_token_start])
|
120 |
+
cur_modality_indicators.append(torch.zeros(len(cur_input_ids[:image_token_start])).long())
|
121 |
+
cur_modality_indicators.append(torch.ones(len(cur_image_features)).long())
|
122 |
+
|
123 |
+
if labels is not None:
|
124 |
+
cur_new_labels.append(cur_labels[:image_token_start])
|
125 |
+
cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
|
126 |
+
cur_labels = cur_labels[image_token_start+1:]
|
127 |
+
cur_image_idx += 1
|
128 |
+
cur_input_ids = cur_input_ids[image_token_start+1:]
|
129 |
+
image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
|
130 |
+
if cur_input_ids.numel() > 0:
|
131 |
+
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids))
|
132 |
+
cur_modality_indicators.append(torch.zeros(len(cur_input_ids)).long())
|
133 |
+
if labels is not None:
|
134 |
+
cur_new_labels.append(cur_labels)
|
135 |
+
cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds]
|
136 |
+
cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0)
|
137 |
+
new_input_embeds.append(cur_new_input_embeds)
|
138 |
+
|
139 |
+
# Modality
|
140 |
+
cur_modality_indicators = [x.to(device=self.device) for x in cur_modality_indicators]
|
141 |
+
cur_modality_indicators = torch.cat(cur_modality_indicators, dim=0)
|
142 |
+
new_modality_indicators.append(cur_modality_indicators)
|
143 |
+
|
144 |
+
|
145 |
+
if labels is not None:
|
146 |
+
cur_new_labels = torch.cat(cur_new_labels, dim=0)
|
147 |
+
new_labels.append(cur_new_labels)
|
148 |
+
|
149 |
+
if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds):
|
150 |
+
max_len = max(x.shape[0] for x in new_input_embeds)
|
151 |
+
|
152 |
+
# Embedding
|
153 |
+
new_input_embeds_align = []
|
154 |
+
for cur_new_embed in new_input_embeds:
|
155 |
+
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)
|
156 |
+
new_input_embeds_align.append(cur_new_embed)
|
157 |
+
new_input_embeds = torch.stack(new_input_embeds_align, dim=0)
|
158 |
+
|
159 |
+
# Modality
|
160 |
+
new_modality_indicators_align = []
|
161 |
+
for cur_modality_indicator in new_modality_indicators:
|
162 |
+
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)
|
163 |
+
new_modality_indicators_align.append(cur_new_embed)
|
164 |
+
new_modality_indicators = torch.stack(new_modality_indicators_align, dim=0)
|
165 |
+
|
166 |
+
# Label
|
167 |
+
if labels is not None:
|
168 |
+
new_labels_align = []
|
169 |
+
_new_labels = new_labels
|
170 |
+
for cur_new_label in new_labels:
|
171 |
+
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)
|
172 |
+
new_labels_align.append(cur_new_label)
|
173 |
+
new_labels = torch.stack(new_labels_align, dim=0)
|
174 |
+
|
175 |
+
# Attention Mask
|
176 |
+
if attention_mask is not None:
|
177 |
+
new_attention_mask = []
|
178 |
+
for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(attention_mask, _new_labels, new_labels):
|
179 |
+
new_attn_mask_pad_left = torch.full((cur_new_labels.shape[0] - labels.shape[1],), True, dtype=attention_mask.dtype, device=attention_mask.device)
|
180 |
+
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)
|
181 |
+
cur_new_attention_mask = torch.cat((new_attn_mask_pad_left, cur_attention_mask, new_attn_mask_pad_right), dim=0)
|
182 |
+
new_attention_mask.append(cur_new_attention_mask)
|
183 |
+
attention_mask = torch.stack(new_attention_mask, dim=0)
|
184 |
+
assert attention_mask.shape == new_labels.shape
|
185 |
+
else:
|
186 |
+
new_input_embeds = torch.stack(new_input_embeds, dim=0)
|
187 |
+
new_modality_indicators = torch.stack(new_modality_indicators, dim=0)
|
188 |
+
if labels is not None:
|
189 |
+
new_labels = torch.stack(new_labels, dim=0)
|
190 |
+
|
191 |
+
if attention_mask is not None:
|
192 |
+
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)
|
193 |
+
attention_mask = torch.cat((new_attn_mask_pad_left, attention_mask), dim=1)
|
194 |
+
assert attention_mask.shape == new_input_embeds.shape[:2]
|
195 |
+
return None, new_modality_indicators, attention_mask, past_key_values, new_input_embeds, new_labels
|
196 |
+
|
197 |
+
|
198 |
+
|
199 |
+
class MPLUGOwl2LlamaModel(MPLUGOwl2MetaModel, LlamaModel):
|
200 |
+
config_class = MPLUGOwl2Config
|
201 |
+
|
202 |
+
def __init__(self, config: MPLUGOwl2Config):
|
203 |
+
super(MPLUGOwl2LlamaModel, self).__init__(config)
|
204 |
+
|
205 |
+
|
206 |
+
class MPLUGOwl2LlamaForCausalLM(LlamaForCausalLM, MPLUGOwl2MetaForCausalLM):
|
207 |
+
config_class = MPLUGOwl2Config
|
208 |
+
|
209 |
+
def __init__(self, config):
|
210 |
+
super(LlamaForCausalLM, self).__init__(config)
|
211 |
+
self.model = MPLUGOwl2LlamaModel(config)
|
212 |
+
|
213 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
214 |
+
|
215 |
+
# Initialize weights and apply final processing
|
216 |
+
self.post_init()
|
217 |
+
|
218 |
+
def get_model(self):
|
219 |
+
return self.model
|
220 |
+
|
221 |
+
def forward(
|
222 |
+
self,
|
223 |
+
input_ids: torch.LongTensor = None,
|
224 |
+
# modality_indicators: torch.LongTensor = None,
|
225 |
+
attention_mask: Optional[torch.Tensor] = None,
|
226 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
227 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
228 |
+
labels: Optional[torch.LongTensor] = None,
|
229 |
+
use_cache: Optional[bool] = None,
|
230 |
+
output_attentions: Optional[bool] = None,
|
231 |
+
output_hidden_states: Optional[bool] = None,
|
232 |
+
images: Optional[torch.FloatTensor] = None,
|
233 |
+
return_dict: Optional[bool] = None,
|
234 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
235 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
236 |
+
output_hidden_states = (
|
237 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
238 |
+
)
|
239 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
240 |
+
input_ids, modality_indicators, attention_mask, past_key_values, inputs_embeds, labels = \
|
241 |
+
self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images)
|
242 |
+
|
243 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
244 |
+
outputs = self.model(
|
245 |
+
input_ids=input_ids,
|
246 |
+
modality_indicators=modality_indicators,
|
247 |
+
attention_mask=attention_mask,
|
248 |
+
past_key_values=past_key_values,
|
249 |
+
inputs_embeds=inputs_embeds,
|
250 |
+
use_cache=use_cache,
|
251 |
+
output_attentions=output_attentions,
|
252 |
+
output_hidden_states=output_hidden_states,
|
253 |
+
return_dict=return_dict
|
254 |
+
)
|
255 |
+
|
256 |
+
hidden_states = outputs[0]
|
257 |
+
logits = self.lm_head(hidden_states)
|
258 |
+
|
259 |
+
loss = None
|
260 |
+
if labels is not None:
|
261 |
+
# Shift so that tokens < n predict n
|
262 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
263 |
+
shift_labels = labels[..., 1:].contiguous()
|
264 |
+
# Flatten the tokens
|
265 |
+
loss_fct = CrossEntropyLoss()
|
266 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
267 |
+
shift_labels = shift_labels.view(-1)
|
268 |
+
# Enable model/pipeline parallelism
|
269 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
270 |
+
loss = loss_fct(shift_logits, shift_labels)
|
271 |
+
|
272 |
+
if not return_dict:
|
273 |
+
output = (logits,) + outputs[1:]
|
274 |
+
return (loss,) + output if loss is not None else output
|
275 |
+
|
276 |
+
return CausalLMOutputWithPast(
|
277 |
+
loss=loss,
|
278 |
+
logits=logits,
|
279 |
+
past_key_values=outputs.past_key_values,
|
280 |
+
hidden_states=outputs.hidden_states,
|
281 |
+
attentions=outputs.attentions,
|
282 |
+
)
|
283 |
+
|
284 |
+
def prepare_inputs_for_generation(
|
285 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
286 |
+
):
|
287 |
+
if past_key_values:
|
288 |
+
input_ids = input_ids[:, -1:]
|
289 |
+
|
290 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
291 |
+
if inputs_embeds is not None and past_key_values is None:
|
292 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
293 |
+
else:
|
294 |
+
model_inputs = {"input_ids": input_ids}
|
295 |
+
|
296 |
+
model_inputs.update(
|
297 |
+
{
|
298 |
+
"past_key_values": past_key_values,
|
299 |
+
"use_cache": kwargs.get("use_cache"),
|
300 |
+
"attention_mask": attention_mask,
|
301 |
+
"images": kwargs.get("images", None),
|
302 |
+
}
|
303 |
+
)
|
304 |
+
return model_inputs
|
305 |
+
|
306 |
+
AutoConfig.register("mplug_owl2", MPLUGOwl2Config)
|
307 |
+
AutoModelForCausalLM.register(MPLUGOwl2Config, MPLUGOwl2LlamaForCausalLM)
|
308 |
+
|
309 |
+
replace_llama_modality_adaptive()
|
310 |
+
|
311 |
+
if __name__ == "__main__":
|
312 |
+
config = MPLUGOwl2Config.from_pretrained('q-future/one-align')
|
313 |
+
from icecream import ic
|
314 |
+
# config = MPLUGOwl2Config()
|
315 |
+
model = AutoModelForCausalLM(config)
|
316 |
+
|
317 |
+
images = torch.randn(2, 3, 448, 448)
|
318 |
+
input_ids = torch.cat([
|
319 |
+
torch.ones(8).long(), torch.tensor([-1]*1).long(), torch.ones(8).long(), torch.tensor([-1]*1).long(), torch.ones(8).long()
|
320 |
+
], dim=0).unsqueeze(0)
|
321 |
+
labels = input_ids.clone()
|
322 |
+
labels[labels < 0] = -100
|
323 |
+
|
324 |
+
# image_feature = model.encode_images(images)
|
325 |
+
# ic(image_feature.shape)
|
326 |
+
|
327 |
+
output = model(images=images, input_ids=input_ids, labels=labels)
|
328 |
+
ic(output.loss)
|
329 |
+
ic(output.logits.shape)
|
330 |
+
|
331 |
+
model.save_pretrained('/cpfs01/shared/public/test/tmp_owl')
|