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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 16 |
+
from abc import ABC, abstractmethod
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
|
| 21 |
+
# from .multimodal_encoder.builder import build_vision_tower
|
| 22 |
+
# from .multimodal_projector.builder import build_vision_projector
|
| 23 |
+
|
| 24 |
+
# from .builders import build_vision_tower, build_vision_projector
|
| 25 |
+
# from .constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 26 |
+
import pdb
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
#############################################################################
|
| 30 |
+
# builders
|
| 31 |
+
#############################################################################
|
| 32 |
+
|
| 33 |
+
###################################################################
|
| 34 |
+
|
| 35 |
+
import torch
|
| 36 |
+
import torch.nn as nn
|
| 37 |
+
import re
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class IdentityMap(nn.Module):
|
| 41 |
+
def __init__(self):
|
| 42 |
+
super().__init__()
|
| 43 |
+
|
| 44 |
+
def forward(self, x, *args, **kwargs):
|
| 45 |
+
return x
|
| 46 |
+
|
| 47 |
+
@property
|
| 48 |
+
def config(self):
|
| 49 |
+
return {"mm_projector_type": 'identity'}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class SimpleResBlock(nn.Module):
|
| 53 |
+
def __init__(self, channels):
|
| 54 |
+
super().__init__()
|
| 55 |
+
self.pre_norm = nn.LayerNorm(channels)
|
| 56 |
+
|
| 57 |
+
self.proj = nn.Sequential(
|
| 58 |
+
nn.Linear(channels, channels),
|
| 59 |
+
nn.GELU(),
|
| 60 |
+
nn.Linear(channels, channels)
|
| 61 |
+
)
|
| 62 |
+
def forward(self, x):
|
| 63 |
+
x = self.pre_norm(x)
|
| 64 |
+
return x + self.proj(x)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def build_vision_projector(config, delay_load=False, **kwargs):
|
| 68 |
+
projector_type = getattr(config, 'mm_projector_type', 'linear')
|
| 69 |
+
|
| 70 |
+
if projector_type == 'linear':
|
| 71 |
+
return nn.Linear(config.mm_hidden_size, config.hidden_size)
|
| 72 |
+
|
| 73 |
+
mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
|
| 74 |
+
if mlp_gelu_match:
|
| 75 |
+
mlp_depth = int(mlp_gelu_match.group(1))
|
| 76 |
+
modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
|
| 77 |
+
for _ in range(1, mlp_depth):
|
| 78 |
+
modules.append(nn.GELU())
|
| 79 |
+
modules.append(nn.Linear(config.hidden_size, config.hidden_size))
|
| 80 |
+
return nn.Sequential(*modules)
|
| 81 |
+
|
| 82 |
+
if projector_type == 'identity':
|
| 83 |
+
return IdentityMap()
|
| 84 |
+
|
| 85 |
+
raise ValueError(f'Unknown projector type: {projector_type}')
|
| 86 |
+
###################################################################
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
###################################################################
|
| 91 |
+
|
| 92 |
+
import os
|
| 93 |
+
from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
|
| 94 |
+
from transformers import AutoModel
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class CLIPVisionTower(nn.Module):
|
| 98 |
+
def __init__(self, vision_tower, args, delay_load=False):
|
| 99 |
+
super().__init__()
|
| 100 |
+
|
| 101 |
+
self.is_loaded = False
|
| 102 |
+
|
| 103 |
+
self.vision_tower_name = vision_tower
|
| 104 |
+
self.select_layer = args.mm_vision_select_layer
|
| 105 |
+
self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
|
| 106 |
+
|
| 107 |
+
if not delay_load:
|
| 108 |
+
self.load_model()
|
| 109 |
+
else:
|
| 110 |
+
self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
|
| 111 |
+
|
| 112 |
+
def load_model(self):
|
| 113 |
+
print(f'loading vision model from {self.vision_tower_name}')
|
| 114 |
+
self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
|
| 115 |
+
if 'clip' in self.vision_tower_name.lower():
|
| 116 |
+
self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
|
| 117 |
+
|
| 118 |
+
elif 'internvit' in self.vision_tower_name.lower():
|
| 119 |
+
self.vision_tower = AutoModel.from_pretrained(self.vision_tower_name, trust_remote_code=True)
|
| 120 |
+
else:
|
| 121 |
+
raise ValueError(f'Please implement the loading of vision encoder here')
|
| 122 |
+
|
| 123 |
+
self.vision_tower.requires_grad_(False)
|
| 124 |
+
|
| 125 |
+
self.is_loaded = True
|
| 126 |
+
|
| 127 |
+
def feature_select(self, image_forward_outs):
|
| 128 |
+
image_features = image_forward_outs.hidden_states[self.select_layer]
|
| 129 |
+
if self.select_feature == 'patch':
|
| 130 |
+
image_features = image_features[:, 1:]
|
| 131 |
+
elif self.select_feature == 'cls_patch':
|
| 132 |
+
image_features = image_features
|
| 133 |
+
else:
|
| 134 |
+
raise ValueError(f'Unexpected select feature: {self.select_feature}')
|
| 135 |
+
return image_features
|
| 136 |
+
|
| 137 |
+
@torch.no_grad()
|
| 138 |
+
def forward(self, images):
|
| 139 |
+
if type(images) is list:
|
| 140 |
+
image_features = []
|
| 141 |
+
for image in images:
|
| 142 |
+
image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
|
| 143 |
+
image_feature = self.feature_select(image_forward_out).to(image.dtype)
|
| 144 |
+
image_features.append(image_feature)
|
| 145 |
+
else:
|
| 146 |
+
image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
|
| 147 |
+
image_features = self.feature_select(image_forward_outs).to(images.dtype)
|
| 148 |
+
|
| 149 |
+
return image_features
|
| 150 |
+
|
| 151 |
+
@property
|
| 152 |
+
def dummy_feature(self):
|
| 153 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
| 154 |
+
|
| 155 |
+
@property
|
| 156 |
+
def dtype(self):
|
| 157 |
+
return self.vision_tower.dtype
|
| 158 |
+
|
| 159 |
+
@property
|
| 160 |
+
def device(self):
|
| 161 |
+
return self.vision_tower.device
|
| 162 |
+
|
| 163 |
+
@property
|
| 164 |
+
def config(self):
|
| 165 |
+
if self.is_loaded:
|
| 166 |
+
return self.vision_tower.config
|
| 167 |
+
else:
|
| 168 |
+
return self.cfg_only
|
| 169 |
+
|
| 170 |
+
@property
|
| 171 |
+
def hidden_size(self):
|
| 172 |
+
return self.config.hidden_size
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def num_patches(self):
|
| 176 |
+
return (self.config.image_size // self.config.patch_size) ** 2
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def build_vision_tower(vision_tower_cfg, **kwargs):
|
| 181 |
+
vision_tower = getattr(vision_tower_cfg, 'mm_vision_tower', getattr(vision_tower_cfg, 'vision_tower', None))
|
| 182 |
+
is_absolute_path_exists = os.path.exists(vision_tower)
|
| 183 |
+
if is_absolute_path_exists or vision_tower.startswith("openai") or vision_tower.startswith("laion"):
|
| 184 |
+
return CLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
|
| 185 |
+
|
| 186 |
+
raise ValueError(f'Unknown vision tower: {vision_tower}')
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
#############################################################################
|
| 190 |
+
# builders
|
| 191 |
+
#############################################################################
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
#############################################################################
|
| 196 |
+
# constants
|
| 197 |
+
#############################################################################
|
| 198 |
+
|
| 199 |
+
CONTROLLER_HEART_BEAT_EXPIRATION = 30
|
| 200 |
+
WORKER_HEART_BEAT_INTERVAL = 15
|
| 201 |
+
|
| 202 |
+
LOGDIR = "."
|
| 203 |
+
|
| 204 |
+
# Model Constants
|
| 205 |
+
IGNORE_INDEX = -100
|
| 206 |
+
IMAGE_TOKEN_INDEX = -200
|
| 207 |
+
DEFAULT_IMAGE_TOKEN = "<image>"
|
| 208 |
+
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
| 209 |
+
DEFAULT_IM_START_TOKEN = "<im_start>"
|
| 210 |
+
DEFAULT_IM_END_TOKEN = "<im_end>"
|
| 211 |
+
IMAGE_PLACEHOLDER = "<image-placeholder>"
|
| 212 |
+
|
| 213 |
+
#############################################################################
|
| 214 |
+
# constants
|
| 215 |
+
#############################################################################
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class LlavaMetaModel:
|
| 219 |
+
|
| 220 |
+
def __init__(self, config):
|
| 221 |
+
super(LlavaMetaModel, self).__init__(config)
|
| 222 |
+
|
| 223 |
+
if hasattr(config, "mm_vision_tower"):
|
| 224 |
+
self.vision_tower = build_vision_tower(config, delay_load=True)
|
| 225 |
+
self.mm_projector = build_vision_projector(config)
|
| 226 |
+
|
| 227 |
+
def get_vision_tower(self):
|
| 228 |
+
vision_tower = getattr(self, 'vision_tower', None)
|
| 229 |
+
if type(vision_tower) is list:
|
| 230 |
+
vision_tower = vision_tower[0]
|
| 231 |
+
return vision_tower
|
| 232 |
+
|
| 233 |
+
def initialize_vision_modules(self, model_args, fsdp=None):
|
| 234 |
+
vision_tower = model_args.vision_tower
|
| 235 |
+
mm_vision_select_layer = model_args.mm_vision_select_layer
|
| 236 |
+
mm_vision_select_feature = model_args.mm_vision_select_feature
|
| 237 |
+
pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
|
| 238 |
+
|
| 239 |
+
self.config.mm_vision_tower = vision_tower
|
| 240 |
+
|
| 241 |
+
if self.get_vision_tower() is None:
|
| 242 |
+
vision_tower = build_vision_tower(model_args)
|
| 243 |
+
|
| 244 |
+
if fsdp is not None and len(fsdp) > 0:
|
| 245 |
+
self.vision_tower = [vision_tower]
|
| 246 |
+
else:
|
| 247 |
+
self.vision_tower = vision_tower
|
| 248 |
+
else:
|
| 249 |
+
if fsdp is not None and len(fsdp) > 0:
|
| 250 |
+
vision_tower = self.vision_tower[0]
|
| 251 |
+
else:
|
| 252 |
+
vision_tower = self.vision_tower
|
| 253 |
+
vision_tower.load_model()
|
| 254 |
+
|
| 255 |
+
self.config.use_mm_proj = True
|
| 256 |
+
self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
|
| 257 |
+
self.config.mm_hidden_size = vision_tower.hidden_size
|
| 258 |
+
self.config.mm_vision_select_layer = mm_vision_select_layer
|
| 259 |
+
self.config.mm_vision_select_feature = mm_vision_select_feature
|
| 260 |
+
|
| 261 |
+
if getattr(self, 'mm_projector', None) is None:
|
| 262 |
+
self.mm_projector = build_vision_projector(self.config)
|
| 263 |
+
else:
|
| 264 |
+
# In case it is frozen by LoRA
|
| 265 |
+
for p in self.mm_projector.parameters():
|
| 266 |
+
p.requires_grad = True
|
| 267 |
+
|
| 268 |
+
if pretrain_mm_mlp_adapter is not None:
|
| 269 |
+
mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
|
| 270 |
+
def get_w(weights, keyword):
|
| 271 |
+
return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
|
| 272 |
+
|
| 273 |
+
self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class LlavaMetaForCausalLM(ABC):
|
| 277 |
+
|
| 278 |
+
@abstractmethod
|
| 279 |
+
def get_model(self):
|
| 280 |
+
pass
|
| 281 |
+
|
| 282 |
+
@abstractmethod
|
| 283 |
+
def get_tokenizer(self):
|
| 284 |
+
pass
|
| 285 |
+
|
| 286 |
+
def get_vision_tower(self):
|
| 287 |
+
return self.get_model().get_vision_tower()
|
| 288 |
+
|
| 289 |
+
def encode_images(self, images):
|
| 290 |
+
image_features = self.get_model().get_vision_tower()(images)
|
| 291 |
+
image_features = self.get_model().mm_projector(image_features)
|
| 292 |
+
return image_features
|
| 293 |
+
|
| 294 |
+
def prepare_inputs_labels_for_multimodal_new(
|
| 295 |
+
self, input_ids: list[torch.tensor], position_ids, attention_mask: list[torch.tensor], past_key_values, labels, images
|
| 296 |
+
):
|
| 297 |
+
vision_tower = self.get_vision_tower()
|
| 298 |
+
if not self.training: # TODO: check this out!!
|
| 299 |
+
# pdb.set_trace()
|
| 300 |
+
if vision_tower is None or images is None or input_ids.shape[1] == 1:
|
| 301 |
+
if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1:
|
| 302 |
+
|
| 303 |
+
if attention_mask is None:
|
| 304 |
+
# only happen for qwen at inference
|
| 305 |
+
# raise ValueError(f'should not be here except for Qwen!')
|
| 306 |
+
return input_ids, None, attention_mask, past_key_values, None, labels
|
| 307 |
+
|
| 308 |
+
target_shape = past_key_values[-1][-1].shape[-2] + 1
|
| 309 |
+
attention_mask = torch.cat((attention_mask, torch.ones(
|
| 310 |
+
(attention_mask.shape[0], target_shape - attention_mask.shape[1]),
|
| 311 |
+
dtype=attention_mask.dtype,
|
| 312 |
+
device=attention_mask.device
|
| 313 |
+
)), dim=1)
|
| 314 |
+
position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
|
| 315 |
+
return input_ids, position_ids, attention_mask, past_key_values, None, labels
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
# ####################### this block must be optimized! #######################
|
| 319 |
+
# if type(images) is list or images.ndim == 5:
|
| 320 |
+
# concat_images = torch.cat([image for image in images], dim=0)
|
| 321 |
+
# image_features = self.encode_images(concat_images)
|
| 322 |
+
# split_sizes = [image.shape[0] for image in images]
|
| 323 |
+
# image_features = torch.split(image_features, split_sizes, dim=0)
|
| 324 |
+
# image_features = [x.flatten(0, 1).to(self.device) for x in image_features]
|
| 325 |
+
# else:
|
| 326 |
+
# image_features = self.encode_images(images).to(self.device)
|
| 327 |
+
# ####################### this block must be optimized! #######################
|
| 328 |
+
|
| 329 |
+
# ####################### optimized #######################
|
| 330 |
+
if getattr(self, 'cached_image_features', None) is None:
|
| 331 |
+
# this attribute should be cleared in bot.clear_history()
|
| 332 |
+
if type(images) is list or images.ndim == 5:
|
| 333 |
+
concat_images = torch.cat([image for image in images], dim=0)
|
| 334 |
+
image_features = self.encode_images(concat_images)
|
| 335 |
+
split_sizes = [image.shape[0] for image in images]
|
| 336 |
+
image_features = torch.split(image_features, split_sizes, dim=0)
|
| 337 |
+
image_features = [x.flatten(0, 1).to(self.device) for x in image_features]
|
| 338 |
+
else:
|
| 339 |
+
image_features = self.encode_images(images).to(self.device)
|
| 340 |
+
self.cached_image_features = image_features
|
| 341 |
+
image_features = self.cached_image_features
|
| 342 |
+
# ####################### optimized #######################
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
# TODO: image start / end is not implemented here to support pretraining.
|
| 346 |
+
if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
|
| 347 |
+
raise NotImplementedError
|
| 348 |
+
|
| 349 |
+
# Let's just add dummy tensors if they do not exist,
|
| 350 |
+
# it is a headache to deal with None all the time.
|
| 351 |
+
# But it is not ideal, and if you have a better idea,
|
| 352 |
+
# please open an issue / submit a PR, thanks.
|
| 353 |
+
_labels = labels
|
| 354 |
+
_position_ids = position_ids
|
| 355 |
+
_attention_mask = attention_mask
|
| 356 |
+
if attention_mask is None:
|
| 357 |
+
# attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
|
| 358 |
+
attention_mask = [torch.tensor([1]*l).to(input_ids).bool() for l in map(len, [ip for ip in input_ids])]
|
| 359 |
+
else:
|
| 360 |
+
# attention_mask = attention_mask.bool()
|
| 361 |
+
attention_mask = [att.bool() for att in attention_mask]
|
| 362 |
+
|
| 363 |
+
# if position_ids is None:
|
| 364 |
+
# position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
|
| 365 |
+
|
| 366 |
+
if labels is None:
|
| 367 |
+
labels = [torch.tensor([IGNORE_INDEX]*l).to(input_ids) for l in map(len, [ip for ip in input_ids])]
|
| 368 |
+
# labels = torch.full_like(input_ids, IGNORE_INDEX)
|
| 369 |
+
else:
|
| 370 |
+
labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
|
| 371 |
+
# remove the padding using attention_mask -- TODO: double check
|
| 372 |
+
# pdb.set_trace()
|
| 373 |
+
input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
|
| 374 |
+
|
| 375 |
+
new_input_embeds = []
|
| 376 |
+
new_labels = []
|
| 377 |
+
cur_image_idx = 0
|
| 378 |
+
for batch_idx, cur_input_ids in enumerate(input_ids):
|
| 379 |
+
num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
|
| 380 |
+
if num_images == 0:
|
| 381 |
+
|
| 382 |
+
############### FIXME ###############
|
| 383 |
+
if cur_image_idx > len(image_features)-1:
|
| 384 |
+
cur_image_idx = len(image_features)-1
|
| 385 |
+
print(f'warning: {input_ids}')
|
| 386 |
+
############### FIXME ###############
|
| 387 |
+
|
| 388 |
+
cur_image_features = image_features[cur_image_idx]
|
| 389 |
+
cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
|
| 390 |
+
cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
|
| 391 |
+
new_input_embeds.append(cur_input_embeds)
|
| 392 |
+
new_labels.append(labels[batch_idx])
|
| 393 |
+
cur_image_idx += 1
|
| 394 |
+
continue
|
| 395 |
+
|
| 396 |
+
image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
|
| 397 |
+
cur_input_ids_noim = []
|
| 398 |
+
cur_labels = labels[batch_idx]
|
| 399 |
+
cur_labels_noim = []
|
| 400 |
+
for i in range(len(image_token_indices) - 1):
|
| 401 |
+
cur_input_ids_noim.append(cur_input_ids[image_token_indices[i]+1:image_token_indices[i+1]])
|
| 402 |
+
cur_labels_noim.append(cur_labels[image_token_indices[i]+1:image_token_indices[i+1]])
|
| 403 |
+
split_sizes = [x.shape[0] for x in cur_labels_noim]
|
| 404 |
+
cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
|
| 405 |
+
cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
|
| 406 |
+
cur_new_input_embeds = []
|
| 407 |
+
cur_new_labels = []
|
| 408 |
+
|
| 409 |
+
# you have 10 images, but you have 11 placeholders
|
| 410 |
+
for i in range(num_images + 1):
|
| 411 |
+
cur_new_input_embeds.append(cur_input_embeds_no_im[i])
|
| 412 |
+
cur_new_labels.append(cur_labels_noim[i])
|
| 413 |
+
if i < num_images:
|
| 414 |
+
############### FIXME ###############
|
| 415 |
+
if cur_image_idx > len(image_features)-1:
|
| 416 |
+
cur_image_idx = len(image_features)-1
|
| 417 |
+
print(f'warning: {input_ids}')
|
| 418 |
+
############### FIXME ###############
|
| 419 |
+
|
| 420 |
+
cur_image_features = image_features[cur_image_idx]
|
| 421 |
+
cur_image_idx += 1
|
| 422 |
+
cur_new_input_embeds.append(cur_image_features)
|
| 423 |
+
cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
|
| 424 |
+
|
| 425 |
+
cur_new_input_embeds = torch.cat(cur_new_input_embeds)
|
| 426 |
+
cur_new_labels = torch.cat(cur_new_labels)
|
| 427 |
+
|
| 428 |
+
new_input_embeds.append(cur_new_input_embeds)
|
| 429 |
+
new_labels.append(cur_new_labels)
|
| 430 |
+
|
| 431 |
+
# Truncate sequences to max length as image embeddings can make the sequence longer
|
| 432 |
+
tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None)
|
| 433 |
+
if tokenizer_model_max_length is not None:
|
| 434 |
+
new_input_embeds = [x[:tokenizer_model_max_length] for x in new_input_embeds]
|
| 435 |
+
new_labels = [x[:tokenizer_model_max_length] for x in new_labels]
|
| 436 |
+
|
| 437 |
+
# Combine them
|
| 438 |
+
max_len = max(x.shape[0] for x in new_input_embeds)
|
| 439 |
+
batch_size = len(new_input_embeds)
|
| 440 |
+
|
| 441 |
+
new_input_embeds_padded = []
|
| 442 |
+
new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
|
| 443 |
+
attention_mask = torch.zeros((batch_size, max_len), dtype=torch.bool, device=attention_mask[0].device)
|
| 444 |
+
position_ids = torch.zeros((batch_size, max_len), dtype=torch.long, device=attention_mask[0].device)
|
| 445 |
+
|
| 446 |
+
for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
|
| 447 |
+
cur_len = cur_new_embed.shape[0]
|
| 448 |
+
# print(f'cur_len[{i}]before padding: {cur_len}')
|
| 449 |
+
# if i==0:
|
| 450 |
+
# print(f"{getattr(self.config, 'tokenizer_padding_side', 'right')} {self.get_tokenizer().padding_side}")
|
| 451 |
+
if getattr(self.config, 'tokenizer_padding_side', 'right') == "left": # checked, this is correct
|
| 452 |
+
# if self.get_tokenizer().padding_side == 'left':
|
| 453 |
+
new_input_embeds_padded.append(torch.cat((
|
| 454 |
+
torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device),
|
| 455 |
+
cur_new_embed
|
| 456 |
+
), dim=0))
|
| 457 |
+
if cur_len > 0:
|
| 458 |
+
new_labels_padded[i, -cur_len:] = cur_new_labels
|
| 459 |
+
attention_mask[i, -cur_len:] = True
|
| 460 |
+
position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
| 461 |
+
else:
|
| 462 |
+
new_input_embeds_padded.append(torch.cat((
|
| 463 |
+
cur_new_embed,
|
| 464 |
+
torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)
|
| 465 |
+
), dim=0))
|
| 466 |
+
if cur_len > 0:
|
| 467 |
+
new_labels_padded[i, :cur_len] = cur_new_labels
|
| 468 |
+
attention_mask[i, :cur_len] = True
|
| 469 |
+
position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
| 470 |
+
|
| 471 |
+
new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
|
| 472 |
+
|
| 473 |
+
if _labels is None:
|
| 474 |
+
new_labels = None
|
| 475 |
+
else:
|
| 476 |
+
new_labels = new_labels_padded
|
| 477 |
+
|
| 478 |
+
if _attention_mask is None:
|
| 479 |
+
attention_mask = None
|
| 480 |
+
else:
|
| 481 |
+
# attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
|
| 482 |
+
attention_mask = attention_mask.to(dtype=torch.bool)
|
| 483 |
+
|
| 484 |
+
if _position_ids is None:
|
| 485 |
+
position_ids = None
|
| 486 |
+
|
| 487 |
+
return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
|
| 488 |
+
|
| 489 |
+
def initialize_vision_tokenizer(self, model_args, tokenizer):
|
| 490 |
+
if model_args.mm_use_im_patch_token:
|
| 491 |
+
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
| 492 |
+
self.resize_token_embeddings(len(tokenizer))
|
| 493 |
+
|
| 494 |
+
if model_args.mm_use_im_start_end:
|
| 495 |
+
num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
| 496 |
+
self.resize_token_embeddings(len(tokenizer))
|
| 497 |
+
|
| 498 |
+
if num_new_tokens > 0:
|
| 499 |
+
input_embeddings = self.get_input_embeddings().weight.data
|
| 500 |
+
output_embeddings = self.get_output_embeddings().weight.data
|
| 501 |
+
|
| 502 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
|
| 503 |
+
dim=0, keepdim=True)
|
| 504 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
|
| 505 |
+
dim=0, keepdim=True)
|
| 506 |
+
|
| 507 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
| 508 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
| 509 |
+
|
| 510 |
+
if model_args.tune_mm_mlp_adapter:
|
| 511 |
+
for p in self.get_input_embeddings().parameters():
|
| 512 |
+
p.requires_grad = True
|
| 513 |
+
for p in self.get_output_embeddings().parameters():
|
| 514 |
+
p.requires_grad = False
|
| 515 |
+
|
| 516 |
+
if model_args.pretrain_mm_mlp_adapter:
|
| 517 |
+
mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location='cpu')
|
| 518 |
+
embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight']
|
| 519 |
+
assert num_new_tokens == 2
|
| 520 |
+
if input_embeddings.shape == embed_tokens_weight.shape:
|
| 521 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
|
| 522 |
+
elif embed_tokens_weight.shape[0] == num_new_tokens:
|
| 523 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight
|
| 524 |
+
else:
|
| 525 |
+
raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
|
| 526 |
+
elif model_args.mm_use_im_patch_token:
|
| 527 |
+
if model_args.tune_mm_mlp_adapter:
|
| 528 |
+
for p in self.get_input_embeddings().parameters():
|
| 529 |
+
p.requires_grad = False
|
| 530 |
+
for p in self.get_output_embeddings().parameters():
|
| 531 |
+
p.requires_grad = False
|