Spaces:
Running
Running
Upload train_vqa.py
Browse files- train_vqa.py +202 -0
train_vqa.py
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from torch.utils.data import DataLoader
|
22 |
+
import torch.backends.cudnn as cudnn
|
23 |
+
import torch.distributed as dist
|
24 |
+
|
25 |
+
from models.blip_vqa import blip_vqa
|
26 |
+
import utils
|
27 |
+
from utils import cosine_lr_schedule
|
28 |
+
from data import create_dataset, create_sampler, create_loader
|
29 |
+
from data.vqa_dataset import vqa_collate_fn
|
30 |
+
from data.utils import save_result
|
31 |
+
|
32 |
+
|
33 |
+
def train(model, data_loader, optimizer, epoch, device):
|
34 |
+
# train
|
35 |
+
model.train()
|
36 |
+
|
37 |
+
metric_logger = utils.MetricLogger(delimiter=" ")
|
38 |
+
metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}'))
|
39 |
+
metric_logger.add_meter('loss', utils.SmoothedValue(window_size=1, fmt='{value:.4f}'))
|
40 |
+
|
41 |
+
header = 'Train Epoch: [{}]'.format(epoch)
|
42 |
+
print_freq = 50
|
43 |
+
|
44 |
+
for i,(image, question, answer, weights, n) in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
|
45 |
+
image, weights = image.to(device,non_blocking=True), weights.to(device,non_blocking=True)
|
46 |
+
|
47 |
+
loss = model(image, question, answer, train=True, n=n, weights=weights)
|
48 |
+
|
49 |
+
optimizer.zero_grad()
|
50 |
+
loss.backward()
|
51 |
+
optimizer.step()
|
52 |
+
|
53 |
+
metric_logger.update(loss=loss.item())
|
54 |
+
metric_logger.update(lr=optimizer.param_groups[0]["lr"])
|
55 |
+
|
56 |
+
# gather the stats from all processes
|
57 |
+
metric_logger.synchronize_between_processes()
|
58 |
+
print("Averaged stats:", metric_logger.global_avg())
|
59 |
+
return {k: "{:.3f}".format(meter.global_avg) for k, meter in metric_logger.meters.items()}
|
60 |
+
|
61 |
+
|
62 |
+
@torch.no_grad()
|
63 |
+
def evaluation(model, data_loader, device, config) :
|
64 |
+
# test
|
65 |
+
model.eval()
|
66 |
+
|
67 |
+
metric_logger = utils.MetricLogger(delimiter=" ")
|
68 |
+
header = 'Generate VQA test result:'
|
69 |
+
print_freq = 50
|
70 |
+
|
71 |
+
result = []
|
72 |
+
|
73 |
+
if config['inference']=='rank':
|
74 |
+
answer_list = data_loader.dataset.answer_list
|
75 |
+
answer_candidates = model.tokenizer(answer_list, padding='longest', return_tensors='pt').to(device)
|
76 |
+
answer_candidates.input_ids[:,0] = model.tokenizer.bos_token_id
|
77 |
+
|
78 |
+
for n, (image, question, question_id) in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
|
79 |
+
image = image.to(device,non_blocking=True)
|
80 |
+
|
81 |
+
if config['inference']=='generate':
|
82 |
+
answers = model(image, question, train=False, inference='generate')
|
83 |
+
|
84 |
+
for answer, ques_id in zip(answers, question_id):
|
85 |
+
ques_id = int(ques_id.item())
|
86 |
+
result.append({"question_id":ques_id, "answer":answer})
|
87 |
+
|
88 |
+
elif config['inference']=='rank':
|
89 |
+
answer_ids = model(image, question, answer_candidates, train=False, inference='rank', k_test=config['k_test'])
|
90 |
+
|
91 |
+
for ques_id, answer_id in zip(question_id, answer_ids):
|
92 |
+
result.append({"question_id":int(ques_id.item()), "answer":answer_list[answer_id]})
|
93 |
+
|
94 |
+
return result
|
95 |
+
|
96 |
+
|
97 |
+
def main(args, config):
|
98 |
+
utils.init_distributed_mode(args)
|
99 |
+
|
100 |
+
device = torch.device(args.device)
|
101 |
+
|
102 |
+
# fix the seed for reproducibility
|
103 |
+
seed = args.seed + utils.get_rank()
|
104 |
+
torch.manual_seed(seed)
|
105 |
+
np.random.seed(seed)
|
106 |
+
random.seed(seed)
|
107 |
+
cudnn.benchmark = True
|
108 |
+
|
109 |
+
#### Dataset ####
|
110 |
+
print("Creating vqa datasets")
|
111 |
+
datasets = create_dataset('vqa', config)
|
112 |
+
|
113 |
+
if args.distributed:
|
114 |
+
num_tasks = utils.get_world_size()
|
115 |
+
global_rank = utils.get_rank()
|
116 |
+
samplers = create_sampler(datasets, [True, False], num_tasks, global_rank)
|
117 |
+
else:
|
118 |
+
samplers = [None, None]
|
119 |
+
|
120 |
+
train_loader, test_loader = create_loader(datasets,samplers,
|
121 |
+
batch_size=[config['batch_size_train'],config['batch_size_test']],
|
122 |
+
num_workers=[4,4],is_trains=[True, False],
|
123 |
+
collate_fns=[vqa_collate_fn,None])
|
124 |
+
#### Model ####
|
125 |
+
print("Creating model")
|
126 |
+
model = blip_vqa(pretrained=config['pretrained'], image_size=config['image_size'],
|
127 |
+
vit=config['vit'], vit_grad_ckpt=config['vit_grad_ckpt'], vit_ckpt_layer=config['vit_ckpt_layer'])
|
128 |
+
|
129 |
+
model = model.to(device)
|
130 |
+
|
131 |
+
model_without_ddp = model
|
132 |
+
if args.distributed:
|
133 |
+
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
|
134 |
+
model_without_ddp = model.module
|
135 |
+
|
136 |
+
optimizer = torch.optim.AdamW(params=model.parameters(), lr=config['init_lr'], weight_decay=config['weight_decay'])
|
137 |
+
|
138 |
+
best = 0
|
139 |
+
best_epoch = 0
|
140 |
+
|
141 |
+
print("Start training")
|
142 |
+
start_time = time.time()
|
143 |
+
for epoch in range(0, config['max_epoch']):
|
144 |
+
if not args.evaluate:
|
145 |
+
if args.distributed:
|
146 |
+
train_loader.sampler.set_epoch(epoch)
|
147 |
+
|
148 |
+
cosine_lr_schedule(optimizer, epoch, config['max_epoch'], config['init_lr'], config['min_lr'])
|
149 |
+
|
150 |
+
train_stats = train(model, train_loader, optimizer, epoch, device)
|
151 |
+
|
152 |
+
else:
|
153 |
+
break
|
154 |
+
|
155 |
+
if utils.is_main_process():
|
156 |
+
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},
|
157 |
+
'epoch': epoch,
|
158 |
+
}
|
159 |
+
with open(os.path.join(args.output_dir, "log.txt"),"a") as f:
|
160 |
+
f.write(json.dumps(log_stats) + "\n")
|
161 |
+
|
162 |
+
save_obj = {
|
163 |
+
'model': model_without_ddp.state_dict(),
|
164 |
+
'optimizer': optimizer.state_dict(),
|
165 |
+
'config': config,
|
166 |
+
'epoch': epoch,
|
167 |
+
}
|
168 |
+
torch.save(save_obj, os.path.join(args.output_dir, 'checkpoint_%02d.pth'%epoch))
|
169 |
+
|
170 |
+
dist.barrier()
|
171 |
+
|
172 |
+
vqa_result = evaluation(model_without_ddp, test_loader, device, config)
|
173 |
+
result_file = save_result(vqa_result, args.result_dir, 'vqa_result')
|
174 |
+
|
175 |
+
total_time = time.time() - start_time
|
176 |
+
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
177 |
+
print('Training time {}'.format(total_time_str))
|
178 |
+
|
179 |
+
|
180 |
+
|
181 |
+
if __name__ == '__main__':
|
182 |
+
parser = argparse.ArgumentParser()
|
183 |
+
parser.add_argument('--config', default='./configs/vqa.yaml')
|
184 |
+
parser.add_argument('--output_dir', default='output/VQA')
|
185 |
+
parser.add_argument('--evaluate', action='store_true')
|
186 |
+
parser.add_argument('--device', default='cuda')
|
187 |
+
parser.add_argument('--seed', default=42, type=int)
|
188 |
+
parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes')
|
189 |
+
parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training')
|
190 |
+
parser.add_argument('--distributed', default=True, type=bool)
|
191 |
+
args = parser.parse_args()
|
192 |
+
|
193 |
+
config = yaml.load(open(args.config, 'r'), Loader=yaml.Loader)
|
194 |
+
|
195 |
+
args.result_dir = os.path.join(args.output_dir, 'result')
|
196 |
+
|
197 |
+
Path(args.output_dir).mkdir(parents=True, exist_ok=True)
|
198 |
+
Path(args.result_dir).mkdir(parents=True, exist_ok=True)
|
199 |
+
|
200 |
+
yaml.dump(config, open(os.path.join(args.output_dir, 'config.yaml'), 'w'))
|
201 |
+
|
202 |
+
main(args, config)
|