-
Notifications
You must be signed in to change notification settings - Fork 27
/
train.py
235 lines (192 loc) · 7.37 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# Torch imports
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
import torch.backends.cudnn as cudnn
cudnn.benchmark = True
# Python imports
import tqdm
from tqdm import tqdm
import os
from os.path import join as ospj
import csv
#Local imports
from data import dataset as dset
from models.common import Evaluator
from utils.utils import save_args, load_args
from utils.config_model import configure_model
from flags import parser, DATA_FOLDER
best_auc = 0
best_hm = 0
compose_switch = True
device = 'cuda' if torch.cuda.is_available() else 'cpu'
def main():
# Get arguments and start logging
args = parser.parse_args()
load_args(args.config, args)
logpath = os.path.join(args.cv_dir, args.name)
os.makedirs(logpath, exist_ok=True)
save_args(args, logpath, args.config)
writer = SummaryWriter(log_dir = logpath, flush_secs = 30)
# Get dataset
trainset = dset.CompositionDataset(
root=os.path.join(DATA_FOLDER,args.data_dir),
phase='train',
split=args.splitname,
model =args.image_extractor,
num_negs=args.num_negs,
pair_dropout=args.pair_dropout,
update_features = args.update_features,
train_only= args.train_only,
open_world=args.open_world
)
trainloader = torch.utils.data.DataLoader(
trainset,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.workers)
testset = dset.CompositionDataset(
root=os.path.join(DATA_FOLDER,args.data_dir),
phase=args.test_set,
split=args.splitname,
model =args.image_extractor,
subset=args.subset,
update_features = args.update_features,
open_world=args.open_world
)
testloader = torch.utils.data.DataLoader(
testset,
batch_size=args.test_batch_size,
shuffle=False,
num_workers=args.workers)
# Get model and optimizer
image_extractor, model, optimizer = configure_model(args, trainset)
args.extractor = image_extractor
train = train_normal
evaluator_val = Evaluator(testset, model)
print(model)
start_epoch = 0
# Load checkpoint
if args.load is not None:
checkpoint = torch.load(args.load)
if image_extractor:
try:
image_extractor.load_state_dict(checkpoint['image_extractor'])
if args.freeze_features:
print('Freezing image extractor')
image_extractor.eval()
for param in image_extractor.parameters():
param.requires_grad = False
except:
print('No Image extractor in checkpoint')
model.load_state_dict(checkpoint['net'])
start_epoch = checkpoint['epoch']
print('Loaded model from ', args.load)
for epoch in tqdm(range(start_epoch, args.max_epochs + 1), desc = 'Current epoch'):
train(epoch, image_extractor, model, trainloader, optimizer, writer)
if model.is_open and args.model=='compcos' and ((epoch+1)%args.update_feasibility_every)==0 :
print('Updating feasibility scores')
model.update_feasibility(epoch+1.)
if epoch % args.eval_val_every == 0:
with torch.no_grad(): # todo: might not be needed
test(epoch, image_extractor, model, testloader, evaluator_val, writer, args, logpath)
print('Best AUC achieved is ', best_auc)
print('Best HM achieved is ', best_hm)
def train_normal(epoch, image_extractor, model, trainloader, optimizer, writer):
'''
Runs training for an epoch
'''
if image_extractor:
image_extractor.train()
model.train() # Let's switch to training
train_loss = 0.0
for idx, data in tqdm(enumerate(trainloader), total=len(trainloader), desc = 'Training'):
data = [d.to(device) for d in data]
if image_extractor:
data[0] = image_extractor(data[0])
loss, _ = model(data)
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_loss += loss.item()
train_loss = train_loss/len(trainloader)
writer.add_scalar('Loss/train_total', train_loss, epoch)
print('Epoch: {}| Loss: {}'.format(epoch, round(train_loss, 2)))
def test(epoch, image_extractor, model, testloader, evaluator, writer, args, logpath):
'''
Runs testing for an epoch
'''
global best_auc, best_hm
def save_checkpoint(filename):
state = {
'net': model.state_dict(),
'epoch': epoch,
'AUC': stats['AUC']
}
if image_extractor:
state['image_extractor'] = image_extractor.state_dict()
torch.save(state, os.path.join(logpath, 'ckpt_{}.t7'.format(filename)))
if image_extractor:
image_extractor.eval()
model.eval()
accuracies, all_sub_gt, all_attr_gt, all_obj_gt, all_pair_gt, all_pred = [], [], [], [], [], []
for idx, data in tqdm(enumerate(testloader), total=len(testloader), desc='Testing'):
data = [d.to(device) for d in data]
if image_extractor:
data[0] = image_extractor(data[0])
_, predictions = model(data)
attr_truth, obj_truth, pair_truth = data[1], data[2], data[3]
all_pred.append(predictions)
all_attr_gt.append(attr_truth)
all_obj_gt.append(obj_truth)
all_pair_gt.append(pair_truth)
if args.cpu_eval:
all_attr_gt, all_obj_gt, all_pair_gt = torch.cat(all_attr_gt), torch.cat(all_obj_gt), torch.cat(all_pair_gt)
else:
all_attr_gt, all_obj_gt, all_pair_gt = torch.cat(all_attr_gt).to('cpu'), torch.cat(all_obj_gt).to(
'cpu'), torch.cat(all_pair_gt).to('cpu')
all_pred_dict = {}
# Gather values as dict of (attr, obj) as key and list of predictions as values
if args.cpu_eval:
for k in all_pred[0].keys():
all_pred_dict[k] = torch.cat(
[all_pred[i][k].to('cpu') for i in range(len(all_pred))])
else:
for k in all_pred[0].keys():
all_pred_dict[k] = torch.cat(
[all_pred[i][k] for i in range(len(all_pred))])
# Calculate best unseen accuracy
results = evaluator.score_model(all_pred_dict, all_obj_gt, bias=args.bias, topk=args.topk)
stats = evaluator.evaluate_predictions(results, all_attr_gt, all_obj_gt, all_pair_gt, all_pred_dict, topk=args.topk)
stats['a_epoch'] = epoch
result = ''
# write to Tensorboard
for key in stats:
writer.add_scalar(key, stats[key], epoch)
result = result + key + ' ' + str(round(stats[key], 4)) + '| '
result = result + args.name
print(f'Test Epoch: {epoch}')
print(result)
if epoch > 0 and epoch % args.save_every == 0:
save_checkpoint(epoch)
if stats['AUC'] > best_auc:
best_auc = stats['AUC']
print('New best AUC ', best_auc)
save_checkpoint('best_auc')
if stats['best_hm'] > best_hm:
best_hm = stats['best_hm']
print('New best HM ', best_hm)
save_checkpoint('best_hm')
# Logs
with open(ospj(logpath, 'logs.csv'), 'a') as f:
w = csv.DictWriter(f, stats.keys())
if epoch == 0:
w.writeheader()
w.writerow(stats)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('Best AUC achieved is ', best_auc)
print('Best HM achieved is ', best_hm)