-
Notifications
You must be signed in to change notification settings - Fork 11
/
main_qamc_mlm.py
275 lines (234 loc) · 9.72 KB
/
main_qamc_mlm.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
from utils.lib import *
from main_qamc_task_specific import (
LAVENDER_QAMC_TS, Dataset_QAMC_TS, Agent_QAMC_TS)
from dataset import get_tsv_dls
from utils.args import get_args
from utils.logger import LOGGER, add_log_to_file
from utils.dist import (
NoOp, is_main_process,
get_rank, get_world_size, iter_tqdm, all_gather)
class Dataset_QAMC_MLM(Dataset_QAMC_TS):
def __init__(self, args, img_tsv_path, txt, id2lineidx, split, tokzr=None):
super().__init__(
args, img_tsv_path, txt, id2lineidx, split, tokzr)
self.ans_tok_ids = self.tokzr.convert_tokens_to_ids(
[f"{i}" for i in range(self.args.size_option)])
def append_mask(self, tokens, padding_len):
tokens = [self.tokzr.cls_token] + tokens + [self.tokzr.mask_token] + [
self.tokzr.sep_token] + [self.tokzr.pad_token] * (padding_len)
return tokens
def prepend_mask(self, tokens, padding_len):
tokens = [self.tokzr.mask_token, self.tokzr.cls_token] + tokens + [
self.tokzr.sep_token
] + [self.tokzr.pad_token] * (padding_len)
return tokens
def replace_cls(self, tokens, padding_len):
tokens = [self.tokzr.mask_token] + tokens + [
self.tokzr.sep_token
] + [self.tokzr.pad_token] * (padding_len)
return tokens
def insert_mask(self, tokens, padding_len):
tokens = [self.tokzr.cls_token] + tokens + [
self.tokzr.sep_token
] + [self.tokzr.pad_token] * (padding_len)
if len(tokens) < 10:
tokens += [self.tokzr.mask_token]
else:
tokens = tokens[:10] + [self.tokzr.mask_token] + tokens[10:]
return tokens
def str2txt(self, s):
# txt, mask = super().str2txt(s)
# txt, mask = self.append_mask_tok2txt(txt, mask)
# return txt, mask
tokens = self.tokzr.tokenize(s)
tokens = tokens[:self.args.size_txt-1]
padding_len = self.args.size_txt - len(tokens)
if self.args.mask_pos == "append":
tokens = self.append_mask(tokens, padding_len)
elif self.args.mask_pos == "prepend":
tokens = self.prepend_mask(tokens, padding_len)
elif self.args.mask_pos == "insert":
tokens = self.insert_mask(tokens, padding_len)
elif self.args.mask_pos == "replace":
tokens = self.replace_cls(tokens, padding_len)
txt = self.tokzr.convert_tokens_to_ids(tokens)
mask = [1 if w != self.pad_token_id else 0 for w in txt]
mask = T.LongTensor(mask)
txt = T.LongTensor(txt)
return txt, mask
def __getitem__(self, idx):
item = self.txt[idx]
video_id = item['video']
lineidx = self.id2lineidx[video_id]
b = self.seek_img_tsv(lineidx)[2:]
img = self.get_img_or_video(b)
ans_idx = item['answer']
ans_tok_id = self.tokzr.convert_tokens_to_ids([f"{ans_idx}"])[0]
question = item['question']
for i in range(self.args.size_option):
answer = item[f'option_{i}']
answer = f"option {i}: " + answer
question = self.concat_txt(question, answer)
txt, mask = self.str2txt(question)
mask_ans = T.ones(txt.shape).long() * -1
mask_ans[txt == self.mask_token_id] = ans_tok_id
return img, txt, mask, mask_ans, ans_idx
@property
def prompt_text(self):
return "which answer is correct, from " + \
f"{list(range(self.args.size_option))}?"
def collate_batch(self, inputs):
img, txt, mask, mask_ans, ans_idx = map(list, unzip(inputs))
all_imgs = T.stack(img, dim=0)
all_mask_ans = T.stack(mask_ans, dim=0)
all_txts = T.stack(txt, dim=0)
all_masks = T.stack(mask, dim=0)
ans_idx = T.LongTensor(ans_idx)
batch = {
"img": all_imgs, "txt": all_txts,
"mask": all_masks, "mask_ans": all_mask_ans,
"ans_idx": ans_idx}
return batch
class LAVENDER_QAMC_MLM(LAVENDER_QAMC_TS):
def __init__(self, args, tokzr=None):
super().__init__(args, tokzr)
bert = transformers.AutoModelForMaskedLM.from_pretrained(
self.args.tokenizer)
self.fc_mtm = bert.cls
del bert
del self.fc
self.task_tok2id = {"vtm": 0, "mc": 1, "oe": 2, "cap": 3}
self.emb_task = T.nn.Parameter(
0.02*T.randn(10, self.hidden_size))
def prepro_pretxt(self, task_or_prompt_txt):
return T.ones_like(task_or_prompt_txt) * -1
def forward(self, batch):
batch = defaultdict(lambda: None, batch)
img, txt, mask = [
batch[key] for key in ["img", "txt", "mask"]]
ans = batch["mask_ans"]
(_B, _T, _, _H, _W), (_, _X) = img.shape, txt.shape
_h, _w = _H//32, _W//32
feat_img, mask_img, feat_txt, mask_txt = self.go_feat(
img, txt, mask)
ans, mask_txt, feat_txt = self.prepro_txt_inputs(
ans, mask_txt, feat_txt, task_name=batch["task_name"],
prompt=batch["prompt"])
out, _ = self.go_cross(feat_img, mask_img, feat_txt, mask_txt)
out = self.fc_mtm(out[:, (1+_h*_w)*_T:])
return out, ans
class Agent_QAMC_MLM(Agent_QAMC_TS):
def __init__(self, args, model, ans_tok_ids):
super().__init__(args, model)
self.ans_tok_ids = ans_tok_ids
def step(self, batch, is_train):
with T.cuda.amp.autocast(enabled=not self.args.deepspeed):
out = self.forward_step(batch)
out, ans = out
if is_train:
ans = ans.flatten(0, 1)
out = out.flatten(0, len(out.shape)-2)
ans = ans.flatten(0, len(ans.shape)-1)
ls = self.loss_func(out, ans)
self.backward_step(ls)
return ls.item()
else:
_B, _ = ans.shape
p_all_ans_toks = out[:, :, self.ans_tok_ids]
ans_mtm = ans
out_mtm = p_all_ans_toks[ans_mtm != -1]
out_mtm = out_mtm / out_mtm.sum(dim=-1).view(_B, 1)
out_mtm = out_mtm.view(_B, -1)
out_mtm = T.argmax(out_mtm, dim=-1)
# ans_idx = T.LongTensor(ans_idx, device=out_mtm.device)
ans_idx = batch["ans_idx"]
ac = (out_mtm == ans_idx).float().tolist()
return ac
def go_dl(self, ep, dl, is_train):
if is_train:
self.model.train()
else:
self.model.eval()
ret = []
idx = 0
for idx, batch in enumerate(dl):
if is_train:
self.global_step += 1
if idx % self.args.logging_steps == 0 and is_train:
LOGGER.info(self.log_memory(ep, idx+1))
if self.args.enable_prompt:
batch["prompt"] = dl.dataset.get_prompt()
elif self.args.enable_task_token:
if ep == 0:
batch["task_name"] = "vtm"
else:
batch["task_name"] = self.args.task_token
batch = self.prepare_batch(batch)
curr_ret = self.step(batch=batch, is_train=is_train)
if isinstance(curr_ret, list):
ret.extend(curr_ret)
else:
ret.append(curr_ret)
if idx % self.args.logging_steps != 0 and is_train:
LOGGER.info(self.log_memory(ep, idx+1))
gathered_ret = []
for ret_per_rank in all_gather(ret):
gathered_ret.extend(ret_per_rank)
num_ex = len(gathered_ret)
ret = float(np.average(gathered_ret))
return ret
if __name__ == '__main__':
args = get_args()
tokzr = transformers.AutoTokenizer.from_pretrained(args.tokenizer)
dl_tr, dl_vl, dl_ts = get_tsv_dls(
args, Dataset_QAMC_MLM, tokzr=tokzr)
if args.size_epoch == 0 or len(dl_tr) == 0:
args.max_iter = 1
else:
args.max_iter = len(dl_tr) * args.size_epoch
model = LAVENDER_QAMC_MLM(args, tokzr=tokzr)
model.load_ckpt(args.path_ckpt)
if args.reinit_head:
model.reinit_head()
model.cuda()
if args.distributed:
LOGGER.info(f"n_gpu: {args.num_gpus}, rank: {get_rank()},"
f" world_size: {get_world_size()}")
args.path_output = '%s/_%s_%s' % (
args.path_output, args.task,
datetime.now().strftime('%Y%m%d%H%M%S'))
agent = Agent_QAMC_MLM(
args, model, dl_ts.dataset.ans_tok_ids
)
if args.distributed:
agent.prepare_dist_model()
agent.save_training_meta()
if is_main_process():
add_log_to_file('%s/stdout.txt' % (args.path_output))
else:
LOGGER = NoOp()
# DIST.barrier()
LOGGER.info("Saved training meta infomation, start training ...")
if os.path.exists(args.path_ckpt):
LOGGER.info("Zero-shot Evaluation")
ac_vl = agent.go_dl(0, dl_vl, False)
ac_ts = agent.go_dl(0, dl_ts, False)
LOGGER.info('ZS: %.2f %.2f' % (
ac_vl*100, ac_ts*100))
else:
LOGGER.info("No pre-trained weight, skip zero-shot Evaluation")
if args.size_epoch:
LOGGER.info("Start training....")
for e in iter_tqdm(range(args.size_epoch)):
ls_tr = agent.go_dl(e+1, dl_tr, True)
ac_vl = agent.go_dl(e+1, dl_vl, False)
ac_ts = agent.go_dl(e+1, dl_ts, False)
agent.log['ls_tr'].append(ls_tr)
agent.log['ac_vl'].append(ac_vl)
agent.log['ac_ts'].append(ac_ts)
LOGGER.info('Ep %d: %.6f %.2f %.2f' % (
e+1, ls_tr, ac_vl*100, ac_ts*100))
agent.save_model(e+1)
best_vl, best_ts = agent.best_epoch()
LOGGER.info(f'Best val @ ep {best_vl[0]+1}, {best_vl[1]*100:.2f}')
LOGGER.info(f'Best test @ ep {best_ts[0]+1}, {best_ts[1]*100:.2f}')