yfyangd commited on
Commit
74ec059
·
1 Parent(s): eeece1a

Upload eval_retrieval_video.py

Browse files
Files changed (1) hide show
  1. BLIP/eval_retrieval_video.py +250 -0
BLIP/eval_retrieval_video.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 argparse
9
+ import os
10
+ import ruamel_yaml as yaml
11
+ import numpy as np
12
+ import random
13
+ import time
14
+ import datetime
15
+ import json
16
+ from pathlib import Path
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ import torch.backends.cudnn as cudnn
22
+ import torch.distributed as dist
23
+ from torch.utils.data import DataLoader
24
+
25
+ from models.blip_retrieval import blip_retrieval
26
+ import utils
27
+ from data.video_dataset import VideoDataset
28
+
29
+
30
+ @torch.no_grad()
31
+ def evaluation(model, data_loader, tokenizer, device, config):
32
+ # test
33
+ model.eval()
34
+
35
+ metric_logger = utils.MetricLogger(delimiter=" ")
36
+ header = 'Evaluation:'
37
+
38
+ print('Computing features for evaluation...')
39
+ start_time = time.time()
40
+
41
+ texts = data_loader.dataset.text
42
+ num_text = len(texts)
43
+ text_bs = 256
44
+ text_ids = []
45
+ text_embeds = []
46
+ text_atts = []
47
+ for i in range(0, num_text, text_bs):
48
+ text = texts[i: min(num_text, i+text_bs)]
49
+ text_input = tokenizer(text, padding='max_length', truncation=True, max_length=35, return_tensors="pt").to(device)
50
+ text_output = model.text_encoder(text_input.input_ids, attention_mask = text_input.attention_mask, mode='text')
51
+ text_embed = F.normalize(model.text_proj(text_output.last_hidden_state[:,0,:]))
52
+ text_embeds.append(text_embed)
53
+ text_ids.append(text_input.input_ids)
54
+ text_atts.append(text_input.attention_mask)
55
+
56
+ text_embeds = torch.cat(text_embeds,dim=0)
57
+ text_ids = torch.cat(text_ids,dim=0)
58
+ text_atts = torch.cat(text_atts,dim=0)
59
+ text_ids[:,0] = tokenizer.additional_special_tokens_ids[0]
60
+
61
+ video_feats = []
62
+ video_embeds = []
63
+ for video, video_id in data_loader:
64
+
65
+ B,N,C,W,H = video.size()
66
+ video = video.view(-1,C,W,H)
67
+ video = video.to(device,non_blocking=True)
68
+ video_feat = model.visual_encoder(video)
69
+ video_embed = model.vision_proj(video_feat[:,0,:])
70
+ video_embed = video_embed.view(B,N,-1).mean(dim=1)
71
+ video_embed = F.normalize(video_embed,dim=-1)
72
+
73
+ video_feat = video_feat.view(B,-1,video_feat.shape[-1])
74
+ video_feats.append(video_feat.cpu())
75
+ video_embeds.append(video_embed)
76
+
77
+ video_feats = torch.cat(video_feats,dim=0)
78
+ video_embeds = torch.cat(video_embeds,dim=0)
79
+
80
+ sims_matrix = video_embeds @ text_embeds.t()
81
+ score_matrix_v2t = torch.full((len(texts),len(texts)),-100.0).to(device)
82
+
83
+ num_tasks = utils.get_world_size()
84
+ rank = utils.get_rank()
85
+ step = sims_matrix.size(0)//num_tasks + 1
86
+ start = rank*step
87
+ end = min(sims_matrix.size(0),start+step)
88
+
89
+ for i,sims in enumerate(metric_logger.log_every(sims_matrix[start:end], 50, header)):
90
+ topk_sim, topk_idx = sims.topk(k=config['k_test'], dim=0)
91
+
92
+ encoder_output = video_feats[start+i].repeat(config['k_test'],1,1).to(device,non_blocking=True)
93
+ encoder_att = torch.ones(encoder_output.size()[:-1],dtype=torch.long).to(device,non_blocking=True)
94
+ output = model.text_encoder(text_ids[topk_idx],
95
+ attention_mask = text_atts[topk_idx],
96
+ encoder_hidden_states = encoder_output,
97
+ encoder_attention_mask = encoder_att,
98
+ return_dict = True,
99
+ )
100
+ score = model.itm_head(output.last_hidden_state[:,0,:])[:,1]
101
+ score_matrix_v2t[start+i,topk_idx] = score + topk_sim
102
+
103
+ sims_matrix = sims_matrix.t()
104
+ score_matrix_t2v = torch.full((len(texts),len(texts)),-100.0).to(device)
105
+
106
+ step = sims_matrix.size(0)//num_tasks + 1
107
+ start = rank*step
108
+ end = min(sims_matrix.size(0),start+step)
109
+
110
+ for i,sims in enumerate(metric_logger.log_every(sims_matrix[start:end], 50, header)):
111
+
112
+ topk_sim, topk_idx = sims.topk(k=config['k_test'], dim=0)
113
+ encoder_output = video_feats[topk_idx].to(device,non_blocking=True)
114
+ encoder_att = torch.ones(encoder_output.size()[:-1],dtype=torch.long).to(device,non_blocking=True)
115
+ output = model.text_encoder(text_ids[start+i].repeat(config['k_test'],1),
116
+ attention_mask = text_atts[start+i].repeat(config['k_test'],1),
117
+ encoder_hidden_states = encoder_output,
118
+ encoder_attention_mask = encoder_att,
119
+ return_dict = True,
120
+ )
121
+ score = model.itm_head(output.last_hidden_state[:,0,:])[:,1]
122
+ score_matrix_t2v[start+i,topk_idx] = score + topk_sim
123
+
124
+ if args.distributed:
125
+ dist.barrier()
126
+ torch.distributed.all_reduce(score_matrix_v2t, op=torch.distributed.ReduceOp.SUM)
127
+ torch.distributed.all_reduce(score_matrix_t2v, op=torch.distributed.ReduceOp.SUM)
128
+
129
+ total_time = time.time() - start_time
130
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
131
+ print('Evaluation time {}'.format(total_time_str))
132
+
133
+ return score_matrix_v2t.cpu().numpy(), score_matrix_t2v.cpu().numpy()
134
+
135
+
136
+
137
+ @torch.no_grad()
138
+ def itm_eval(scores_v2t, scores_t2v, txt2vmg, vid2txt):
139
+
140
+ #Video->Text
141
+ ranks = np.zeros(scores_v2t.shape[0])
142
+ for index,score in enumerate(scores_v2t):
143
+ inds = np.argsort(score)[::-1]
144
+ ranks[index] = np.where(inds == vid2txt[index])[0][0]
145
+
146
+ # Compute metrics
147
+ tr1 = 100.0 * len(np.where(ranks < 1)[0]) / len(ranks)
148
+ tr5 = 100.0 * len(np.where(ranks < 5)[0]) / len(ranks)
149
+ tr10 = 100.0 * len(np.where(ranks < 10)[0]) / len(ranks)
150
+
151
+ #Text->Video
152
+ ranks = np.zeros(scores_t2v.shape[0])
153
+
154
+ for index,score in enumerate(scores_t2v):
155
+ inds = np.argsort(score)[::-1]
156
+ ranks[index] = np.where(inds == txt2vmg[index])[0][0]
157
+
158
+ mdR = np.median(ranks+1)
159
+
160
+ # Compute metrics
161
+ vr1 = 100.0 * len(np.where(ranks < 1)[0]) / len(ranks)
162
+ vr5 = 100.0 * len(np.where(ranks < 5)[0]) / len(ranks)
163
+ vr10 = 100.0 * len(np.where(ranks < 10)[0]) / len(ranks)
164
+
165
+ tr_mean = (tr1 + tr5 + tr10) / 3
166
+ vr_mean = (vr1 + vr5 + vr10) / 3
167
+ r_mean = (tr_mean + vr_mean) / 2
168
+
169
+ eval_result = {'txt_r1': tr1,
170
+ 'txt_r5': tr5,
171
+ 'txt_r10': tr10,
172
+ 'txt_r_mean': tr_mean,
173
+ 'vid_r1': vr1,
174
+ 'vid_r5': vr5,
175
+ 'vid_r10': vr10,
176
+ 'vid_r_mean': vr_mean,
177
+ 'vid_mdR': mdR,
178
+ 'r_mean': r_mean}
179
+ return eval_result
180
+
181
+
182
+
183
+
184
+ def main(args, config):
185
+ utils.init_distributed_mode(args)
186
+
187
+ device = torch.device(args.device)
188
+
189
+ # fix the seed for reproducibility
190
+ seed = args.seed + utils.get_rank()
191
+ torch.manual_seed(seed)
192
+ np.random.seed(seed)
193
+ random.seed(seed)
194
+ cudnn.benchmark = True
195
+
196
+ #### Dataset ####
197
+ print("Creating retrieval dataset")
198
+ test_dataset = VideoDataset(config['video_root'],config['ann_root'],num_frm=config['num_frm_test'],
199
+ max_img_size=config['image_size'], frm_sampling_strategy='uniform')
200
+
201
+ test_loader = DataLoader(
202
+ test_dataset,
203
+ batch_size=config['batch_size'],
204
+ num_workers=4,
205
+ pin_memory=True,
206
+ drop_last=False,
207
+ shuffle=False,
208
+ )
209
+
210
+ #### Model ####
211
+ print("Creating model")
212
+ model = blip_retrieval(pretrained=config['pretrained'], image_size=config['image_size'], vit=config['vit'])
213
+
214
+ model = model.to(device)
215
+
216
+ model_without_ddp = model
217
+ if args.distributed:
218
+ model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
219
+ model_without_ddp = model.module
220
+
221
+ score_v2t, score_t2v, = evaluation(model_without_ddp, test_loader, model_without_ddp.tokenizer, device, config)
222
+
223
+ if utils.is_main_process():
224
+
225
+ test_result = itm_eval(score_v2t, score_t2v, test_loader.dataset.txt2video, test_loader.dataset.video2txt)
226
+ print(test_result)
227
+
228
+ log_stats = {**{f'{k}': v for k, v in test_result.items()},}
229
+ with open(os.path.join(args.output_dir, "test_result.txt"),"a") as f:
230
+ f.write(json.dumps(log_stats) + "\n")
231
+
232
+
233
+ if __name__ == '__main__':
234
+ parser = argparse.ArgumentParser()
235
+ parser.add_argument('--config', default='./configs/retrieval_msrvtt.yaml')
236
+ parser.add_argument('--output_dir', default='output/Retrieval_msrvtt')
237
+ parser.add_argument('--device', default='cuda')
238
+ parser.add_argument('--seed', default=42, type=int)
239
+ parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes')
240
+ parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training')
241
+ parser.add_argument('--distributed', default=True, type=bool)
242
+ args = parser.parse_args()
243
+
244
+ config = yaml.load(open(args.config, 'r'), Loader=yaml.Loader)
245
+
246
+ Path(args.output_dir).mkdir(parents=True, exist_ok=True)
247
+
248
+ yaml.dump(config, open(os.path.join(args.output_dir, 'config.yaml'), 'w'))
249
+
250
+ main(args, config)