Spaces:
Running
Running
Upload pretrain.py
Browse files- pretrain.py +173 -0
pretrain.py
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_pretrain import blip_pretrain
|
26 |
+
import utils
|
27 |
+
from utils import warmup_lr_schedule, step_lr_schedule
|
28 |
+
from data import create_dataset, create_sampler, create_loader
|
29 |
+
|
30 |
+
def train(model, data_loader, optimizer, epoch, device, config):
|
31 |
+
# train
|
32 |
+
model.train()
|
33 |
+
|
34 |
+
metric_logger = utils.MetricLogger(delimiter=" ")
|
35 |
+
metric_logger.add_meter('lr', utils.SmoothedValue(window_size=50, fmt='{value:.6f}'))
|
36 |
+
metric_logger.add_meter('loss_ita', utils.SmoothedValue(window_size=50, fmt='{value:.4f}'))
|
37 |
+
metric_logger.add_meter('loss_itm', utils.SmoothedValue(window_size=50, fmt='{value:.4f}'))
|
38 |
+
metric_logger.add_meter('loss_lm', utils.SmoothedValue(window_size=50, fmt='{value:.4f}'))
|
39 |
+
|
40 |
+
header = 'Train Epoch: [{}]'.format(epoch)
|
41 |
+
print_freq = 50
|
42 |
+
|
43 |
+
if config['laion_path']:
|
44 |
+
data_loader.dataset.reload_laion(epoch)
|
45 |
+
|
46 |
+
data_loader.sampler.set_epoch(epoch)
|
47 |
+
|
48 |
+
for i, (image, caption) in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
|
49 |
+
|
50 |
+
if epoch==0:
|
51 |
+
warmup_lr_schedule(optimizer, i, config['warmup_steps'], config['warmup_lr'], config['init_lr'])
|
52 |
+
|
53 |
+
optimizer.zero_grad()
|
54 |
+
|
55 |
+
image = image.to(device,non_blocking=True)
|
56 |
+
|
57 |
+
# ramp up alpha in the first 2 epochs
|
58 |
+
alpha = config['alpha']*min(1,(epoch*len(data_loader)+i)/(2*len(data_loader)))
|
59 |
+
|
60 |
+
loss_ita, loss_itm, loss_lm = model(image, caption, alpha = alpha)
|
61 |
+
loss = loss_ita + loss_itm + loss_lm
|
62 |
+
|
63 |
+
loss.backward()
|
64 |
+
optimizer.step()
|
65 |
+
|
66 |
+
metric_logger.update(loss_ita=loss_ita.item())
|
67 |
+
metric_logger.update(loss_itm=loss_itm.item())
|
68 |
+
metric_logger.update(loss_lm=loss_lm.item())
|
69 |
+
metric_logger.update(lr=optimizer.param_groups[0]["lr"])
|
70 |
+
|
71 |
+
|
72 |
+
# gather the stats from all processes
|
73 |
+
metric_logger.synchronize_between_processes()
|
74 |
+
print("Averaged stats:", metric_logger.global_avg())
|
75 |
+
return {k: "{:.3f}".format(meter.global_avg) for k, meter in metric_logger.meters.items()}
|
76 |
+
|
77 |
+
|
78 |
+
def main(args, config):
|
79 |
+
utils.init_distributed_mode(args)
|
80 |
+
|
81 |
+
device = torch.device(args.device)
|
82 |
+
|
83 |
+
# fix the seed for reproducibility
|
84 |
+
seed = args.seed + utils.get_rank()
|
85 |
+
torch.manual_seed(seed)
|
86 |
+
np.random.seed(seed)
|
87 |
+
random.seed(seed)
|
88 |
+
cudnn.benchmark = True
|
89 |
+
|
90 |
+
#### Dataset ####
|
91 |
+
print("Creating dataset")
|
92 |
+
datasets = [create_dataset('pretrain', config, min_scale=0.2)]
|
93 |
+
print('number of training samples: %d'%len(datasets[0]))
|
94 |
+
|
95 |
+
num_tasks = utils.get_world_size()
|
96 |
+
global_rank = utils.get_rank()
|
97 |
+
samplers = create_sampler(datasets, [True], num_tasks, global_rank)
|
98 |
+
|
99 |
+
data_loader = create_loader(datasets,samplers,batch_size=[config['batch_size']], num_workers=[4], is_trains=[True], collate_fns=[None])[0]
|
100 |
+
|
101 |
+
#### Model ####
|
102 |
+
print("Creating model")
|
103 |
+
model = blip_pretrain(image_size=config['image_size'], vit=config['vit'], vit_grad_ckpt=config['vit_grad_ckpt'],
|
104 |
+
vit_ckpt_layer=config['vit_ckpt_layer'], queue_size=config['queue_size'])
|
105 |
+
|
106 |
+
model = model.to(device)
|
107 |
+
|
108 |
+
optimizer = torch.optim.AdamW(params=model.parameters(), lr=config['init_lr'], weight_decay=config['weight_decay'])
|
109 |
+
|
110 |
+
start_epoch = 0
|
111 |
+
if args.checkpoint:
|
112 |
+
checkpoint = torch.load(args.checkpoint, map_location='cpu')
|
113 |
+
state_dict = checkpoint['model']
|
114 |
+
model.load_state_dict(state_dict)
|
115 |
+
|
116 |
+
optimizer.load_state_dict(checkpoint['optimizer'])
|
117 |
+
start_epoch = checkpoint['epoch']+1
|
118 |
+
print('resume checkpoint from %s'%args.checkpoint)
|
119 |
+
|
120 |
+
model_without_ddp = model
|
121 |
+
if args.distributed:
|
122 |
+
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
|
123 |
+
model_without_ddp = model.module
|
124 |
+
|
125 |
+
print("Start training")
|
126 |
+
start_time = time.time()
|
127 |
+
for epoch in range(start_epoch, config['max_epoch']):
|
128 |
+
|
129 |
+
step_lr_schedule(optimizer, epoch, config['init_lr'], config['min_lr'], config['lr_decay_rate'])
|
130 |
+
|
131 |
+
train_stats = train(model, data_loader, optimizer, epoch, device, config)
|
132 |
+
if utils.is_main_process():
|
133 |
+
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},
|
134 |
+
'epoch': epoch,
|
135 |
+
}
|
136 |
+
save_obj = {
|
137 |
+
'model': model_without_ddp.state_dict(),
|
138 |
+
'optimizer': optimizer.state_dict(),
|
139 |
+
'config': config,
|
140 |
+
'epoch': epoch,
|
141 |
+
}
|
142 |
+
torch.save(save_obj, os.path.join(args.output_dir, 'checkpoint_%02d.pth'%epoch))
|
143 |
+
|
144 |
+
with open(os.path.join(args.output_dir, "log.txt"),"a") as f:
|
145 |
+
f.write(json.dumps(log_stats) + "\n")
|
146 |
+
|
147 |
+
dist.barrier()
|
148 |
+
|
149 |
+
total_time = time.time() - start_time
|
150 |
+
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
151 |
+
print('Training time {}'.format(total_time_str))
|
152 |
+
|
153 |
+
|
154 |
+
if __name__ == '__main__':
|
155 |
+
parser = argparse.ArgumentParser()
|
156 |
+
parser.add_argument('--config', default='./configs/pretrain.yaml')
|
157 |
+
parser.add_argument('--output_dir', default='output/Pretrain')
|
158 |
+
parser.add_argument('--checkpoint', default='')
|
159 |
+
parser.add_argument('--evaluate', action='store_true')
|
160 |
+
parser.add_argument('--device', default='cuda')
|
161 |
+
parser.add_argument('--seed', default=42, type=int)
|
162 |
+
parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes')
|
163 |
+
parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training')
|
164 |
+
parser.add_argument('--distributed', default=True, type=bool)
|
165 |
+
args = parser.parse_args()
|
166 |
+
|
167 |
+
config = yaml.load(open(args.config, 'r'), Loader=yaml.Loader)
|
168 |
+
|
169 |
+
Path(args.output_dir).mkdir(parents=True, exist_ok=True)
|
170 |
+
|
171 |
+
yaml.dump(config, open(os.path.join(args.output_dir, 'config.yaml'), 'w'))
|
172 |
+
|
173 |
+
main(args, config)
|