File size: 15,337 Bytes
8a096e8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 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 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 |
#coding=utf-8
import os
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models.layers import trunc_normal_
from contextlib import suppress
import logging
from einops import rearrange
from peft import LoraConfig, get_peft_model
from bigmodelvis import Visualization
from .clip_encoder_hd import CLIPVisionTowerHD
from .conversation import get_conv_template
from .processors_conv import preprocess_qwen
from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedModel
from transformers.generation import GenerationConfig
from transformers import Qwen2Config, Qwen2ForCausalLM
def get_autocast(precision, cache_enabled=True):
if precision == "amp_bfloat16" or precision == "amp_bf16" or precision == 'bf16':
# amp_bfloat16 is more stable than amp float16 for clip training
return lambda: torch.cuda.amp.autocast(dtype=torch.bfloat16, cache_enabled=cache_enabled)
elif precision == 'fp16':
return lambda: torch.cuda.amp.autocast(dtype=torch.float16, cache_enabled=cache_enabled)
elif precision == 'fp32':
return suppress
else:
raise ValueError('not supported precision: {}'.format(precision))
class LayerNorm(nn.LayerNorm):
"""Subclass torch's LayerNorm to handle fp16."""
def forward(self, x: torch.Tensor):
orig_type = x.dtype
ret = super().forward(x.type(torch.float32))
return ret.type(orig_type)
class MLP(nn.Module):
""" Very simple multi-layer perceptron (also called FFN)"""
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
super().__init__()
self.num_layers = num_layers
h = [hidden_dim] * (num_layers - 1)
self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
def forward(self, x):
for i, layer in enumerate(self.layers):
x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
return x
class InfMLLM_Unified_HD_Chat(PreTrainedModel):
def __init__(self, config, debug=False):
super().__init__(config)
## Initialize LM model
self.lm_tokenizer = AutoTokenizer.from_pretrained(config._name_or_path, use_fast=False, trust_remote_code=True)
self.media_token_img = "<|image|>"
self.media_token_id_img = self.lm_tokenizer(self.media_token_img, return_tensors="pt",add_special_tokens=False).input_ids.item()
self.lm_model = Qwen2ForCausalLM(config.lm_config)
self.lm_tokenizer.model_max_length = config.max_txt_len
self.template_name = config.conv_style
self.preprocess_function = preprocess_qwen
self.separate = nn.Parameter(torch.zeros([1, 1, 4096]))
self.newline = nn.Parameter(torch.zeros([1, 1, 1, 4096]))
## Initialize image encoder
self.encoder_img = CLIPVisionTowerHD(config.vision_config, vision_select_layer=-2)
self.encoder_img_ln = lambda x: x
self.adapter_img = nn.Sequential(
nn.Linear(self.encoder_img.num_features*4, self.lm_model.config.hidden_size),
nn.GELU(),
nn.Linear(self.lm_model.config.hidden_size, self.lm_model.config.hidden_size)
)
## Others
self.config = config
self.precision = config.precision
self._apply_lemmatizer = getattr(config, 'apply_lemmatizer', False)
self._lemmatizer = None
def forward_encoder_img(self, image):
autocast = get_autocast(self.precision, cache_enabled=True)
with autocast():
assert isinstance(image, list)
image_embeds, image_split = self.encoder_img(image, self.separate, self.newline)
image_embeds = self.encoder_img_ln(image_embeds) # [bsz, L, D]
image_embeds = self.adapter_img(image_embeds)
return image_embeds, image_split
def _concat_embeds(self,
prompt_embeds, prompt_ids, prompt_masks,
labels=None, padding='left'):
emb_lens = [len(emb) for emb in prompt_embeds]
if len(set(emb_lens)) == 1:
if labels is not None:
return torch.stack(prompt_embeds, dim=0), torch.stack(prompt_ids, dim=0), torch.stack(prompt_masks, dim=0), torch.stack(labels, dim=0)
return torch.stack(prompt_embeds, dim=0), torch.stack(prompt_ids, dim=0), torch.stack(prompt_masks, dim=0)
pad_emb = self.lm_model.get_input_embeddings()(torch.tensor(self.lm_tokenizer.pad_token_id, device=prompt_embeds[0].device))
prompt_embeds_new = pad_emb.expand(len(emb_lens), max(emb_lens), -1).clone()
prompt_ids_new = torch.ones([len(emb_lens), max(emb_lens)]).to(prompt_ids[0]) * self.lm_tokenizer.pad_token_id
prompt_masks_new = torch.zeros([len(emb_lens), max(emb_lens)]).to(prompt_masks[0])
if labels is not None:
labels_new = -100 * torch.ones([len(emb_lens), max(emb_lens)]).to(prompt_ids[0])
for i, L in enumerate(emb_lens):
if padding == 'left':
prompt_embeds_new[i, -L:] = prompt_embeds[i]
prompt_ids_new[i, -L:] = prompt_ids[i]
prompt_masks_new[i, -L:] = prompt_masks[i]
if labels is not None:
labels_new[i, -L:] = labels[i]
elif padding == 'right':
prompt_embeds_new[i, :L] = prompt_embeds[i]
prompt_ids_new[i, :L] = prompt_ids[i]
prompt_masks_new[i, :L] = prompt_masks[i]
if labels is not None:
labels_new[i, :L] = labels[i]
else:
raise ValueError()
if labels is not None:
return prompt_embeds_new, prompt_ids_new, prompt_masks_new, labels_new
return prompt_embeds_new, prompt_ids_new, prompt_masks_new
def _insert_media_feat(self,
prompt_embeds, prompt_ids, prompt_masks,
is_languages,
embeds_media, media_token_id,
index_list=None,
labels=None, len_media=None):
## insert embeds_media into prompt
prompt_embeds_new = []
prompt_masks_new = []
prompt_ids_new = []
labels_new = []
device = embeds_media[0].device
if index_list is not None:
assert len(index_list) == len(embeds_media)
assert len(embeds_media) <= len(prompt_embeds)
for b in range(len(prompt_embeds)):
if (index_list is not None) and (b not in index_list):
prompt_embeds_new.append(prompt_embeds[b])
prompt_ids_new.append(prompt_ids[b])
prompt_masks_new.append(prompt_masks[b])
if labels is not None:
labels_new.append(labels[b])
else:
_idx = prompt_ids[b].tolist().index(media_token_id)
if index_list is not None:
b_media = index_list.index(b)
else:
b_media = b
if len_media is not None:
cur_embeds_media = embeds_media[b_media, :len_media[b_media]]
else:
cur_embeds_media = embeds_media[b_media]
prompt_embeds_new.append(torch.cat([prompt_embeds[b][:_idx+1],
cur_embeds_media,
prompt_embeds[b][_idx+1:]
], dim=0))
prompt_ids_new.append(torch.cat([prompt_ids[b][:_idx+1],
torch.ones(len(cur_embeds_media), dtype=torch.long).to(device).fill_(-100),
prompt_ids[b][_idx+1:]
], dim=0))
if labels is not None:
labels_new.append(torch.cat([labels[b][:_idx+1],
torch.ones(len(cur_embeds_media), dtype=torch.long).to(device).fill_(-100),
labels[b][_idx+1:]
], dim=0))
# if is pure-language sample, mask out image-embeddings
prompt_masks_new.append(torch.cat([prompt_masks[b][:_idx+1],
torch.zeros(len(cur_embeds_media), dtype=torch.long).to(device) if is_languages[b] else
torch.ones(len(cur_embeds_media), dtype=torch.long).to(device),
prompt_masks[b][_idx+1:]], dim=0))
if labels is not None:
return prompt_embeds_new, prompt_ids_new, prompt_masks_new, labels_new
return prompt_embeds_new, prompt_ids_new, prompt_masks_new
@torch.no_grad()
def generate(
self,
samples,
num_beams=5,
max_length=128,
min_length=1,
top_p=0.9,
temperature=0.,
return_prompts=False
):
autocast = get_autocast(self.precision, cache_enabled=True)
with autocast():
conversations = samples['conversations']
is_languages = [False] * len(conversations)
image_img = samples.get('images', None)
index_img = list(range(len(image_img)))
device = None
special_prefix = ["" for _ in range(len(conversations))]
if (self.config.encoder_img is not None) and (image_img is not None) and len(index_img) > 0:
for i in index_img:
special_prefix[i] = self.media_token_img + special_prefix[i]
new_image_img = []
for index in index_img:
new_image_img.append(image_img[index])
embeds_img, len_img = self.forward_encoder_img(new_image_img)
device = embeds_img.device
conv = get_conv_template(self.template_name)
roles = {'human': conv.roles[0], 'gpt': conv.roles[1]}
prompts = []
for i, source in enumerate(conversations):
if roles[source[0]['from']] != conv.roles[0]:
# Skip the first one if it is not from human
source = source[1:]
per_prefix = special_prefix[i]
conv.messages = []
for j, sentence in enumerate(source):
role = roles[sentence['from']]
assert role == conv.roles[j % 2], f'{i}'
sentence['value'] = sentence['value'].replace("<image>", "").strip() # llava-1.5 add <image> to the begin of the question, remove here
if j == 0:
sentence['value'] = per_prefix + sentence['value']
conv.append_message(role, sentence['value'])
prompts.append(conv.get_prompt())
self.lm_tokenizer.padding_side = "left"
if self.lm_tokenizer.bos_token is not None:
prompt_text = [self.lm_tokenizer.bos_token + t for t in prompts]
else:
prompt_text = prompts
prompt_tokens = self.lm_tokenizer(
prompt_text,
return_tensors="pt",
padding="longest",
truncation=False,
add_special_tokens=False
).to(device)
prompt_embeds = self.lm_model.get_input_embeddings()(prompt_tokens.input_ids)
prompt_masks = prompt_tokens.attention_mask # [bsz, n2]
prompt_ids = prompt_tokens.input_ids
assert torch.all(prompt_ids[:, -1] != self.lm_tokenizer.pad_token_id), "make sure padding left"
if embeds_img is not None:
prompt_embeds, prompt_ids, prompt_masks = self._insert_media_feat(prompt_embeds=prompt_embeds,
prompt_ids=prompt_ids,
prompt_masks=prompt_masks,
is_languages=is_languages,
embeds_media=embeds_img,
media_token_id=self.media_token_id_img,
index_list=index_img,
len_media=len_img)
# pad and concat embeds
prompt_embeds, prompt_ids, prompt_masks = self._concat_embeds(prompt_embeds, prompt_ids, prompt_masks, padding="left")
assert torch.all(prompt_ids[:, -1] != self.lm_tokenizer.pad_token_id), "make sure padding left"
kwargs = {}
kwargs['max_new_tokens'] = max_length
outputs = self.lm_model.generate(
#input_ids=input_ids,
inputs_embeds=prompt_embeds,
attention_mask=prompt_masks,
do_sample=True if temperature > 0 else False,
temperature=temperature,
top_p=top_p,
num_beams=num_beams,
eos_token_id=self.lm_tokenizer.eos_token_id,
#max_length=max_length,
min_length=min_length,
**kwargs
)
output_text = self.lm_tokenizer.batch_decode(
outputs, skip_special_tokens=True
)
output_text = [text.strip() for text in output_text]
if self._apply_lemmatizer or ("apply_lemmatizer" in samples.keys() and samples["apply_lemmatizer"]):
output_text = self._lemmatize(output_text)
if return_prompts:
return output_text, prompts
return output_text
def _lemmatize(self, answers):
def apply(answer):
doc = self.lemmatizer(answer)
words = []
for token in doc:
if token.pos_ in ["NOUN", "VERB"]:
words.append(token.lemma_)
else:
words.append(token.text)
answer = " ".join(words)
return answer
return [apply(answer) for answer in answers]
@property
def lemmatizer(self):
if self._lemmatizer is None:
try:
import spacy
self._lemmatizer = spacy.load("en_core_web_sm")
except ImportError:
logging.error(
"""
Please install spacy and en_core_web_sm model to apply lemmatization.
python -m spacy download en_core_web_sm
OR
import spacy.cli
spacy.cli.download("en_core_web_sm")
"""
)
exit(1)
return self._lemmatizer
|