-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathT5VisionModelPredictionHeadBAN.py
165 lines (128 loc) · 6.91 KB
/
T5VisionModelPredictionHeadBAN.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
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from architectures.T5VisionModel import T5VisionModel
from network.connect import FCNet
from network.connect import BCNet
from torch.nn.utils.weight_norm import weight_norm
from matplotlib import pyplot as plt
# Bilinear Attention
class BiAttention(nn.Module):
def __init__(self, x_dim, y_dim, z_dim, glimpse, dropout=[.2,.5]): #128, 1024, 1024,2
super(BiAttention, self).__init__()
self.glimpse = glimpse
self.logits = weight_norm(BCNet(x_dim, y_dim, z_dim, glimpse, dropout=dropout, k=3),
name='h_mat', dim=None)
def forward(self, v, q, v_mask=True): # v:32,1,128; q:32,12,1024
"""
v: [batch, k, vdim]
q: [batch, qdim]
"""
v_num = v.size(1)
q_num = q.size(1)
logits = self.logits(v, q) # b x g x v x q
#print(v_num, q_num, logits.shape)
if v_mask:
mask = (0 == v.abs().sum(2)).unsqueeze(1).unsqueeze(3).expand(logits.size())
#print(mask.shape, v.shape)
logits.data.masked_fill_(mask.data, -float('inf'))
p = nn.functional.softmax(logits.view(-1, self.glimpse, v_num * q_num), 2)
return p.view(-1, self.glimpse, v_num, q_num), logits
class BiResNet(nn.Module):
def __init__(self, v_dim, q_dim, glimpse):
super(BiResNet,self).__init__()
# Optional module: counter
# use_counter = cfg.TRAIN.ATTENTION.USE_COUNTER if priotize_using_counter is None else priotize_using_counter
# if use_counter or priotize_using_counter:
# objects = 10 # minimum number of boxes
# if use_counter or priotize_using_counter:
# counter = Counter(objects)
# else:
# counter = None
# # init Bilinear residual network
self.glimpse = glimpse
b_net = [] # bilinear connect : (XTU)T A (YTV)
q_prj = [] # output of bilinear connect + original question-> new question Wq_ +q
c_prj = []
for i in range(self.glimpse):
b_net.append(BCNet(v_dim, q_dim, q_dim, None, k=1))
q_prj.append(FCNet([q_dim, q_dim], '', .2))
# if use_counter or priotize_using_counter:
# c_prj.append(FCNet([objects + 1, cfg.TRAIN.QUESTION.HID_DIM], 'ReLU', .0))
self.b_net = nn.ModuleList(b_net)
self.q_prj = nn.ModuleList(q_prj)
self.c_prj = nn.ModuleList(c_prj)
def forward(self, v_emb, q_emb, att_p):
b_emb = [0] * self.glimpse
for g in range(self.glimpse):
b_emb[g] = self.b_net[g].forward_with_weights(v_emb, q_emb, att_p[:,g,:,:]) # b x l x h
# atten, _ = logits[:,g,:,:].max(2)
q_emb = self.q_prj[g](b_emb[g].unsqueeze(1)) + q_emb
#print(q_emb.shape, q_emb.sum(1).shape)
return q_emb.sum(1)
class T5VisionModelPredictionHeadBAN(T5VisionModel):
def __init__(self, device, num_classes, vision_encoder = "ViT-B/32", T5_version = "t5-small", max_source_length = 512, max_target_length = 128, use_image_info=True, vision_checkpoint=None, mapping_checkpoint=None, glimpse = 10, retrieval_function=None, use_quantifier = True):
super().__init__(device, vision_encoder = vision_encoder, T5_version = T5_version, max_source_length = max_source_length, max_target_length = max_target_length, use_image_info=use_image_info, vision_checkpoint=vision_checkpoint, mapping_checkpoint=mapping_checkpoint, retrieval_function=retrieval_function, use_quantifier=use_quantifier)
self.loss_fn = torch.nn.CrossEntropyLoss()
self.num_classes = num_classes
self.BAN_att = BiAttention(512, 512, 512, 10)
self.BAN_resnet = BiResNet(512, 512, 10)
self.prediction_head = nn.Linear(512, self.num_classes)
self.prediction_dropout = nn.Dropout(0.1)
def predict(self, batch):
question_embedding, image_embeddings, attention_mask, _ = self.prepare_input(batch)
target_encoding = self.tokenizer(
batch['answer'], padding="longest", max_length=self.max_target_length, truncation=True
)
labels = target_encoding.input_ids
labels = torch.tensor(labels)
labels[labels == self.tokenizer.pad_token_id] = -100
labels = labels.to(self.device)
output = self.T5_model(inputs_embeds = question_embedding, attention_mask=attention_mask, labels=labels)
question_features = output['encoder_last_hidden_state']
image_features = image_embeddings
attn, _ = self.BAN_att(image_features, question_features)
resnet_output = self.BAN_resnet(image_features,question_features,attn)
dropped = self.prediction_dropout(resnet_output)
logits = self.prediction_head(dropped)
predictions = torch.argmax(logits, dim = 1)
return predictions
def prepare_input(self, batch):
task_prefixes = [f"Answer the {x} question: " for x in batch['task']]
image_embeddings = self.vision_model.visual(batch["image"].to(self.device))
input_sentences = [task_prefixes[i] + batch['question'][i] for i in range(len(batch['question']))]
encoding = self.tokenizer(
input_sentences,
padding="longest",
max_length=self.max_source_length,
truncation=True,
return_tensors="pt",
)
question_embedding = self.T5_model.shared(encoding["input_ids"].to(self.device))
attention_mask = encoding.attention_mask.to(self.device)
question_embedding.to(self.device)
norm = question_embedding.pow(2).sum(keepdim=True, dim=2).sqrt()
question_embedding = question_embedding / norm
norm = image_embeddings.pow(2).sum(keepdim=True, dim=2).sqrt()
image_embeddings = image_embeddings / norm
return question_embedding, image_embeddings, attention_mask, encoding
def forward(self, batch):
question_embedding, image_embeddings, attention_mask, _ = self.prepare_input(batch)
target_encoding = self.tokenizer(
batch['answer'], padding="longest", max_length=self.max_target_length, truncation=True
)
labels = target_encoding.input_ids
labels = torch.tensor(labels)
labels[labels == self.tokenizer.pad_token_id] = -100
labels = labels.to(self.device)
#print(batch['labels'])
output = self.T5_model(inputs_embeds = question_embedding, attention_mask=attention_mask, labels=labels)
#print(output['encoder_last_hidden_state'].shape)
question_features = output['encoder_last_hidden_state']
image_features = image_embeddings
attn, _ = self.BAN_att(image_features, question_features)
resnet_output = self.BAN_resnet(image_features,question_features,attn)
dropped = self.prediction_dropout(resnet_output)
logits = self.prediction_head(dropped)
return self.loss_fn(logits, batch['label'].to(self.device))