Upload folder using huggingface_hub
Browse filesFiles changed (23)
- config.jsonAdded+52
- configuration_emu.pyAdded+77
- constants.pyAdded+47
- generation_config.jsonAdded+7
- model-00001-of-00015.safetensorsAdded+3
- model-00002-of-00015.safetensorsAdded+3
- model-00003-of-00015.safetensorsAdded+3
- model-00004-of-00015.safetensorsAdded+3
- model-00005-of-00015.safetensorsAdded+3
- model-00006-of-00015.safetensorsAdded+3
- model-00007-of-00015.safetensorsAdded+3
- model-00008-of-00015.safetensorsAdded+3
- model-00009-of-00015.safetensorsAdded+3
- model-00010-of-00015.safetensorsAdded+3
- model-00011-of-00015.safetensorsAdded+3
- model-00012-of-00015.safetensorsAdded+3
- model-00013-of-00015.safetensorsAdded+3
- model-00014-of-00015.safetensorsAdded+3
- model-00015-of-00015.safetensorsAdded+3
- model.safetensors.index.jsonAdded
- modeling_emu.pyAdded+913
- modeling_llama.pyAdded
- visual.pyAdded+450
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152{ "_name_or_path": "/work1/amd/xiwenwei/Emu/Emu2/Emu2", "architectures": [ "EmuForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "auto_map": { "AutoConfig": "configuration_emu.EmuConfig", "AutoModelForCausalLM": "modeling_emu.EmuForCausalLM" }, "bos_token_id": 1, "d_model": 1792, "eos_token_id": 2, "hidden_act": "silu", "hidden_size": 6656, "initializer_range": 0.02, "intermediate_size": 17920, "llama_config_path": "/share/project/quansun/models/llm_models/llama/hf/llama-30b", "max_position_embeddings": 2048, "model_version": "base", "num_attention_heads": 52, "num_hidden_layers": 60, "num_key_value_heads": 52, "pad_token_id": 32000, "pretraining_tp": 1, "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 10000.0, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.44.0", "use_cache": true, "vision_config": { "drop_path_rate": 0, "eva_model_name": "eva-clip-E-14-plus", "head_width": 112, "image_size": 448, "intermediate_size": 15360, "layer_norm_eps": 1e-06, "layers": 64, "mlp_ratio": 8.571428571428571, "n_query": 64, "patch_size": 14, "postnorm": true, "qkv_bias": true, "v_query": 64, "width": 1792, "xattn": false }, "vocab_size": 32272}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677from typing import Literalfrom transformers import PretrainedConfig
class EmuConfig(PretrainedConfig): _auto_class = "AutoConfig"
def __init__( self, vocab_size=32000, hidden_size=4096, intermediate_size=11008, num_hidden_layers=32, num_attention_heads=32, hidden_act='silu', max_position_embeddings=2048, initializer_range=0.02, rms_norm_eps=1e-06, model_version: Literal["base", "chat"] = "base", pad_token_id=0, bos_token_id=1, eos_token_id=2, tie_word_embeddings=False, use_cache=True, pretraining_tp=1, rope_theta=10000.0, rope_scaling=None, attention_bias=False, attention_dropout=0.0, **kwargs, ): self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_attention_heads = num_attention_heads self.max_position_embeddings = max_position_embeddings self.rms_norm_eps = rms_norm_eps self.initializer_range = initializer_range self.vocab_size = vocab_size self.num_hidden_layers = num_hidden_layers self.hidden_act = hidden_act self.model_version = model_version self.use_cache = use_cache self.pretraining_tp = pretraining_tp self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling self._rope_scaling_validation() self.attention_bias = attention_bias self.attention_dropout = attention_dropout super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, )
def _rope_scaling_validation(self): """ Validate the `rope_scaling` configuration. """ if self.rope_scaling is None: return
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, " f"got {self.rope_scaling}" ) rope_scaling_type = self.rope_scaling.get("type", None) rope_scaling_factor = self.rope_scaling.get("factor", None) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0: raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647EVA_IMAGE_SIZE = 448OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073)OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711)
DEFAULT_IMAGE_FILE_SUFFIX = ['jpg', '0.png', 'png', 'jpeg', 'webp']DEFAULT_TEXT_FILE_SUFFIX = ['txt', '0.txt']
IGNORE_INDEX = -100
# special tokens# START DEFAULT_PAD_TOKEN = "[PAD]"DEFAULT_BOS_TOKEN = '<s>'DEFAULT_EOS_TOKEN = '</s>'DEFAULT_UNK_TOKEN = "<unk>"
DEFAULT_IMG_TOKEN = "[IMG]"DEFAULT_IMG_END_TOKEN = "[/IMG]"DEFAULT_IMAGE_TOKEN = "<image>"DEFAULT_gIMG_TOKEN = "[gIMG]"DEFAULT_gIMG_END_TOKEN = "[/gIMG]"DEFAULT_EOC_TOKEN = "[EOC]"DEFAULT_VIDEO_TOKEN = "[VIDEO]"
GRD_SYMBOL = "<grounding>"BOP_SYMBOL = "<phrase>"EOP_SYMBOL = "</phrase>"BOO_SYMBOL = "<object>"EOO_SYMBOL = "</object>"DOM_SYMBOL = "</delimiter_of_multi_objects/>"
REC_SYMBOL = "<REC>"
USER_TOKEN = "[USER]"ASSISTANT_TOKEN = "[ASSISTANT]"# END
# special token id# STARTIMAGE = 32003BOI = 32001
# END
DEFAULT_IMG_PLACEHOLDER = "[<IMG_PLH>]"DEFAULT_VID_PLACEHOLDER = "[<VID_PLH>]"FAKE_VIDEO_END_TOKEN = "[/VIDEO]"1234567{ "_from_model_config": true, "bos_token_id": 1, "eos_token_id": 2, "pad_token_id": 32000, "transformers_version": "4.44.0"}123version https://git-lfs.github.com/spec/v1oid sha256:ff555a578375fecd46ccaadc20f0476923d9b6ef7461813bdf939054c6e499f1size 4977365880123version https://git-lfs.github.com/spec/v1oid sha256:b09b36c3df197271620d8e0f6d448c2beef4e0add52719f433c3f6275b2e031esize 4984263544123version https://git-lfs.github.com/spec/v1oid sha256:50f2b4e9eabfdca65a25a73df385df6c1f9c16817953e628ae8e93d4a308c079size 4873397680123version https://git-lfs.github.com/spec/v1oid sha256:279480d40494cfe6211cdc389fafc9e77e35d3f914f5a4da6ef98b0d6e91f2b0size 4996080424123version https://git-lfs.github.com/spec/v1oid sha256:5b3b49ba684d04cbaba41613412759fdc2e8558143273a3661c40ab887544552size 4873370832123version https://git-lfs.github.com/spec/v1oid sha256:d7699b475ba6d4c80bb535cac21bda4e28a0b5ec1167a1767c666b7b0868da4dsize 4934738904123version https://git-lfs.github.com/spec/v1oid sha256:51faa6107c95df232e6176cd09c22ebf68b45e53fa0a8c1d80ad1c5b2192caf6size 4934712392123version https://git-lfs.github.com/spec/v1oid sha256:7e73197a4f83adbc9f23df5b37acc5109e0fb7befc5a7135da0f4343925e56a2size 4873397728123version https://git-lfs.github.com/spec/v1oid sha256:ff9c749753637f5243bb9edee99c424ee7202f82b19fb4dbb206474974c433e5size 4996080464123version https://git-lfs.github.com/spec/v1oid sha256:179e2bbe6989958a47ae14a860dda3078fdd389a69fb583d54ebe8b554c700c8size 4873370832123version https://git-lfs.github.com/spec/v1oid sha256:47203ed6da9fa7b07021d19839ff3a2339e4ca9a980a327a4816f706aa6d8eb8size 4934738904123version https://git-lfs.github.com/spec/v1oid sha256:cacd016742ec3432ddcaafeab33b693fc03c825513145aaeab03a516e7eb0bf8size 4934712392123version https://git-lfs.github.com/spec/v1oid sha256:41126c8659d4e30935686d85cbbaa7d1c99833d4fbbf18a5bb0e2123d2be3c78size 4873397728123version https://git-lfs.github.com/spec/v1oid sha256:925b86bb2323ce2e3472f90f9953f45ed0fd0ff91505937daf14915ebc679e72size 4996080464123version https://git-lfs.github.com/spec/v1oid sha256:c8a10d25ddb7e4d50b3d0f8140050fdf07110b9a14237213f473d6667103b19asize 4757728872123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913# from functools import partial# from typing import Any, List, Optional, Mapping, Callable# from collections import OrderedDict# from argparse import Namespace# import torch# from torch import nn# import torch.nn.functional as F# import torchvision.transforms as T# import PIL# import transformers# from transformers import PreTrainedModel, PreTrainedTokenizer
# from .configuration_emu import EmuConfig# from .constants import *# from .modeling_llama import LlamaForCausalLM# from .visual import EVAVisionTransformer
# class EmuPreTrainedModel(PreTrainedModel):# config_class = EmuConfig# base_model_prefix = "model"# supports_gradient_checkpointing = False# _no_split_modules = ["LlamaDecoderLayer", "Block"]# _skip_keys_device_placement = "past_key_values"
# def _init_weights(self, module):# std = self.config.initializer_range# if isinstance(module, nn.Linear):# module.weight.data.normal_(mean=0.0, std=std)# if module.bias is not None:# module.bias.data.zero_()# elif isinstance(module, nn.Embedding):# module.weight.data.normal_(mean=0.0, std=std)# if module.padding_idx is not None:# module.weight.data[module.padding_idx].zero_()
# class EmuForClsAndRegression(EmuPreTrainedModel):
# def __init__(self, config):# super(EmuForClsAndRegression, self).__init__(config)
# self.lm = LlamaForCausalLM(config=config)
# self.lm.model.embed_tokens.padding_idx = config.pad_token_id
# def get_num_layers(self):# return len(self.lm.model.layers)
# class EmuModel(EmuPreTrainedModel):
# def __init__(self, config):# super().__init__(config)
# vision_config = Namespace(**config.vision_config)
# self.visual = EVAVisionTransformer(# img_size=vision_config.image_size,# patch_size=vision_config.patch_size,# embed_dim=vision_config.width,# depth=vision_config.layers,# num_heads=vision_config.width // vision_config.head_width,# mlp_ratio=vision_config.mlp_ratio,# qkv_bias=vision_config.qkv_bias,# drop_path_rate=vision_config.drop_path_rate,# norm_layer=partial(nn.LayerNorm, eps=vision_config.layer_norm_eps),# xattn=vision_config.xattn,# postnorm=vision_config.postnorm,# )
# self.decoder = EmuForClsAndRegression(config)
# self.gradient_checkpointing = False # self.n_query = vision_config.n_query# self.v_query = vision_config.v_query
# @property# def device(self):# return next(iter(self.parameters())).device
# @property# def dtype(self):# return next(iter(self.parameters())).dtype
# @torch.no_grad()# def encode_image(self, image: torch.Tensor, *, n_query=None):# n_query = n_query if n_query is not None else self.n_query
# image_embeds = self.visual(image)# image_embeds = image_embeds[:, 1:, :]# b, n, c = image_embeds.shape# sqrt_n = int(n**0.5)# image_embeds = image_embeds.permute(0, 2, 1).view(b, c, sqrt_n, sqrt_n)
# stride = int(sqrt_n // (n_query ** 0.5))# image_embeds = F.avg_pool2d(image_embeds, kernel_size=(stride, stride), stride=stride)# image_embeds = image_embeds.view(b, c, -1).permute(0, 2, 1).contiguous()# return image_embeds
# class EmuForCausalLM(EmuPreTrainedModel):# _auto_class = "AutoModelForCausalLM"
# def __init__(self, config):# super().__init__(config)
# self.config = config# self.model = EmuModel(config)# # LM to EVA# self.project_down = nn.Linear(config.hidden_size, config.d_model, bias=False)# # EVA to LM# self.project_up = nn.Linear(config.d_model, config.hidden_size, bias=False)
# self.n_query = self.model.n_query# self.v_query = self.model.v_query
# self.image_placeholder = DEFAULT_IMG_TOKEN + DEFAULT_IMAGE_TOKEN * self.n_query + DEFAULT_IMG_END_TOKEN# # temporarily borrow [gIMG] as the video frame feature placeholder.# self.video_placeholder = DEFAULT_IMG_TOKEN + DEFAULT_gIMG_TOKEN * self.v_query + DEFAULT_IMG_END_TOKEN
# # @property# # def device(self):# # return next(iter(self.parameters())).device
# # @property# # def dtype(self):# # return next(iter(self.parameters())).dtype# def device(self, module=None):# if module is None:# return next(self.parameters()).device# return next(module.parameters()).device
# def dtype(self, module):# if module is None:# return next(self.parameters()).dtype# return next(module.parameters()).dtype
# @torch.no_grad()# def generate(# self,# input_ids,# attention_mask,# image: Optional[torch.Tensor] = None,# video: Optional[torch.Tensor] = None,# num_beams=5,# max_new_tokens=10,# min_len=1,# do_sample=False,# penalty_alpha=None,# top_p=None,# top_k=None,# temperature=None,# length_penalty=-1,# repetition_penalty=1.0,# **kwargs# ):
# text_embeds = self.model.decoder.lm.model.embed_tokens(input_ids).to("cuda")# if image is not None:# prompt_image_embeds = self.model.encode_image(image, n_query=self.n_query)# _, _, c = prompt_image_embeds.shape# prompt_image_embeds = prompt_image_embeds.view(-1, c)# prompt_image_embeds = self.project_up(prompt_image_embeds)# image_idx = (input_ids == IMAGE)# text_embeds[image_idx] = prompt_image_embeds.to(text_embeds.device)
# if video is not None:# prompt_video_embeds = self.model.encode_image(video, n_query=self.v_query)# _, _, c = prompt_video_embeds.shape# prompt_video_embeds = prompt_video_embeds.view(-1, c)# prompt_video_embeds = self.project_up(prompt_video_embeds)# video_idx = (input_ids == VIDEO)# text_embeds[video_idx] = prompt_video_embeds.to(text_embeds.device)
# outputs = self.model.decoder.lm.generate(# inputs_embeds=text_embeds,# attention_mask=attention_mask,# do_sample=do_sample,# num_beams=num_beams,# max_new_tokens=max_new_tokens,# min_length=min_len,# length_penalty=length_penalty,# repetition_penalty=repetition_penalty,# penalty_alpha=penalty_alpha,# top_k=top_k,# top_p=top_p,# temperature=temperature,# **kwargs,# )
# return outputs
# def prepare_image_input(self, images):# image_size: int = self.config.vision_config['image_size']# transform = T.Compose(# [# T.Resize(# (image_size, image_size), interpolation=T.InterpolationMode.BICUBIC# ),# T.ToTensor(),# T.Normalize(OPENAI_DATASET_MEAN, OPENAI_DATASET_STD),# ]# )# images = [transform(image) for image in images]# return torch.stack(images, 0)
# def _prepare_chat_template(self, text, system_msg=""):# text = [# system_msg + USER_TOKEN + ": " + t + ASSISTANT_TOKEN +":"# for t in text# ]# return text
# def prepare_text_input(# self, # text: List[str],# tokenizer: PreTrainedTokenizer,# image_placeholder: str = DEFAULT_IMG_PLACEHOLDER,# video_placeholder: str = DEFAULT_VID_PLACEHOLDER,# ):# text = [# t.replace(image_placeholder, self.image_placeholder).replace(video_placeholder, self.video_placeholder)# for t in text# ]# input_ids = tokenizer(text, padding="longest", return_tensors="pt")# return input_ids
# def build_input_ids(# self,# text: List[str],# tokenizer: PreTrainedTokenizer,# image: Optional[List["PIL.Image"]] = None,# video: Optional[List["PIL.Image"]] = None,# system_msg: str = "",# to_cuda: bool = True# ):
# if self.config.model_version == "chat":# text = self._prepare_chat_template(text, system_msg)
# if image is not None:# image = self.prepare_image_input(image)# if video is not None:# video = self.prepare_image_input(video)# inputs = self.prepare_text_input(text, tokenizer)# input_ids = inputs.input_ids# attention_mask = inputs.attention_mask
# if to_cuda:# input_ids = input_ids.to("cuda")# attention_mask = attention_mask.to("cuda")# if image is not None:# image = image.to("cuda")# if video is not None:# video = video.to("cuda")
# return {# 'input_ids': input_ids,# 'attention_mask': attention_mask,# 'image': image,# 'video': video# }
# def __call__(# self,# text: List[str],# tokenizer: PreTrainedTokenizer,# image: Optional[torch.Tensor] = None,# placeholder: str = DEFAULT_IMG_PLACEHOLDER,# lm_loss_weight: float = 1.0, # img_loss_weight: float = 1.0,# ):# IMAGE, BOI = tokenizer.convert_tokens_to_ids([DEFAULT_IMAGE_TOKEN, DEFAULT_IMG_TOKEN])# if image is not None:# batch_size = len(image)# # Now image is a list of images in [(5,3,448,448), (...)]# flattened_images = torch.cat(image, dim=0)# # [bs*5, 3, 448, 448]# prompt_image_embeds = self.model.encode_image(flattened_images)# _, _, c = prompt_image_embeds.shape# label = prompt_image_embeds# label = label.view(batch_size, -1, self.n_query, c)# label = label[:, -1, :, :]#.reshape(-1, c) # prompt_image_embeds = prompt_image_embeds.view(-1, c)# prompt_image_embeds = self.project_up(prompt_image_embeds)
# text = [t.replace(placeholder, self.image_placeholder) for t in text]
# inputs = tokenizer(text, padding="longest", return_tensors="pt")# device = self.device(self.model.decoder.lm.model.embed_tokens)# attention_mask = inputs.attention_mask.to(device)# input_ids = inputs.input_ids.to(device) # B x N# text_embeds = self.model.decoder.lm.model.embed_tokens(input_ids)# image_idx = (input_ids == IMAGE)# text_embeds[image_idx] = prompt_image_embeds.to(text_embeds.device)
# lm_labels = input_ids.clone()# # boi_idx = (input_ids == BOI)# lm_labels[image_idx] = IGNORE_INDEX # ignore image tokens# # lm_labels[boi_idx] = IGNORE_INDEX # also ignore any BOI tokens
# outputs = self.model.decoder.lm(# inputs_embeds=text_embeds,# attention_mask=attention_mask,# labels=lm_labels,# output_hidden_states=True,# return_dict=True,# )# lm_loss = outputs.loss
# hidden_states = outputs.hidden_states[-1]# hidden_states = self.project_down(hidden_states)
# # Compute last image embedding positions# boi_idx = torch.where(input_ids == BOI)# last_img_boi_idx = []# for bi in range(batch_size):# last_img_boi_idx.append(boi_idx[1][boi_idx[0] == bi][-1].item())# # Position of BOI of the input sequence will be the first img embedding position of the output sequence as forward will generate new token at the end of the sequence# preds = []# targets = []# for i, idx in enumerate(last_img_boi_idx):# avail = hidden_states.size(1) - idx# m = min(self.n_query, avail)# preds.append(hidden_states[i, idx:idx+m, :].contiguous()) #self.n_query, :].contiguous())# targets.append(label[i, :m, :].contiguous()) #, idx-1:idx+self.n_query, :].contiguous())
# preds = torch.stack(preds).view(-1, hidden_states.shape[-1])# targets = torch.stack(targets).view(-1, hidden_states.shape[-1])
# # print(" label.shape:", label.shape) # should be [batch_size, n_query, C]# # print(" len(last_img_boi_idx):", len(last_img_boi_idx))# # print(" preds_list len:", len(preds)) # number of rows in preds# # print(" preds.shape:", preds.shape)# # print(" targets.shape:", targets.shape)# loss_fn = torch.nn.MSELoss()# img_loss = loss_fn(preds, targets) #label)# total_loss = lm_loss_weight * lm_loss + img_loss_weight * img_loss
# # print(f"Image loss: {img_loss}, Language loss: {lm_loss}")
# return total_loss
# @torch.no_grad()# def generate_image(# self,# text: List[str],# tokenizer: PreTrainedTokenizer,# image: Optional[torch.Tensor] = None,# placeholder: str = DEFAULT_IMG_PLACEHOLDER,# ):# IMAGE, BOI = tokenizer.convert_tokens_to_ids([DEFAULT_IMAGE_TOKEN, DEFAULT_IMG_TOKEN])# if image is not None:# prompt_image_embeds = self.model.encode_image(image)# _, _, c = prompt_image_embeds.shape# prompt_image_embeds = prompt_image_embeds.view(-1, c)# prompt_image_embeds = self.project_up(prompt_image_embeds)
# text = [t.replace(placeholder, self.image_placeholder) for t in text]
# target_image_embeds = None# for num_img_token in range(self.n_query):# if num_img_token == 0:# text = [f"{t}{DEFAULT_IMG_TOKEN}" for t in text]# else:# text = [f"{t}{DEFAULT_IMAGE_TOKEN}" for t in text]
# inputs = tokenizer(text, padding="longest", return_tensors="pt")# device = self.device(self.model.decoder.lm.model.embed_tokens)# attention_mask = inputs.attention_mask.to(device)# input_ids = inputs.input_ids.to(device) # B x N
# text_embeds = self.model.decoder.lm.model.embed_tokens(input_ids)
# image_idx = (input_ids == IMAGE)# cumsum_idx = torch.flip(torch.cumsum(torch.flip(image_idx, dims=[1]), dim=1), dims=[1])# if image is not None:# prompt_idx = torch.logical_and(image_idx, cumsum_idx > num_img_token)# text_embeds[prompt_idx] = prompt_image_embeds.to(text_embeds.device)
# if target_image_embeds is not None:# target_idx = torch.logical_and(image_idx, torch.logical_and(cumsum_idx > 0, cumsum_idx <= num_img_token))# text_embeds[target_idx] = self.project_up(target_image_embeds).to(text_embeds.device)
# outputs = self.model.decoder.lm.model(# inputs_embeds=text_embeds,# attention_mask=attention_mask,# output_hidden_states=True,# return_dict=True,# )
# image_idx = (input_ids == IMAGE) + (input_ids == BOI)# cumsum_idx = torch.flip(torch.cumsum(torch.flip(image_idx, dims=[1]), dim=1), dims=[1])# target_idx = torch.logical_and(image_idx, torch.logical_and(cumsum_idx > 0, cumsum_idx <= num_img_token+1))
# hidden_states = outputs.hidden_states[-1]# target_image_embeds = hidden_states[target_idx.to(hidden_states.device)]# target_image_embeds = target_image_embeds.view(-1, target_image_embeds.shape[-1])# target_image_embeds = self.project_down(target_image_embeds)
# _, C = target_image_embeds.shape# B = hidden_states.shape[0]# target_image_embeds = target_image_embeds.view(B, -1, C)
# return target_image_embeds
from functools import partialfrom typing import Any, List, Optional, Mapping, Callablefrom collections import OrderedDictfrom argparse import Namespaceimport torchfrom torch import nnimport torch.nn.functional as Fimport torchvision.transforms as Timport PILimport transformersfrom transformers import PreTrainedModel, PreTrainedTokenizer
from .configuration_emu import EmuConfigfrom .constants import *from .modeling_llama import LlamaForCausalLMfrom .visual import EVAVisionTransformer
class EmuPreTrainedModel(PreTrainedModel): config_class = EmuConfig base_model_prefix = "model" supports_gradient_checkpointing = False _no_split_modules = ["LlamaDecoderLayer", "Block"] _skip_keys_device_placement = "past_key_values"
def _init_weights(self, module): std = self.config.initializer_range if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_()
class EmuForClsAndRegression(EmuPreTrainedModel):
def __init__(self, config): super(EmuForClsAndRegression, self).__init__(config)
self.lm = LlamaForCausalLM(config=config)
self.lm.model.embed_tokens.padding_idx = config.pad_token_id
def get_num_layers(self): return len(self.lm.model.layers)
class EmuModel(EmuPreTrainedModel):
def __init__(self, config): super().__init__(config)
vision_config = Namespace(**config.vision_config)
self.visual = EVAVisionTransformer( img_size=vision_config.image_size, patch_size=vision_config.patch_size, embed_dim=vision_config.width, depth=vision_config.layers, num_heads=vision_config.width // vision_config.head_width, mlp_ratio=vision_config.mlp_ratio, qkv_bias=vision_config.qkv_bias, drop_path_rate=vision_config.drop_path_rate, norm_layer=partial(nn.LayerNorm, eps=vision_config.layer_norm_eps), xattn=vision_config.xattn, postnorm=vision_config.postnorm, )
self.decoder = EmuForClsAndRegression(config)
self.gradient_checkpointing = False self.n_query = vision_config.n_query self.v_query = vision_config.v_query
@property def device(self): return next(iter(self.parameters())).device
@property def dtype(self): return next(iter(self.parameters())).dtype
@torch.no_grad() def encode_image(self, image: torch.Tensor, *, n_query=None): n_query = n_query if n_query is not None else self.n_query
image_embeds = self.visual(image) image_embeds = image_embeds[:, 1:, :] b, n, c = image_embeds.shape sqrt_n = int(n**0.5) image_embeds = image_embeds.permute(0, 2, 1).view(b, c, sqrt_n, sqrt_n)
stride = int(sqrt_n // (n_query ** 0.5)) image_embeds = F.avg_pool2d(image_embeds, kernel_size=(stride, stride), stride=stride) image_embeds = image_embeds.view(b, c, -1).permute(0, 2, 1).contiguous() return image_embeds
class EmuForCausalLM(EmuPreTrainedModel): _auto_class = "AutoModelForCausalLM"
def __init__(self, config): super().__init__(config)
self.config = config self.model = EmuModel(config) # LM to EVA self.project_down = nn.Linear(config.hidden_size, config.d_model, bias=False) # EVA to LM self.project_up = nn.Linear(config.d_model, config.hidden_size, bias=False)
self.n_query = self.model.n_query self.v_query = self.model.v_query
self.image_placeholder = DEFAULT_IMG_TOKEN + DEFAULT_IMAGE_TOKEN * self.n_query + DEFAULT_IMG_END_TOKEN # temporarily borrow [gIMG] as the video frame feature placeholder. self.video_placeholder = DEFAULT_IMG_TOKEN + DEFAULT_gIMG_TOKEN * self.v_query + DEFAULT_IMG_END_TOKEN
# @property # def device(self): # return next(iter(self.parameters())).device
# @property # def dtype(self): # return next(iter(self.parameters())).dtype def device(self, module=None): if module is None: return next(self.parameters()).device return next(module.parameters()).device
def dtype(self, module=None): if module is None: return next(self.parameters()).dtype return next(module.parameters()).dtype
@torch.no_grad() def generate( self, input_ids, attention_mask, image: Optional[torch.Tensor] = None, video: Optional[torch.Tensor] = None, num_beams=5, max_new_tokens=10, min_len=1, do_sample=False, penalty_alpha=None, top_p=None, top_k=None, temperature=None, length_penalty=-1, repetition_penalty=1.0, lambda_txt: float = 1.0, # <<< NEW lambda_img: float = 1.0, # <<< NEW **kwargs ):
text_embeds = self.model.decoder.lm.model.embed_tokens(input_ids).to("cuda") if image is not None: prompt_image_embeds = self.model.encode_image(image, n_query=self.n_query) _, _, c = prompt_image_embeds.shape prompt_image_embeds = prompt_image_embeds.view(-1, c) prompt_image_embeds = self.project_up(prompt_image_embeds) image_idx = (input_ids == IMAGE) text_embeds[image_idx] = prompt_image_embeds.to(text_embeds.device)
if video is not None: prompt_video_embeds = self.model.encode_image(video, n_query=self.v_query) _, _, c = prompt_video_embeds.shape prompt_video_embeds = prompt_video_embeds.view(-1, c) prompt_video_embeds = self.project_up(prompt_video_embeds) video_idx = (input_ids == VIDEO) text_embeds[video_idx] = prompt_video_embeds.to(text_embeds.device)
# modified: build masks for initial context B, T = input_ids.shape img_token_mask = torch.zeros((B, T), dtype=text_embeds.dtype, device=text_embeds.device) txt_token_mask = torch.ones((B, T), dtype=text_embeds.dtype, device=text_embeds.device)
if image is not None: boi_idx = torch.where(input_ids == BOI) for b in range(B): idxs = boi_idx[1][boi_idx[0] == b] if idxs.numel() > 0: j = idxs[-1].item() m = min(self.n_query, T - j) img_token_mask[b, j:j+m] = 1.0 txt_token_mask[b, j:j+m] = 0.0
outputs = self.model.decoder.lm.generate( inputs_embeds=text_embeds, attention_mask=attention_mask, do_sample=do_sample, num_beams=num_beams, max_new_tokens=max_new_tokens, min_length=min_len, length_penalty=length_penalty, repetition_penalty=repetition_penalty, penalty_alpha=penalty_alpha, top_k=top_k, top_p=top_p, temperature=temperature, lambda_txt=lambda_txt, # modified lambda_img=lambda_img, # img_token_mask=img_token_mask, # txt_token_mask=txt_token_mask, **kwargs, )
return outputs
def prepare_image_input(self, images): image_size: int = self.config.vision_config['image_size'] transform = T.Compose( [ T.Resize( (image_size, image_size), interpolation=T.InterpolationMode.BICUBIC ), T.ToTensor(), T.Normalize(OPENAI_DATASET_MEAN, OPENAI_DATASET_STD), ] ) images = [transform(image) for image in images] return torch.stack(images, 0)
def _prepare_chat_template(self, text, system_msg=""): text = [ system_msg + USER_TOKEN + ": " + t + ASSISTANT_TOKEN +":" for t in text ] return text
def prepare_text_input( self, text: List[str], tokenizer: PreTrainedTokenizer, image_placeholder: str = DEFAULT_IMG_PLACEHOLDER, video_placeholder: str = DEFAULT_VID_PLACEHOLDER, ): text = [ t.replace(image_placeholder, self.image_placeholder).replace(video_placeholder, self.video_placeholder) for t in text ] input_ids = tokenizer(text, padding="longest", return_tensors="pt") return input_ids
def build_input_ids( self, text: List[str], tokenizer: PreTrainedTokenizer, image: Optional[List["PIL.Image"]] = None, video: Optional[List["PIL.Image"]] = None, system_msg: str = "", to_cuda: bool = True ):
if self.config.model_version == "chat": text = self._prepare_chat_template(text, system_msg)
if image is not None: image = self.prepare_image_input(image) if video is not None: video = self.prepare_image_input(video) inputs = self.prepare_text_input(text, tokenizer) input_ids = inputs.input_ids attention_mask = inputs.attention_mask
if to_cuda: input_ids = input_ids.to("cuda") attention_mask = attention_mask.to("cuda") if image is not None: image = image.to("cuda") if video is not None: video = video.to("cuda")
return { 'input_ids': input_ids, 'attention_mask': attention_mask, 'image': image, 'video': video }
def __call__( self, text: List[str], tokenizer: PreTrainedTokenizer, image: Optional[torch.Tensor] = None, placeholder: str = DEFAULT_IMG_PLACEHOLDER, lm_loss_weight: float = 1.0, img_loss_weight: float = 1.0, return_dict=False, lambda_txt: float = 1.0, lambda_img: float = 1.0, lambda_orth: float = 1e-4, ): IMAGE, BOI = tokenizer.convert_tokens_to_ids([DEFAULT_IMAGE_TOKEN, DEFAULT_IMG_TOKEN]) if image is not None: batch_size = len(image) # Now image is a list of images in [(5,3,448,448), (...)] flattened_images = torch.cat(image, dim=0) # [bs*5, 3, 448, 448] prompt_image_embeds = self.model.encode_image(flattened_images) _, _, c = prompt_image_embeds.shape label = prompt_image_embeds label = label.view(batch_size, -1, self.n_query, c) label = label[:, -1, :, :]#.reshape(-1, c) prompt_image_embeds = prompt_image_embeds.view(-1, c) prompt_image_embeds = self.project_up(prompt_image_embeds)
text = [t.replace(placeholder, self.image_placeholder) for t in text]
inputs = tokenizer(text, padding="longest", return_tensors="pt") device = self.device(self.model.decoder.lm.model.embed_tokens) attention_mask = inputs.attention_mask.to(device) input_ids = inputs.input_ids.to(device) # B x N text_embeds = self.model.decoder.lm.model.embed_tokens(input_ids) image_idx = (input_ids == IMAGE) text_embeds[image_idx] = prompt_image_embeds.to(text_embeds.device)
# modified: modality masks (build BEFORE LM forward) B, N = input_ids.shape # float masks so they can multiply activations; keep dtype/device consistent img_token_mask = torch.zeros((B, N), dtype=text_embeds.dtype, device=text_embeds.device) last_img_boi_idx = [None] * B if image is not None: boi_idx = torch.where(input_ids == BOI) for bi in range(B): idxs = boi_idx[1][boi_idx[0] == bi] if idxs.numel() > 0: j = idxs[-1].item() last_img_boi_idx[bi] = j m = min(self.n_query, N - j) img_token_mask[bi, j:j+m] = 1.0 # only gate the n_query positions txt_token_mask = 1.0 - img_token_mask
lm_labels = input_ids.clone() # boi_idx = (input_ids == BOI) lm_labels[image_idx] = IGNORE_INDEX # ignore image tokens # lm_labels[boi_idx] = IGNORE_INDEX # also ignore any BOI tokens
outputs = self.model.decoder.lm( inputs_embeds=text_embeds, attention_mask=attention_mask, labels=lm_labels, output_hidden_states=True, return_dict=True, lambda_txt=lambda_txt, lambda_img=lambda_img, # img_token_mask=img_token_mask, # modified # txt_token_mask=txt_token_mask, # modified ) lm_loss = outputs.loss
hidden_states = outputs.hidden_states[-1] hidden_states = self.project_down(hidden_states)
# =================== OLD ======================================================= # # Compute last image embedding positions # boi_idx = torch.where(input_ids == BOI) # last_img_boi_idx = [] # for bi in range(batch_size): # last_img_boi_idx.append(boi_idx[1][boi_idx[0] == bi][-1].item()) # # Position of BOI of the input sequence will be the first img embedding position of the output sequence as forward will generate new token at the end of the sequence # preds = [] # targets = [] # for i, idx in enumerate(last_img_boi_idx): # avail = hidden_states.size(1) - idx # m = min(self.n_query, avail) # preds.append(hidden_states[i, idx:idx+m, :].contiguous()) #self.n_query, :].contiguous()) # targets.append(label[i, :m, :].contiguous()) #, idx-1:idx+self.n_query, :].contiguous())
# preds = torch.stack(preds).view(-1, hidden_states.shape[-1]) # targets = torch.stack(targets).view(-1, hidden_states.shape[-1])
# # print(" label.shape:", label.shape) # should be [batch_size, n_query, C] # # print(" len(last_img_boi_idx):", len(last_img_boi_idx)) # # print(" preds_list len:", len(preds)) # number of rows in preds # # print(" preds.shape:", preds.shape) # # print(" targets.shape:", targets.shape) # loss_fn = torch.nn.MSELoss() # img_loss = loss_fn(preds, targets) #label) # total_loss = lm_loss_weight * lm_loss + img_loss_weight * img_loss
# # print(f"Image loss: {img_loss}, Language loss: {lm_loss}") # =================== OLD ======================================
# If you use image loss, reuse last_img_boi_idx above (we computed it earlier) preds, targets = [], [] if image is not None: for i, j in enumerate(last_img_boi_idx): if j is None: # no BOI for this sample continue avail = hidden_states.size(1) - j m = min(self.n_query, avail) preds.append(hidden_states[i, j:j+m, :].contiguous()) targets.append(label[i, :m, :].contiguous())
preds = torch.stack(preds).view(-1, hidden_states.shape[-1]) targets = torch.stack(targets).view(-1, hidden_states.shape[-1]) img_loss = torch.nn.functional.mse_loss(preds, targets) total_loss = lm_loss_weight * lm_loss + img_loss_weight * img_loss else: img_loss = torch.tensor(0.0, dtype=lm_loss.dtype, device=lm_loss.device) total_loss = lm_loss
# ########################## Orthogonal Regularization ########################## # orth_txt_loss, orth_img_loss = 0., 0. # for name, param in self.model.named_parameters(): # if "lora_A" in name: # for name_, param_ in self.model.named_parameters(): # if "loratxt_A" in name_ and name.split("lora_A")[0] == name_.split("loratxt_A")[0]: # orth_txt_loss += torch.abs(torch.mm(param, param_.T)).sum() # [r * dim] * [dim * r] # break # target modules have been matched # if "lora_A" in name: # for name_, param_ in self.model.named_parameters(): # if "loraimg_A" in name_ and name.split("lora_A")[0] == name_.split("loraimg_A")[0]: # orth_img_loss += torch.abs(torch.mm(param, param_.T)).sum() # [r * dim] * [dim * r] # break # print(f"Orthogonal loss: {orthogonal_loss}") # orthogonal_loss = orthogonal_loss * lambda_orth # print(f"Orthogonal loss after scaling: {orthogonal_loss}") # scale = lm_loss.detach() / (orth_txt_loss.detach() + 1e-8) # lm_loss = lm_loss + scale * orth_txt_loss # scale = img_loss.detach() / (orth_img_loss.detach() + 1e-8) # img_loss = img_loss + scale * orth_img_loss
if not return_dict: return total_loss else: return total_loss, lm_loss, img_loss
@torch.no_grad() def generate_image( self, text: List[str], tokenizer: PreTrainedTokenizer, image: Optional[torch.Tensor] = None, placeholder: str = DEFAULT_IMG_PLACEHOLDER, ): IMAGE, BOI = tokenizer.convert_tokens_to_ids([DEFAULT_IMAGE_TOKEN, DEFAULT_IMG_TOKEN]) if image is not None: prompt_image_embeds = self.model.encode_image(image) _, _, c = prompt_image_embeds.shape prompt_image_embeds = prompt_image_embeds.view(-1, c) prompt_image_embeds = self.project_up(prompt_image_embeds)
text = [t.replace(placeholder, self.image_placeholder) for t in text]
target_image_embeds = None for num_img_token in range(self.n_query): if num_img_token == 0: text = [f"{t}{DEFAULT_IMG_TOKEN}" for t in text] else: text = [f"{t}{DEFAULT_IMAGE_TOKEN}" for t in text]
inputs = tokenizer(text, padding="longest", return_tensors="pt") device = self.device(self.model.decoder.lm.model.embed_tokens) attention_mask = inputs.attention_mask.to(device) input_ids = inputs.input_ids.to(device) # B x N
text_embeds = self.model.decoder.lm.model.embed_tokens(input_ids)
image_idx = (input_ids == IMAGE) cumsum_idx = torch.flip(torch.cumsum(torch.flip(image_idx, dims=[1]), dim=1), dims=[1]) if image is not None: prompt_idx = torch.logical_and(image_idx, cumsum_idx > num_img_token) text_embeds[prompt_idx] = prompt_image_embeds.to(text_embeds.device)
if target_image_embeds is not None: target_idx = torch.logical_and(image_idx, torch.logical_and(cumsum_idx > 0, cumsum_idx <= num_img_token)) text_embeds[target_idx] = self.project_up(target_image_embeds).to(text_embeds.device)
outputs = self.model.decoder.lm.model( inputs_embeds=text_embeds, attention_mask=attention_mask, output_hidden_states=True, return_dict=True, )
image_idx = (input_ids == IMAGE) + (input_ids == BOI) cumsum_idx = torch.flip(torch.cumsum(torch.flip(image_idx, dims=[1]), dim=1), dims=[1]) target_idx = torch.logical_and(image_idx, torch.logical_and(cumsum_idx > 0, cumsum_idx <= num_img_token+1))
hidden_states = outputs.hidden_states[-1] target_image_embeds = hidden_states[target_idx.to(hidden_states.device)] target_image_embeds = target_image_embeds.view(-1, target_image_embeds.shape[-1]) target_image_embeds = self.project_down(target_image_embeds)
_, C = target_image_embeds.shape B = hidden_states.shape[0] target_image_embeds = target_image_embeds.view(B, -1, C)
return target_image_embeds123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450# --------------------------------------------------------# Adapted from https://github.com/microsoft/unilm/tree/master/beit# --------------------------------------------------------
import osfrom functools import partial
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.utils.checkpoint import checkpoint
try: from timm.models.layers import drop_path, to_2tupleexcept: from timm.layers import drop_path, to_2tuple
try: import xformers.ops as xopsexcept ImportError: xops = None print("Please 'pip install xformers'")
class PatchDropout(nn.Module): """ https://arxiv.org/abs/2212.00794 """
def __init__(self, prob, exclude_first_token=True): super().__init__() assert 0 <= prob < 1. self.prob = prob self.exclude_first_token = exclude_first_token # exclude CLS token print(f"os.getenv('RoPE')={os.getenv('RoPE')}")
def forward(self, x): if not self.training or self.prob == 0.: return x
if self.exclude_first_token: cls_tokens, x = x[:, :1], x[:, 1:] else: cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1])
batch = x.size()[0] num_tokens = x.size()[1]
batch_indices = torch.arange(batch) batch_indices = batch_indices[..., None]
keep_prob = 1 - self.prob num_patches_keep = max(1, int(num_tokens * keep_prob))
rand = torch.randn(batch, num_tokens) patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices
x = x[batch_indices, patch_indices_keep]
if self.exclude_first_token: x = torch.cat((cls_tokens, x), dim=1)
if self.training and os.getenv('RoPE') == '1': return x, patch_indices_keep
return x
class DropPath(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). """ def __init__(self, drop_prob=None): super(DropPath, self).__init__() self.drop_prob = drop_prob
def forward(self, x): return drop_path(x, self.drop_prob, self.training) def extra_repr(self) -> str: return 'p={}'.format(self.drop_prob)
class Mlp(nn.Module): def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm, drop=0., subln=False,
): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer()
self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop)
def forward(self, x): x = self.fc1(x) x = self.act(x) # x = self.drop(x) # commit this for the orignal BERT implement x = self.ffn_ln(x)
x = self.fc2(x) x = self.drop(x) return x
class SwiGLU(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0., norm_layer=nn.LayerNorm, subln=False): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features
self.w1 = nn.Linear(in_features, hidden_features) self.w2 = nn.Linear(in_features, hidden_features)
self.act = act_layer() self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity() self.w3 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop)
def forward(self, x): x1 = self.w1(x) x2 = self.w2(x) hidden = self.act(x1) * x2 x = self.ffn_ln(hidden) x = self.w3(x) x = self.drop(x) return x
class Attention(nn.Module): def __init__( self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., window_size=None, attn_head_dim=None, xattn=False, rope=None, subln=False, norm_layer=nn.LayerNorm): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads if attn_head_dim is not None: head_dim = attn_head_dim all_head_dim = head_dim * self.num_heads self.scale = qk_scale or head_dim ** -0.5
self.subln = subln if self.subln: self.q_proj = nn.Linear(dim, all_head_dim, bias=False) self.k_proj = nn.Linear(dim, all_head_dim, bias=False) self.v_proj = nn.Linear(dim, all_head_dim, bias=False) else: if qkv_bias: self.qkv = nn.Linear(dim, all_head_dim * 3, bias=True) else: self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
# if qkv_bias: # self.q_bias = nn.Parameter(torch.zeros(all_head_dim)) # self.v_bias = nn.Parameter(torch.zeros(all_head_dim)) # else: # self.q_bias = None # self.v_bias = None
self.window_size = None self.relative_position_bias_table = None self.relative_position_index = None
self.attn_drop = nn.Dropout(attn_drop) self.inner_attn_ln = norm_layer(all_head_dim) if subln else nn.Identity() # self.proj = nn.Linear(all_head_dim, all_head_dim) self.proj = nn.Linear(all_head_dim, dim) self.proj_drop = nn.Dropout(proj_drop) self.xattn = xattn self.xattn_drop = attn_drop
self.rope = rope
def forward(self, x, rel_pos_bias=None, attn_mask=None): B, N, C = x.shape if self.subln: q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias) k = F.linear(input=x, weight=self.k_proj.weight, bias=None) v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias)
q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) # B, num_heads, N, C k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) else:
# qkv_bias = None # if self.q_bias is not None: # qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias)) # qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
qkv = self.qkv(x)
qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # 3, B, num_heads, N, C q, k, v = qkv[0], qkv[1], qkv[2]
if self.rope: q_t = q[:, :, 1:, :] ro_q_t = self.rope(q_t) q = torch.cat((q[:, :, :1, :], ro_q_t), -2).type_as(v)
k_t = k[:, :, 1:, :] ro_k_t = self.rope(k_t) k = torch.cat((k[:, :, :1, :], ro_k_t), -2).type_as(v)
if self.xattn: q = q.permute(0, 2, 1, 3) # B, num_heads, N, C -> B, N, num_heads, C k = k.permute(0, 2, 1, 3) v = v.permute(0, 2, 1, 3)
x = xops.memory_efficient_attention( q, k, v, p=self.xattn_drop, scale=self.scale, ) x = x.reshape(B, N, -1) x = self.inner_attn_ln(x) x = self.proj(x) x = self.proj_drop(x) else: q = q * self.scale attn = (q @ k.transpose(-2, -1))
if self.relative_position_bias_table is not None: relative_position_bias = \ self.relative_position_bias_table[self.relative_position_index.view(-1)].view( self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww attn = attn + relative_position_bias.unsqueeze(0).type_as(attn)
if rel_pos_bias is not None: attn = attn + rel_pos_bias.type_as(attn)
if attn_mask is not None: attn_mask = attn_mask.bool() attn = attn.masked_fill(~attn_mask[:, None, None, :], float("-inf")) attn = attn.softmax(dim=-1) attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, -1) x = self.inner_attn_ln(x) x = self.proj(x) x = self.proj_drop(x) return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., drop_path=0., init_values=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm, window_size=None, attn_head_dim=None, xattn=False, rope=None, postnorm=False, subln=False, naiveswiglu=False): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, window_size=window_size, attn_head_dim=attn_head_dim, xattn=xattn, rope=rope, subln=subln, norm_layer=norm_layer) # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio)
if naiveswiglu: self.mlp = SwiGLU( in_features=dim, hidden_features=mlp_hidden_dim, subln=subln, norm_layer=norm_layer, ) else: self.mlp = Mlp( in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, subln=subln, drop=drop )
if init_values is not None and init_values > 0: self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True) self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True) else: self.gamma_1, self.gamma_2 = None, None
self.postnorm = postnorm
def forward(self, x, rel_pos_bias=None, attn_mask=None): if self.gamma_1 is None: if self.postnorm: x = x + self.drop_path(self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))) x = x + self.drop_path(self.norm2(self.mlp(x))) else: x = x + self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)) x = x + self.drop_path(self.mlp(self.norm2(x))) else: if self.postnorm: x = x + self.drop_path(self.gamma_1 * self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))) x = x + self.drop_path(self.gamma_2 * self.norm2(self.mlp(x))) else: x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)) x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x))) return x
class PatchEmbed(nn.Module): """ Image to Patch Embedding """ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1]) self.img_size = img_size self.patch_size = patch_size self.num_patches = num_patches
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
def forward(self, x, **kwargs): B, C, H, W = x.shape # FIXME look at relaxing size constraints assert H == self.img_size[0] and W == self.img_size[1], \ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." x = self.proj(x).flatten(2).transpose(1, 2) return x
class EVAVisionTransformer(nn.Module): """ Vision Transformer with support for patch or hybrid CNN input stage """ def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm, init_values=None, patch_dropout=0., use_abs_pos_emb=True, use_rel_pos_bias=False, use_shared_rel_pos_bias=False, rope=False, use_mean_pooling=True, init_scale=0.001, grad_checkpointing=False, xattn=False, postnorm=False, pt_hw_seq_len=16, intp_freq=False, naiveswiglu=False, subln=False, ): super().__init__() self.image_size = img_size # self.num_classes = num_classes self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) num_patches = self.patch_embed.num_patches
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if use_abs_pos_emb: self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) else: self.pos_embed = None self.pos_drop = nn.Dropout(p=drop_rate)
self.rel_pos_bias = None self.rope = None
self.naiveswiglu = naiveswiglu
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule self.use_rel_pos_bias = use_rel_pos_bias self.blocks = nn.ModuleList([ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, init_values=init_values, window_size=self.patch_embed.patch_shape if use_rel_pos_bias else None, xattn=xattn, rope=self.rope, postnorm=postnorm, subln=subln, naiveswiglu=naiveswiglu) for i in range(depth)])
# setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0. else nn.Identity()
self.grad_checkpointing = grad_checkpointing
def get_num_layers(self): return len(self.blocks) def lock(self, unlocked_groups=0, freeze_bn_stats=False): assert unlocked_groups == 0, 'partial locking not currently supported for this model' for param in self.parameters(): param.requires_grad = False
@torch.jit.ignore def set_grad_checkpointing(self, enable=True): self.grad_checkpointing = enable
@torch.jit.ignore def no_weight_decay(self): return {'pos_embed', 'cls_token'}
def forward_features(self, x): x = self.patch_embed(x) batch_size, seq_len, _ = x.size()
cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks x = torch.cat((cls_tokens, x), dim=1) if self.pos_embed is not None: x = x + self.pos_embed x = self.pos_drop(x)
# a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in if os.getenv('RoPE') == '1': if self.training and not isinstance(self.patch_dropout, nn.Identity): x, patch_indices_keep = self.patch_dropout(x) self.rope.forward = partial(self.rope.forward, patch_indices_keep=patch_indices_keep) else: self.rope.forward = partial(self.rope.forward, patch_indices_keep=None) x = self.patch_dropout(x) else: x = self.patch_dropout(x)
rel_pos_bias = None
for blk in self.blocks: if self.grad_checkpointing: x = checkpoint(blk, x, (rel_pos_bias,)) else: x = blk(x, rel_pos_bias=rel_pos_bias)
return x
def forward(self, x):
""" :return: forward_features function returns raw features of ViT, forward with return_all_features returns normalized features of ViT :param x: :param return_all_features: """
features = self.forward_features(x) # [B, n_patch, C]
return featuresconfig.jsonAdded+52
configuration_emu.pyAdded+77
constants.pyAdded+47
generation_config.jsonAdded+7
model-00001-of-00015.safetensorsAdded+3
model-00002-of-00015.safetensorsAdded+3
model-00003-of-00015.safetensorsAdded+3
model-00004-of-00015.safetensorsAdded+3
model-00005-of-00015.safetensorsAdded+3
model-00006-of-00015.safetensorsAdded+3
model-00007-of-00015.safetensorsAdded+3
model-00008-of-00015.safetensorsAdded+3
model-00009-of-00015.safetensorsAdded+3
model-00010-of-00015.safetensorsAdded+3
model-00011-of-00015.safetensorsAdded+3
model-00012-of-00015.safetensorsAdded+3
model-00013-of-00015.safetensorsAdded+3
model-00014-of-00015.safetensorsAdded+3
model-00015-of-00015.safetensorsAdded+3
model.safetensors.index.jsonAdded
modeling_emu.pyAdded+913
modeling_llama.pyAdded
visual.pyAdded+450