crystal-technologies commited on
Commit
8490b86
·
1 Parent(s): 25c355e

Upload vqa.py

Browse files
Files changed (1) hide show
  1. vqa.py +127 -0
vqa.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from PIL import Image
3
+ import torch
4
+ from torchvision import transforms
5
+ from torchvision.transforms.functional import InterpolationMode
6
+ from models.blip_vqa import blip_vqa
7
+ import cv2
8
+ import numpy as np
9
+ import matplotlib.image as mpimg
10
+
11
+ from skimage import transform as skimage_transform
12
+ from scipy.ndimage import filters
13
+ from matplotlib import pyplot as plt
14
+
15
+
16
+ import torch
17
+ from torch import nn
18
+ from torchvision import transforms
19
+
20
+ import json
21
+ import traceback
22
+
23
+ class VQA:
24
+ def __init__(self, model_path, image_size=480):
25
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
26
+ self.model = blip_vqa(pretrained=model_path, image_size=image_size, vit='base')
27
+ self.block_num = 9
28
+ self.model.eval()
29
+ self.model.text_encoder.base_model.base_model.encoder.layer[self.block_num].crossattention.self.save_attention = True
30
+
31
+ self.model = self.model.to(self.device)
32
+ def getAttMap(self, img, attMap, blur = True, overlap = True):
33
+ attMap -= attMap.min()
34
+ if attMap.max() > 0:
35
+ attMap /= attMap.max()
36
+ attMap = skimage_transform.resize(attMap, (img.shape[:2]), order = 3, mode = 'constant')
37
+ if blur:
38
+ attMap = filters.gaussian_filter(attMap, 0.02*max(img.shape[:2]))
39
+ attMap -= attMap.min()
40
+ attMap /= attMap.max()
41
+ cmap = plt.get_cmap('jet')
42
+ attMapV = cmap(attMap)
43
+ attMapV = np.delete(attMapV, 3, 2)
44
+ if overlap:
45
+ attMap = 1*(1-attMap**0.7).reshape(attMap.shape + (1,))*img + (attMap**0.7).reshape(attMap.shape+(1,)) * attMapV
46
+ return attMap
47
+
48
+ def gradcam(self, text_input, image_path, image):
49
+ mask = text_input.attention_mask.view(text_input.attention_mask.size(0),1,-1,1,1)
50
+ grads = self.model.text_encoder.base_model.base_model.encoder.layer[self.block_num].crossattention.self.get_attn_gradients()
51
+ cams = self.model.text_encoder.base_model.base_model.encoder.layer[self.block_num].crossattention.self.get_attention_map()
52
+ cams = cams[:, :, :, 1:].reshape(image.size(0), 12, -1, 30, 30) * mask
53
+ grads = grads[:, :, :, 1:].clamp(0).reshape(image.size(0), 12, -1, 30, 30) * mask
54
+ gradcam = cams * grads
55
+ gradcam = gradcam[0].mean(0).cpu().detach()
56
+
57
+ num_image = len(text_input.input_ids[0])
58
+ num_image -= 1
59
+ fig, ax = plt.subplots(num_image, 1, figsize=(15,15*num_image))
60
+
61
+ rgb_image = cv2.imread(image_path)[:, :, ::-1]
62
+ rgb_image = np.float32(rgb_image) / 255
63
+ ax[0].imshow(rgb_image)
64
+ ax[0].set_yticks([])
65
+ ax[0].set_xticks([])
66
+ ax[0].set_xlabel("Image")
67
+
68
+ for i,token_id in enumerate(text_input.input_ids[0][1:-1]):
69
+ word = self.model.tokenizer.decode([token_id])
70
+ gradcam_image = self.getAttMap(rgb_image, gradcam[i+1])
71
+ ax[i+1].imshow(gradcam_image)
72
+ ax[i+1].set_yticks([])
73
+ ax[i+1].set_xticks([])
74
+ ax[i+1].set_xlabel(word)
75
+
76
+ plt.show()
77
+
78
+
79
+ def load_demo_image(self, image_size, img_path, device):
80
+ raw_image = Image.open(img_path).convert('RGB')
81
+ w,h = raw_image.size
82
+ transform = transforms.Compose([
83
+ transforms.Resize((image_size,image_size),interpolation=InterpolationMode.BICUBIC),
84
+ transforms.ToTensor(),
85
+ transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
86
+ ])
87
+ image = transform(raw_image).unsqueeze(0).to(device)
88
+ return raw_image, image
89
+
90
+ def vqa(self, img_path, question):
91
+ raw_image, image = self.load_demo_image(image_size=480, img_path=img_path, device=self.device)
92
+ answer, vl_output, que = self.model(image, question, mode='gradcam', inference='generate')
93
+ loss = vl_output[:,1].sum()
94
+ self.model.zero_grad()
95
+ loss.backward()
96
+
97
+ with torch.no_grad():
98
+ self.gradcam(que, img_path, image)
99
+
100
+ return answer[0]
101
+
102
+ def vqa_demo(self, image, question):
103
+ image_size = 480
104
+ transform = transforms.Compose([
105
+ transforms.ToPILImage(),
106
+ transforms.Resize((image_size,image_size),interpolation=InterpolationMode.BICUBIC),
107
+ transforms.ToTensor(),
108
+ transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
109
+ ])
110
+ image = transform(image).unsqueeze(0).to(self.device)
111
+ answer = self.model(image, question, mode='inference', inference='generate')
112
+
113
+ return answer[0]
114
+
115
+
116
+ if __name__=="__main__":
117
+ if not len(sys.argv) == 3:
118
+ print('Format: python3 vqa.py <path_to_img> <question>')
119
+ print('Sample: python3 vqa.py sample.jpg "What is the color of the horse?"')
120
+
121
+ else:
122
+ model_path = 'checkpoints/model_base_vqa_capfilt_large.pth'
123
+ vqa_object = VQA(model_path=model_path)
124
+ img_path = sys.argv[1]
125
+ question = sys.argv[2]
126
+ answer = vqa_object.vqa(img_path, question)
127
+ print('Question: {} | Answer: {}'.format(question, answer))