Delete blip_decoder.py
Browse files- blip_decoder.py +0 -175
blip_decoder.py
DELETED
|
@@ -1,175 +0,0 @@
|
|
| 1 |
-
'''
|
| 2 |
-
* Copyright (c) 2022, salesforce.com, inc.
|
| 3 |
-
* All rights reserved.
|
| 4 |
-
* SPDX-License-Identifier: BSD-3-Clause
|
| 5 |
-
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
|
| 6 |
-
* By Junnan Li
|
| 7 |
-
'''
|
| 8 |
-
import warnings
|
| 9 |
-
warnings.filterwarnings("ignore")
|
| 10 |
-
|
| 11 |
-
from vit import VisionTransformer, interpolate_pos_embed
|
| 12 |
-
from med import BertConfig, BertModel, BertLMHeadModel
|
| 13 |
-
from transformers import BertTokenizer
|
| 14 |
-
|
| 15 |
-
import torch
|
| 16 |
-
from torch import nn
|
| 17 |
-
import torch.nn.functional as F
|
| 18 |
-
|
| 19 |
-
import os
|
| 20 |
-
from urllib.parse import urlparse
|
| 21 |
-
from timm.models.hub import download_cached_file
|
| 22 |
-
|
| 23 |
-
class BLIP_Decoder(nn.Module):
|
| 24 |
-
def __init__(self,
|
| 25 |
-
med_config = 'configs/med_config.json',
|
| 26 |
-
image_size = 384,
|
| 27 |
-
vit = 'base',
|
| 28 |
-
vit_grad_ckpt = False,
|
| 29 |
-
vit_ckpt_layer = 0,
|
| 30 |
-
prompt = 'a picture of ',
|
| 31 |
-
):
|
| 32 |
-
"""
|
| 33 |
-
Args:
|
| 34 |
-
med_config (str): path for the mixture of encoder-decoder model's configuration file
|
| 35 |
-
image_size (int): input image size
|
| 36 |
-
vit (str): model size of vision transformer
|
| 37 |
-
"""
|
| 38 |
-
super().__init__()
|
| 39 |
-
|
| 40 |
-
self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer)
|
| 41 |
-
self.tokenizer = init_tokenizer()
|
| 42 |
-
med_config = BertConfig.from_json_file(med_config)
|
| 43 |
-
med_config.encoder_width = vision_width
|
| 44 |
-
self.text_decoder = BertLMHeadModel(config=med_config)
|
| 45 |
-
|
| 46 |
-
self.prompt = prompt
|
| 47 |
-
self.prompt_length = len(self.tokenizer(self.prompt).input_ids)-1
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
def forward(self, image, caption):
|
| 51 |
-
|
| 52 |
-
image_embeds = self.visual_encoder(image)
|
| 53 |
-
image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
|
| 54 |
-
|
| 55 |
-
text = self.tokenizer(caption, padding='longest', truncation=True, max_length=40, return_tensors="pt").to(image.device)
|
| 56 |
-
|
| 57 |
-
text.input_ids[:,0] = self.tokenizer.bos_token_id
|
| 58 |
-
|
| 59 |
-
decoder_targets = text.input_ids.masked_fill(text.input_ids == self.tokenizer.pad_token_id, -100)
|
| 60 |
-
decoder_targets[:,:self.prompt_length] = -100
|
| 61 |
-
|
| 62 |
-
decoder_output = self.text_decoder(text.input_ids,
|
| 63 |
-
attention_mask = text.attention_mask,
|
| 64 |
-
encoder_hidden_states = image_embeds,
|
| 65 |
-
encoder_attention_mask = image_atts,
|
| 66 |
-
labels = decoder_targets,
|
| 67 |
-
return_dict = True,
|
| 68 |
-
)
|
| 69 |
-
loss_lm = decoder_output.loss
|
| 70 |
-
|
| 71 |
-
return loss_lm
|
| 72 |
-
|
| 73 |
-
def generate(self, image, sample=False, num_beams=3, max_length=30, min_length=10, top_p=0.9, repetition_penalty=1.0):
|
| 74 |
-
image_embeds = self.visual_encoder(image)
|
| 75 |
-
|
| 76 |
-
if not sample:
|
| 77 |
-
image_embeds = image_embeds.repeat_interleave(num_beams,dim=0)
|
| 78 |
-
|
| 79 |
-
image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device)
|
| 80 |
-
model_kwargs = {"encoder_hidden_states": image_embeds, "encoder_attention_mask":image_atts}
|
| 81 |
-
|
| 82 |
-
prompt = [self.prompt] * image.size(0)
|
| 83 |
-
input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids.to(image.device)
|
| 84 |
-
input_ids[:,0] = self.tokenizer.bos_token_id
|
| 85 |
-
input_ids = input_ids[:, :-1]
|
| 86 |
-
|
| 87 |
-
if sample:
|
| 88 |
-
#nucleus sampling
|
| 89 |
-
outputs = self.text_decoder.generate(input_ids=input_ids,
|
| 90 |
-
max_length=max_length,
|
| 91 |
-
min_length=min_length,
|
| 92 |
-
do_sample=True,
|
| 93 |
-
top_p=top_p,
|
| 94 |
-
num_return_sequences=1,
|
| 95 |
-
eos_token_id=self.tokenizer.sep_token_id,
|
| 96 |
-
pad_token_id=self.tokenizer.pad_token_id,
|
| 97 |
-
repetition_penalty=1.1,
|
| 98 |
-
**model_kwargs)
|
| 99 |
-
else:
|
| 100 |
-
#beam search
|
| 101 |
-
outputs = self.text_decoder.generate(input_ids=input_ids,
|
| 102 |
-
max_length=max_length,
|
| 103 |
-
min_length=min_length,
|
| 104 |
-
num_beams=num_beams,
|
| 105 |
-
eos_token_id=self.tokenizer.sep_token_id,
|
| 106 |
-
pad_token_id=self.tokenizer.pad_token_id,
|
| 107 |
-
repetition_penalty=repetition_penalty,
|
| 108 |
-
**model_kwargs)
|
| 109 |
-
|
| 110 |
-
captions = []
|
| 111 |
-
for output in outputs:
|
| 112 |
-
caption = self.tokenizer.decode(output, skip_special_tokens=True)
|
| 113 |
-
captions.append(caption[len(self.prompt):])
|
| 114 |
-
return captions
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
def blip_decoder(pretrained='',**kwargs):
|
| 118 |
-
model = BLIP_Decoder(**kwargs)
|
| 119 |
-
if pretrained:
|
| 120 |
-
model,msg = load_checkpoint(model,pretrained)
|
| 121 |
-
assert(len(msg.missing_keys)==0)
|
| 122 |
-
return model
|
| 123 |
-
|
| 124 |
-
def init_tokenizer():
|
| 125 |
-
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
| 126 |
-
tokenizer.add_special_tokens({'bos_token':'[DEC]'})
|
| 127 |
-
tokenizer.add_special_tokens({'additional_special_tokens':['[ENC]']})
|
| 128 |
-
tokenizer.enc_token_id = tokenizer.additional_special_tokens_ids[0]
|
| 129 |
-
return tokenizer
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
def create_vit(vit, image_size, use_grad_checkpointing=False, ckpt_layer=0, drop_path_rate=0):
|
| 133 |
-
|
| 134 |
-
assert vit in ['base', 'large'], "vit parameter must be base or large"
|
| 135 |
-
if vit=='base':
|
| 136 |
-
vision_width = 768
|
| 137 |
-
visual_encoder = VisionTransformer(img_size=image_size, patch_size=16, embed_dim=vision_width, depth=12,
|
| 138 |
-
num_heads=12, use_grad_checkpointing=use_grad_checkpointing, ckpt_layer=ckpt_layer,
|
| 139 |
-
drop_path_rate=0 or drop_path_rate
|
| 140 |
-
)
|
| 141 |
-
elif vit=='large':
|
| 142 |
-
vision_width = 1024
|
| 143 |
-
visual_encoder = VisionTransformer(img_size=image_size, patch_size=16, embed_dim=vision_width, depth=24,
|
| 144 |
-
num_heads=16, use_grad_checkpointing=use_grad_checkpointing, ckpt_layer=ckpt_layer,
|
| 145 |
-
drop_path_rate=0.1 or drop_path_rate
|
| 146 |
-
)
|
| 147 |
-
return visual_encoder, vision_width
|
| 148 |
-
|
| 149 |
-
def is_url(url_or_filename):
|
| 150 |
-
parsed = urlparse(url_or_filename)
|
| 151 |
-
return parsed.scheme in ("http", "https")
|
| 152 |
-
|
| 153 |
-
def load_checkpoint(model,url_or_filename):
|
| 154 |
-
if is_url(url_or_filename):
|
| 155 |
-
cached_file = download_cached_file(url_or_filename, check_hash=False, progress=True)
|
| 156 |
-
checkpoint = torch.load(cached_file, map_location='cpu')
|
| 157 |
-
elif os.path.isfile(url_or_filename):
|
| 158 |
-
checkpoint = torch.load(url_or_filename, map_location='cpu')
|
| 159 |
-
else:
|
| 160 |
-
raise RuntimeError('checkpoint url or path is invalid')
|
| 161 |
-
|
| 162 |
-
state_dict = checkpoint['model']
|
| 163 |
-
|
| 164 |
-
state_dict['visual_encoder.pos_embed'] = interpolate_pos_embed(state_dict['visual_encoder.pos_embed'],model.visual_encoder)
|
| 165 |
-
if 'visual_encoder_m.pos_embed' in model.state_dict().keys():
|
| 166 |
-
state_dict['visual_encoder_m.pos_embed'] = interpolate_pos_embed(state_dict['visual_encoder_m.pos_embed'],
|
| 167 |
-
model.visual_encoder_m)
|
| 168 |
-
for key in model.state_dict().keys():
|
| 169 |
-
if key in state_dict.keys():
|
| 170 |
-
if state_dict[key].shape!=model.state_dict()[key].shape:
|
| 171 |
-
del state_dict[key]
|
| 172 |
-
|
| 173 |
-
msg = model.load_state_dict(state_dict,strict=False)
|
| 174 |
-
print('load checkpoint from %s'%url_or_filename)
|
| 175 |
-
return model,msg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|