-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathalign_local.py
173 lines (142 loc) · 6.65 KB
/
align_local.py
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
import os
import copy
import torch
import pytorch_lightning as pl
from scl.config import _config
from scl.modules import SCLTransformer
from scl.datamodules.multitask_datamodule import MTDataModule
from transformers import RobertaTokenizer
from torchvision import transforms
import json
import pickle
import matplotlib.pyplot as plt
import numpy as np
import PIL
from PIL import Image
from PIL import Image, ImageDraw
import pickle
import json
from tqdm import tqdm
from numpy import mean
class VLmae_vis(SCLTransformer):
def __init__(self, config):
super().__init__(config)
@torch.no_grad()
def visualize(self, image, text_ids, text_masks):
text_embeds = self.text_transformer.embeddings(input_ids=text_ids)
device = text_embeds.device
input_shape = text_masks.size()
extend_text_masks = self.text_transformer.get_extended_attention_mask(text_masks, input_shape, device) # [bs,len] -> [bs,1,1,len]
for layer in self.text_transformer.encoder.layer:
text_embeds = layer(text_embeds, extend_text_masks)[0]
text_embeds = self.cross_modal_text_transform(text_embeds)
image_embeds, _ = self.vision_transformer.visual.visual_embed(image, False, self.mask_ratio)
image_masks = torch.ones((image_embeds.shape[0], image_embeds.shape[1]),
dtype=torch.long, device=text_masks.device)
image_embeds = self.vision_transformer(image_embeds)
image_embeds = self.cross_modal_image_transform(image_embeds)
extend_image_masks = self.text_transformer.get_extended_attention_mask(image_masks, image_masks.size(), device)
text_embeds, image_embeds = (
text_embeds + self.token_type_embeddings(torch.zeros_like(text_masks)),
image_embeds
+ self.token_type_embeddings(
torch.full_like(image_masks, 1)
),
)
x, y = text_embeds, image_embeds
t2v_mt = []
for text_layer, image_layer in zip(self.cross_modal_text_layers, self.cross_modal_image_layers):
x1 = text_layer(x, y, extend_text_masks, extend_image_masks, output_attentions=True)
y1 = image_layer(y, x, extend_image_masks, extend_text_masks, output_attentions=True)
x, y = x1[0], y1[0]
t2v_mt.append(x1[1][0,:,1:-1,1:])
return t2v_mt
if __name__ == '__main__':
size = 288
tokenizer = RobertaTokenizer.from_pretrained('/mnt/bn/automl-aigc/yatai/data/pretrained_weight/roberta-base')
t1 = transforms.Resize((size, size), interpolation=PIL.Image.BICUBIC)
t2 = transforms.CenterCrop(size)
t3 = transforms.ToTensor()
t4 = transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711])
t = transforms.Resize((18, 18), interpolation=PIL.Image.BICUBIC)
# split token flag
G_ = tokenizer.tokenize('A bedroom with a bookshelf full of books.')[1][0]
_config = copy.deepcopy(_config)
_config["load_path"] = "model_path"
_config["image_size"] = 288
pl.seed_everything(_config["seed"])
model = VLmae_vis(_config).cuda()
model.eval()
score_box_list = []
score_pixel_list = []
for f in tqdm(range(1500)):
image1 = Image.open(os.path.join('ALIGN-BENCH/images', f+'.jpg'))
image = t1(image1)
image = t2(image)
image = t3(image)
image = t4(image)
image = image.unsqueeze(0).cuda()
annotations = pickle.load(open(os.path.join('ALIGN-BENCH/pkls', f+'.pkl'),'rb'))
caption = annotations['caption']
position = annotations['annotation']
encoding = tokenizer(caption)
caption_tokens = tokenizer.tokenize(caption)
text_ids = torch.tensor(encoding['input_ids']).unsqueeze(0).cuda()
text_mask = torch.tensor(encoding['attention_mask']).unsqueeze(0).cuda()
t2v_att_list = model.visualize(image, text_ids, text_mask)
att_map = t2v_att_list[-1].reshape([12, -1, size//16, size//16]).cpu().numpy().max(0)
att_map_new = att_map[0:1]
caption_tokens_new = [caption_tokens[0]]
for i in range(1, len(caption_tokens)):
if caption_tokens[i] in ['.', ',']:
continue
if caption_tokens[i].startswith(G_):
caption_tokens_new.append(caption_tokens[i][1:])
att_map_new = np.concatenate((att_map_new, att_map[i:i+1]))
else:
caption_tokens_new[-1] = caption_tokens_new[-1] + caption_tokens[i]
att_map_new[-1] = att_map_new[-1] + att_map[i]
width, height = image1.size
token_box_score = []
token_pixel_score = []
for token, region in position.items():
token_ind = 0
token_multi = token.split() # a phrase
n = len(token_multi)
try:
for i in range(len(caption_tokens_new)):
if caption_tokens_new[i].lower() == token_multi[0]:
flag = 1
for j in range(1, n):
if caption_tokens_new[i+j].lower() != token_multi[j]:
flag = 0
if flag == 1:
token_ind = i
break
except:
print(f)
att_map_token = att_map_new[token_ind]
for i in range(1, n):
att_map_token = att_map_token + att_map_new[token_ind + i]
mask_box = torch.zeros(height, width, dtype=torch.float)
mask_pixel = torch.zeros(height, width).bool()
for box in region:
x1 = int(box['bbox_mask'][0])
y1 = int(box['bbox_mask'][1])
x2 = int(box['bbox_mask'][2])
y2 = int(box['bbox_mask'][3])
mask_box[y1:y2, x1:x2] = 1.0
mask_pixel = mask_pixel + box['pixel_mask']
mask_box = mask_box.unsqueeze(0)
mask_box = t(mask_box).squeeze()
box_score = (mask_box * att_map_token).sum() / att_map_token.sum()
token_box_score.append(box_score.item())
mask_pixel = mask_pixel.float().unsqueeze(0)
mask_pixel = t(mask_pixel).squeeze()
pixel_score = (mask_pixel * att_map_token).sum() / att_map_token.sum()
token_pixel_score.append(pixel_score.item())
score_box_list.append(mean(token_box_score))
score_pixel_list.append(mean(token_pixel_score))
# print(score_box_list)
# print(score_pixel_list)
print('local', 'box_score:', mean(score_box_list), 'pixel_score:', mean(score_pixel_list))