doevent commited on
Commit
b4565f8
1 Parent(s): 18beb92

Upload train_caption.py

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