-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_singleattn3_dan.py
259 lines (200 loc) · 11.2 KB
/
train_singleattn3_dan.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import os
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
# from data_loader_dan import get_loader
from data_loader_dan_2 import get_loader
# from data_loader_dan_2 import get_loader
from models_singleattn3_dan import VqaModel, SANModel, TripletLoss
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# device = torch.device('cuda:1' if torch.cuda.is_available() else 'cpu')
def main(args):
os.makedirs(args.log_dir, exist_ok=True)
os.makedirs(args.model_dir, exist_ok=True)
data_loader = get_loader(
input_dir=args.input_dir,
input_vqa_train='train.npy',
input_vqa_valid='valid.npy',
max_qst_length=args.max_qst_length,
max_num_ans=args.max_num_ans,
batch_size=args.batch_size,
num_workers=args.num_workers)
qst_vocab_size = data_loader['train'].dataset.qst_vocab.vocab_size
ans_vocab_size = data_loader['train'].dataset.ans_vocab.vocab_size
ans_unk_idx = data_loader['train'].dataset.ans_vocab.unk2idx
# model = VqaModel(
# embed_size=args.embed_size,
# qst_vocab_size=qst_vocab_size,
# ans_vocab_size=ans_vocab_size,
# word_embed_size=args.word_embed_size,
# num_layers=args.num_layers,
# hidden_size=args.hidden_size).to(device)
model = SANModel(
embed_size=args.embed_size,
qst_vocab_size=qst_vocab_size,
ans_vocab_size=ans_vocab_size,
word_embed_size=args.word_embed_size,
num_layers=args.num_layers,
hidden_size=args.hidden_size)
# model = torch.jit.script(SANModel(
# embed_size=args.embed_size,
# qst_vocab_size=qst_vocab_size,
# ans_vocab_size=ans_vocab_size,
# word_embed_size=args.word_embed_size,
# num_layers=args.num_layers,
# hidden_size=args.hidden_size))
if torch.cuda.device_count() > 0:
print("Using", torch.cuda.device_count(), "GPUs.")
# dim = 0 [40, xxx] -> [10, ...], [10, ...], [10, ...], [10, ...] on 4 GPUs
model = nn.DataParallel(model)
model = model.to(device)
#### margin value to be decided on the basis of validation data
margin = 0.2
#### v_weightage value (for triplet vs classification loss ratio) to be decided on the basis of validation data
v_weightage = 1.0
# v_weightage = 10.0
criterion = nn.CrossEntropyLoss()
criterion2 = TripletLoss(margin)
# criterion2 = torch.jit.script(TripletLoss(margin))
#params = list(model.qst_encoder.parameters()) \
# + list(model.san.parameters()) \
# + list(model.mlp.parameters())
optimizer = optim.Adam(model.parameters(), lr=args.learning_rate)
scheduler = lr_scheduler.StepLR(optimizer, step_size=args.step_size, gamma=args.gamma)
### Early stopping
early_stop_threshold = 10 #3
best_loss = 99999
val_increase_count = 0
stop_training = False
prev_loss = 9999
for epoch in range(args.num_epochs):
for phase in ['train', 'valid']:
running_loss = 0.0
running_ce_loss = 0.0
running_triplet_loss = 0.0
running_corr_exp1 = 0
running_corr_exp2 = 0
batch_step_size = len(data_loader[phase].dataset) / args.batch_size
if phase == 'train':
# scheduler.step()
model.train()
else:
model.eval()
for batch_idx, batch_sample in enumerate(data_loader[phase]):
image = batch_sample['image'].to(device)
question = batch_sample['question'].to(device)
label = batch_sample['answer_label'].to(device)
multi_choice = batch_sample['answer_multi_choice'] # not tensor, list.
supporting_example_image = batch_sample['supporting_example_image'].to(device)
# supporting_example_question = batch_sample['supporting_example_question'].to(device)
opposing_example_image = batch_sample['opposing_example_image'].to(device)
# opposing_example_question = batch_sample['opposing_example_question'].to(device)
optimizer.zero_grad()
with torch.set_grad_enabled(phase == 'train'):
output, attn_scores = model(image, question) # [batch_size, ans_vocab_size=1000, attn_scores=196]
_, pred_exp1 = torch.max(output, 1) # [batch_size]
_, pred_exp2 = torch.max(output, 1) # [batch_size]
ce_loss = criterion(output, label)
if phase == 'train':
_, supporting_example_attn_scores = model(supporting_example_image, question) # [batch_size, ans_vocab_size=1000, attn_scores=196]
_, opposing_example_attn_scores = model(opposing_example_image, question) # [batch_size, ans_vocab_size=1000, attn_scores=196]
triplet_loss = criterion2(attn_scores, supporting_example_attn_scores, opposing_example_attn_scores)
loss = ce_loss + v_weightage * triplet_loss
else:
loss = ce_loss
if phase == 'train':
loss.backward()
optimizer.step()
# Evaluation metric of 'multiple choice'
# Exp1: our model prediction to '<unk>' IS accepted as the answer.
# Exp2: our model prediction to '<unk>' is NOT accepted as the answer.
pred_exp2[pred_exp2 == ans_unk_idx] = -9999
running_loss += loss.item()
running_ce_loss += ce_loss.item()
running_triplet_loss += triplet_loss.item()
running_corr_exp1 += torch.stack([(ans == pred_exp1.cpu()) for ans in multi_choice]).any(dim=0).sum()
running_corr_exp2 += torch.stack([(ans == pred_exp2.cpu()) for ans in multi_choice]).any(dim=0).sum()
# Print the average loss in a mini-batch.
if batch_idx % 100 == 0:
print('| {} SET | Epoch [{:02d}/{:02d}], Step [{:04d}/{:04d}], Loss: {:.4f}, ce_Loss: {:.4f}, triplet_Loss: {:.4f}'
.format(phase.upper(), epoch+1, args.num_epochs, batch_idx, int(batch_step_size), loss.item(), ce_loss.item(), triplet_loss.item()), flush=True)
# Print the average loss and accuracy in an epoch.
epoch_loss = running_loss / batch_step_size
epoch_ce_loss = running_ce_loss / batch_step_size
epoch_triplet_loss = running_triplet_loss / batch_step_size
epoch_acc_exp1 = running_corr_exp1.double() / len(data_loader[phase].dataset) # multiple choice
epoch_acc_exp2 = running_corr_exp2.double() / len(data_loader[phase].dataset) # multiple choice
print('| {} SET | Epoch [{:02d}/{:02d}], Loss: {:.4f}, ce_Loss: {:.4f}, triplet_Loss: {:.4f}, Acc(Exp1): {:.4f}, Acc(Exp2): {:.4f} \n'
.format(phase.upper(), epoch+1, args.num_epochs, epoch_loss, epoch_ce_loss, epoch_triplet_loss, epoch_acc_exp1, epoch_acc_exp2), flush=True)
# Log the loss and accuracy in an epoch.
with open(os.path.join(args.log_dir, '{}-{}-log-epoch-{:02}.txt')
.format(args.model_name, phase, epoch+1), 'w') as f:
f.write(str(epoch+1) + '\t'
+ str(epoch_loss) + '\t'
+ str(epoch_acc_exp1.item()) + '\t'
+ str(epoch_acc_exp2.item()) + '\t'
+ str(epoch_ce_loss) + '\t'
+ str(epoch_triplet_loss))
if phase == 'valid':
if epoch_loss < best_loss:
print("At epoch:",epoch+1,"best loss from:\t",best_loss, "\tto\t",epoch_loss, flush=True)
best_loss = epoch_loss
torch.save(model, os.path.join(args.model_dir, '{}-best_model.pt'.format(args.model_name)))
torch.save({'epoch': epoch+1, 'state_dict': model.state_dict()}, os.path.join(args.model_dir, '{}-best_model.ckpt'.format(args.model_name)))
if epoch_loss > prev_loss:
val_increase_count += 1
else:
val_increase_count = 0
if val_increase_count >= early_stop_threshold:
stop_training = True
prev_loss = epoch_loss
# # Save the model check points.
# if (epoch+1) % args.save_step == 0:
# torch.save({'epoch': epoch+1, 'state_dict': model.state_dict()},
# os.path.join(args.model_dir, 'model-epoch-{:02d}.ckpt'.format(epoch+1)))
scheduler.step()
print("lr val:",optimizer.state_dict()['param_groups'][0]['lr'], flush=True)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--model_name', type=str,
help='model name.')
parser.add_argument('--input_dir', type=str, default='./datasets',
help='input directory for visual question answering.')
parser.add_argument('--log_dir', type=str, default='./logs',
help='directory for logs.')
parser.add_argument('--model_dir', type=str, default='./models',
help='directory for saved models.')
parser.add_argument('--max_qst_length', type=int, default=30,
help='maximum length of question. \
the length in the VQA dataset = 26.')
parser.add_argument('--max_num_ans', type=int, default=10,
help='maximum number of answers.')
parser.add_argument('--embed_size', type=int, default=1024,
help='embedding size of feature vector \
for both image and question.')
parser.add_argument('--word_embed_size', type=int, default=300,
help='embedding size of word \
used for the input in the LSTM.')
parser.add_argument('--num_layers', type=int, default=2,
help='number of layers of the RNN(LSTM).')
parser.add_argument('--hidden_size', type=int, default=512,
help='hidden_size in the LSTM.')
parser.add_argument('--learning_rate', type=float, default=0.001,
help='learning rate for training.')
parser.add_argument('--step_size', type=int, default=10,
help='period of learning rate decay.')
parser.add_argument('--gamma', type=float, default=0.1,
help='multiplicative factor of learning rate decay.')
parser.add_argument('--num_epochs', type=int, default=30,
help='number of epochs.')
parser.add_argument('--batch_size', type=int, default=256,#2,#256, #224, #128, #256,
help='batch_size.')
parser.add_argument('--num_workers', type=int, default=8,
help='number of processes working on cpu.')
parser.add_argument('--save_step', type=int, default=1,
help='save step of model.')
args = parser.parse_args()
main(args)