doevent commited on
Commit
3c7e686
1 Parent(s): b4565f8

Upload train_nlvr.py

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