-
Notifications
You must be signed in to change notification settings - Fork 11
/
train.py
executable file
·188 lines (162 loc) · 8.36 KB
/
train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
r'''
modified training script of GLU-Net
https://github.com/PruneTruong/GLU-Net
'''
import argparse
import os
import pickle
import random
import time
from os import path as osp
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
from tensorboardX import SummaryWriter
from termcolor import colored
from torch.utils.data import DataLoader
from models.cats import CATs
import utils_training.optimize as optimize
from utils_training.evaluation import Evaluator
from utils_training.utils import parse_list, load_checkpoint, save_checkpoint, boolean_string
from data import download
if __name__ == "__main__":
# Argument parsing
parser = argparse.ArgumentParser(description='CATs Training Script')
# Paths
parser.add_argument('--name_exp', type=str,
default=time.strftime('%Y_%m_%d_%H_%M'),
help='name of the experiment to save')
parser.add_argument('--snapshots', type=str, default='./snapshots')
parser.add_argument('--pretrained', dest='pretrained', default=None,
help='path to pre-trained model')
parser.add_argument('--start_epoch', type=int, default=-1,
help='start epoch')
parser.add_argument('--epochs', type=int, default=100,
help='number of training epochs')
parser.add_argument('--batch-size', type=int, default=32,
help='training batch size')
parser.add_argument('--n_threads', type=int, default=32,
help='number of parallel threads for dataloaders')
parser.add_argument('--seed', type=int, default=2021,
help='Pseudo-RNG seed')
parser.add_argument('--datapath', type=str, default='../Datasets_CATs')
parser.add_argument('--benchmark', type=str, default='spair', choices=['pfpascal', 'spair'])
parser.add_argument('--thres', type=str, default='auto', choices=['auto', 'img', 'bbox'])
parser.add_argument('--alpha', type=float, default=0.1)
parser.add_argument('--momentum', type=float, default=0.9, metavar='M',
help='SGD momentum (default: 0.9)')
parser.add_argument('--weight-decay', type=float, default=0.05,
help='weight decay (default: 0.05)')
parser.add_argument('--lr', type=float, default=3e-5, metavar='LR',
help='learning rate (default: 3e-5)')
parser.add_argument('--lr-backbone', type=float, default=3e-6, metavar='LR',
help='learning rate (default: 3e-6)')
parser.add_argument('--scheduler', type=str, default='step', choices=['step', 'cosine'])
parser.add_argument('--step', type=str, default='[70, 80, 90]')
parser.add_argument('--step_gamma', type=float, default=0.5)
parser.add_argument('--feature-size', type=int, default=16)
parser.add_argument('--feature-proj-dim', type=int, default=128)
parser.add_argument('--depth', type=int, default=1)
parser.add_argument('--num-heads', type=int, default=6)
parser.add_argument('--mlp-ratio', type=int, default=4)
parser.add_argument('--hyperpixel', type=str, default='[0,8,20,21,26,28,29,30]')
parser.add_argument('--freeze', type=boolean_string, nargs='?', const=True, default=True)
parser.add_argument('--augmentation', type=boolean_string, nargs='?', const=True, default=True)
# Seed
args = parser.parse_args()
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Initialize Evaluator
Evaluator.initialize(args.benchmark, args.alpha)
# Dataloader
download.download_dataset(args.datapath, args.benchmark)
train_dataset = download.load_dataset(args.benchmark, args.datapath, args.thres, device, 'trn', args.augmentation, args.feature_size)
val_dataset = download.load_dataset(args.benchmark, args.datapath, args.thres, device, 'val', args.augmentation, args.feature_size)
train_dataloader = DataLoader(train_dataset,
batch_size=args.batch_size,
num_workers=args.n_threads,
shuffle=True)
val_dataloader = DataLoader(val_dataset,
batch_size=args.batch_size,
num_workers=args.n_threads,
shuffle=False)
# Model
if args.freeze:
print('Backbone frozen!')
model = CATs(
feature_size=args.feature_size, feature_proj_dim=args.feature_proj_dim,
depth=args.depth, num_heads=args.num_heads, mlp_ratio=args.mlp_ratio,
hyperpixel_ids=parse_list(args.hyperpixel), freeze=args.freeze)
param_model = [param for name, param in model.named_parameters() if 'feature_extraction' not in name]
param_backbone = [param for name, param in model.named_parameters() if 'feature_extraction' in name]
# Optimizer
optimizer = optim.AdamW([{'params': param_model, 'lr': args.lr}, {'params': param_backbone, 'lr': args.lr_backbone}],
weight_decay=args.weight_decay)
# Scheduler
scheduler = \
lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs, eta_min=1e-6, verbose=True)\
if args.scheduler == 'cosine' else\
lr_scheduler.MultiStepLR(optimizer, milestones=parse_list(args.step), gamma=args.step_gamma, verbose=True)
if args.pretrained:
# reload from pre_trained_model
model, optimizer, scheduler, start_epoch, best_val = load_checkpoint(model, optimizer, scheduler,
filename=args.pretrained)
# now individually transfer the optimizer parts...
for state in optimizer.state.values():
for k, v in state.items():
if isinstance(v, torch.Tensor):
state[k] = v.to(device)
cur_snapshot = os.path.basename(os.path.dirname(args.pretrained))
else:
if not os.path.isdir(args.snapshots):
os.mkdir(args.snapshots)
cur_snapshot = args.name_exp
if not osp.isdir(osp.join(args.snapshots, cur_snapshot)):
os.makedirs(osp.join(args.snapshots, cur_snapshot))
with open(osp.join(args.snapshots, cur_snapshot, 'args.pkl'), 'wb') as f:
pickle.dump(args, f)
best_val = 0
start_epoch = 0
# create summary writer
save_path=osp.join(args.snapshots, cur_snapshot)
train_writer = SummaryWriter(os.path.join(save_path, 'train'))
test_writer = SummaryWriter(os.path.join(save_path, 'test'))
model = nn.DataParallel(model)
model = model.to(device)
train_started = time.time()
for epoch in range(start_epoch, args.epochs):
scheduler.step(epoch)
train_loss = optimize.train_epoch(model,
optimizer,
train_dataloader,
device,
epoch,
train_writer)
train_writer.add_scalar('train loss', train_loss, epoch)
train_writer.add_scalar('learning_rate', scheduler.get_lr()[0], epoch)
train_writer.add_scalar('learning_rate_backbone', scheduler.get_lr()[1], epoch)
print(colored('==> ', 'green') + 'Train average loss:', train_loss)
val_loss_grid, val_mean_pck = optimize.validate_epoch(model,
val_dataloader,
device,
epoch=epoch)
print(colored('==> ', 'blue') + 'Val average grid loss :',
val_loss_grid)
print('mean PCK is {}'.format(val_mean_pck))
print(colored('==> ', 'blue') + 'epoch :', epoch + 1)
test_writer.add_scalar('mean PCK', val_mean_pck, epoch)
test_writer.add_scalar('val loss', val_loss_grid, epoch)
is_best = val_mean_pck > best_val
best_val = max(val_mean_pck, best_val)
save_checkpoint({'epoch': epoch + 1,
'state_dict': model.module.state_dict(),
'optimizer': optimizer.state_dict(),
'scheduler': scheduler.state_dict(),
'best_loss': best_val},
is_best, save_path, 'epoch_{}.pth'.format(epoch + 1))
print(args.seed, 'Training took:', time.time()-train_started, 'seconds')