-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrain.py
657 lines (592 loc) · 31.1 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
from torch.utils.data import DataLoader
from torchmetrics.functional import f1_score
from functools import partial
import torch.nn as nn
from tqdm import tqdm
import torch.optim as optim
import torch
import dgl
from graph_utils import get_node_features, tripl2graph, tripl2graphw
from transformers import BertModel, BertTokenizer
def multitask_loss(criterion, outputs, targets):
'''
Function that computes the loss of a multi-head classification problem
Args:
criterion (torch.nn.Module): loss criterion
outputs (torch.Tensor): outputs of the network (batch_size, number_of_tasks, labels_tasks)
targets (torch.Tensor): targtet labels for each task (batch_szie, number_of_tasks)
Return:
losses (torch.Tensor): losses for each task (1, batch_size)
'''
losses = torch.hstack([
criterion(t_input, t_target.long().flatten().clone().detach())
for t_input, t_target in zip(outputs, targets)
])
return losses
class classifier_trainer():
'''
Class to train the classifier of triplets on a dataset.
The dataset should return the image as well as the ground truth triplets which are in the image
'''
def __init__(self, model, dataset_train, dataset_val, collate_fn, save_path, use_cuda=True, device = None):
self.model = model
self.dataset_train = dataset_train
self.dataset_val = dataset_val
self.save_path = save_path
self.collate_fn = collate_fn
self.use_cuda = use_cuda
if device is None:
# Take default cuda:0
device = torch.device("cuda:0")
self.device = device
def fit(self, epochs, learning_rate, batch_size):
# Define dataloader
trainloader = DataLoader(self.dataset_train,batch_size=batch_size,shuffle=True,collate_fn=partial(self.collate_fn,triplet_to_idx=self.dataset_train.triplet_to_idx))
valloader = DataLoader(self.dataset_val,batch_size=1,shuffle=False,collate_fn=partial(self.collate_fn,triplet_to_idx=self.dataset_train.triplet_to_idx))
# Define the criterion
criterion = nn.CrossEntropyLoss()
# Define the optimizer
optimizer = optim.SGD(self.model.parameters(), lr=learning_rate)
if(self.use_cuda):
self.model = self.model.to(self.device)
for epoch in range(epochs):
self.model.train()
epoch_loss_train = 0
accuracy_train = 0
epoch_loss_val = 0
accuracy_val = 0
print('Epoch: '+str(epoch))
for i, data in enumerate(tqdm(trainloader)):
images, triplets = data
images = images.to(self.device)
triplets = triplets.to(self.device)
outputs = self.model(images)
# Reshape with the right size
outputs = outputs.reshape((outputs.shape[0], int(outputs.shape[1]/2), 2))
# Now must create the loss function
loss = multitask_loss(criterion, outputs, triplets).mean()
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Calculate accuracy on training
outputs = torch.sigmoid(outputs)
outputs = torch.tensor([[torch.argmax(task).item() for task in sample ] for sample in outputs]).to(outputs.device)
accuracy = f1_score(outputs, triplets.long(), num_classes=2, mdmc_average='global')
accuracy_train += accuracy
epoch_loss_train+=loss.item()
with torch.no_grad():
self.model.eval()
for j, data in enumerate(tqdm(valloader)):
images, triplets = data
images = images.to(self.device)
triplets = triplets.to(self.device)
outputs = self.model(images)
# Reshape with the right size
outputs = outputs.reshape((outputs.shape[0], int(outputs.shape[1]/2), 2))
# Now must create the loss function
loss = multitask_loss(criterion, outputs, triplets).mean()
# Calculate accuracy on training
outputs = torch.sigmoid(outputs)
outputs = torch.tensor([[torch.argmax(task).item() for task in sample ] for sample in outputs]).to(outputs.device)
accuracy = f1_score(outputs, triplets.long(), num_classes=2, mdmc_average='global')
accuracy_val += accuracy
epoch_loss_val+=loss.item()
print('Training loss: {:.3f}'.format(epoch_loss_train/i))
print('Validation loss: {:.3f}'.format(epoch_loss_val/j))
print('Training accuracy: {:.3f}'.format(accuracy_train/i))
print('Validation accuracy: {:.3f}'.format(accuracy_val/j))
torch.save(self.model,self.save_path)
def finetune(self, model, epochs, learning_rate, batch_size):
self.model = model
# Set all the parameters to trainable
for param in self.model.parameters():
param.requires_grad = True
trainloader = DataLoader(self.dataset_train,batch_size=batch_size,shuffle=True,collate_fn=partial(self.collate_fn,triplet_to_idx=self.dataset_train.triplet_to_idx))
valloader = DataLoader(self.dataset_val,batch_size=1,shuffle=False,collate_fn=partial(self.collate_fn,triplet_to_idx=self.dataset_train.triplet_to_idx))
# Define the criterion
criterion = nn.BCEWithLogitsLoss(reduction='mean')
# Define the optimizer
optimizer = optim.SGD(self.model.parameters(), lr=learning_rate)
if(self.use_cuda):
self.model = self.model.to(self.device)
for epoch in range(epochs):
self.model.train()
epoch_loss_train = 0
epoch_loss_val = 0
print('Epoch: '+str(epoch))
for i, data in enumerate(tqdm(trainloader)):
images, triplets = data
images = images.to(self.device)
triplets = triplets.to(self.device)
outputs = self.model(images)
optimizer.zero_grad()
loss = criterion(outputs,triplets)
loss.backward()
optimizer.step()
epoch_loss_train+=loss.item()
with torch.no_grad():
self.model.eval()
for j, data in enumerate(tqdm(valloader)):
images, triplets = data
images = images.to(self.device)
triplets = triplets.to(self.device)
outputs = self.model(images)
loss = criterion(outputs,triplets)
epoch_loss_val+=loss.item()
print('Training loss: {:.3f}'.format(epoch_loss_train/i))
print('Validation loss: {:.3f}'.format(epoch_loss_val/j))
torch.save(self.model,self.save_path)
class caption_trainer():
'''
Class to train the caption inference on a dataset.
The dataset should return the graphs, captions, max_sequence_length and word2idx dictionary
'''
def __init__(self, model, dataset_train, dataset_val, collate_fn, word2idx, max_capt_length, save_path, use_cuda=True, device = None):
self.model = model
self.dataset_train = dataset_train
self.dataset_val = dataset_val
self.save_path = save_path
self.collate_fn = collate_fn
self.use_cuda = use_cuda
self.word2idx = word2idx
self.max_capt_length = max_capt_length
if device is None:
# Take default cuda:0
device = torch.device("cuda:0")
self.device = device
def fit(self, epochs, learning_rate, batch_size, criterion, early_stopping=False, tol_threshold=5):
# Define dataloader
trainloader = DataLoader(self.dataset_train, batch_size=batch_size, shuffle=True, collate_fn=partial(self.collate_fn, word2idx=self.word2idx, training=True))
if self.dataset_val!='':
valloader = DataLoader(self.dataset_val,batch_size=1,shuffle=False,collate_fn=partial(self.collate_fn, word2idx=self.word2idx, training=True))
# Define the optimizer
optimizer = optim.AdamW(self.model.parameters(), lr=learning_rate)
if(self.use_cuda):
self.model = self.model.to(self.device)
if early_stopping:
val_max = float('inf')
train_max = float('inf')
tollerance = 0
for epoch in range(epochs):
self.model.train()
epoch_loss_train = 0
epoch_loss_val = 0
print('Epoch: '+str(epoch))
for i, data in enumerate(tqdm(trainloader)):
_, captions, encoded_captions, src_ids, dst_ids, node_feats, num_nodes = data
graphs = dgl.batch([dgl.graph((src_id, dst_id)) for src_id, dst_id in zip(src_ids, dst_ids)]).to(self.device)
feats = get_node_features(node_feats, sum(num_nodes)).to(self.device)
outputs = self.model(graphs, feats, encoded_captions)
optimizer.zero_grad()
loss = criterion(outputs, captions, self.word2idx, encoded_captions.size(1), self.device)
loss.backward()
optimizer.step()
epoch_loss_train+=loss.item()
if self.dataset_val!='':
with torch.no_grad():
self.model.eval()
for j, data in enumerate(tqdm(valloader)):
_, captions, encoded_captions, src_ids, dst_ids, node_feats, num_nodes = data
graphs = dgl.batch([dgl.graph((src_id, dst_id)) for src_id, dst_id in zip(src_ids, dst_ids)]).to(self.device)
feats = get_node_features(node_feats, sum(num_nodes)).to(self.device)
outputs = self.model(graphs, feats, encoded_captions)
loss = criterion(outputs, captions, self.word2idx, encoded_captions.size(1), self.device)
epoch_loss_val+=loss.item()
print('Training loss: {:.3f}'.format(epoch_loss_train/i))
if self.dataset_val!='':
print('Validation loss: {:.3f}'.format(epoch_loss_val/j))
if early_stopping:
if ((epoch_loss_val/j) < val_max) and ((epoch_loss_train/i < train_max)) and tollerance<tol_threshold :
val_max = epoch_loss_val/j
train_max = epoch_loss_train/i
best_model=self.model
else:
tollerance+=1
if tollerance>tol_threshold:
print("Stopped training due to overfit")
break
# Restart from the best checkpoint
self.model = best_model
if early_stopping:
torch.save(best_model,self.save_path)
else:
torch.save(self.model,self.save_path)
class augmented_caption_trainer():
'''
Class to train the caption inference on a dataset.
The dataset should return the graphs, captions, max_sequence_length and word2idx dictionary
'''
def __init__(self, model, dataset_train, dataset_val, collate_fn, word2idx, max_capt_length, save_path, use_cuda=True, device = None):
self.model = model
self.dataset_train = dataset_train
self.dataset_val = dataset_val
self.save_path = save_path
self.collate_fn = collate_fn
self.use_cuda = use_cuda
self.word2idx = word2idx
self.max_capt_length = max_capt_length
if device is None:
# Take default cuda:0
device = torch.device("cuda:0")
self.device = device
def fit(self, epochs, learning_rate, batch_size, criterion, early_stopping=False, tol_threshold=5):
# Define dataloader
trainloader = DataLoader(self.dataset_train, batch_size=batch_size, shuffle=True, collate_fn=partial(self.collate_fn, word2idx=self.word2idx, training=True))
if self.dataset_val!='':
valloader = DataLoader(self.dataset_val,batch_size=1,shuffle=False,collate_fn=partial(self.collate_fn, word2idx=self.word2idx, training=True))
# Define the optimizer
optimizer = optim.AdamW(self.model.parameters(), lr=learning_rate)
if(self.use_cuda):
self.model = self.model.to(self.device)
if early_stopping:
val_max = float('inf')
train_max = float('inf')
tollerance = 0
for epoch in range(epochs):
self.model.train()
epoch_loss_train = 0
epoch_loss_val = 0
print('Epoch: '+str(epoch))
for i, data in enumerate(tqdm(trainloader)):
_, img, captions, encoded_captions, src_ids, dst_ids, node_feats, num_nodes = data
graphs = dgl.batch([dgl.graph((src_id, dst_id)) for src_id, dst_id in zip(src_ids, dst_ids)]).to(self.device)
feats = get_node_features(node_feats, sum(num_nodes)).to(self.device)
img = img.to(self.device)
outputs = self.model(graphs, feats, img, encoded_captions)
optimizer.zero_grad()
loss = criterion(outputs, captions, self.word2idx, encoded_captions.size(1), self.device)
loss.backward()
optimizer.step()
epoch_loss_train+=loss.item()
if self.dataset_val!='':
with torch.no_grad():
self.model.eval()
for j, data in enumerate(tqdm(valloader)):
_, img, captions, encoded_captions, src_ids, dst_ids, node_feats, num_nodes = data
graphs = dgl.batch([dgl.graph((src_id, dst_id)) for src_id, dst_id in zip(src_ids, dst_ids)]).to(self.device)
feats = get_node_features(node_feats, sum(num_nodes)).to(self.device)
img = img.to(self.device)
outputs = self.model(graphs, feats, img, encoded_captions)
loss = criterion(outputs, captions, self.word2idx, encoded_captions.size(1), self.device)
epoch_loss_val+=loss.item()
print('Training loss: {:.3f}'.format(epoch_loss_train/i))
if self.dataset_val!='':
print('Validation loss: {:.3f}'.format(epoch_loss_val/j))
if early_stopping:
if ((epoch_loss_val/j) < val_max) and ((epoch_loss_train/i < train_max)) and tollerance<tol_threshold :
val_max = epoch_loss_val/j
train_max = epoch_loss_train/i
best_model=self.model
else:
tollerance+=1
if tollerance>tol_threshold:
print("Stopped training due to overfit")
break
# Restart from the best checkpoint
self.model = best_model
if early_stopping:
torch.save(best_model,self.save_path)
else:
torch.save(self.model,self.save_path)
class full_pipeline_trainer():
'''
Class to train full pipeline on a dataset.
The dataset should return the image as well as the ground truth triplets which are in the image
'''
def __init__(self, model, dataset_train, dataset_val, collate_fn, word2idx, max_capt_length, save_path, use_cuda=True, device = None, pil=False):
self.pil = pil
self.model = model
self.dataset_train = dataset_train
self.dataset_val = dataset_val
self.save_path = save_path
self.collate_fn = collate_fn
self.word2idx = word2idx
self.max_capt_length = max_capt_length
self.use_cuda = use_cuda
if device is None:
# Take default cuda:0
device = torch.device("cuda:0")
self.device = device
def fit(self, epochs, learning_rate, batch_size, criterion, early_stopping=False, tol_threshold=5, plot=False, combo=False):
# For plotting purposes
if plot:
train_losses = []
val_losses = []
# Define dataloader
trainloader = DataLoader(self.dataset_train,batch_size=batch_size,shuffle=True,collate_fn=partial(self.collate_fn,triplet_to_idx=self.dataset_train.triplet_to_idx, word2idx=self.word2idx, training=True, pil=self.pil))
valloader = DataLoader(self.dataset_val,batch_size=1,shuffle=False,collate_fn=partial(self.collate_fn,triplet_to_idx=self.dataset_train.triplet_to_idx, word2idx=self.word2idx, training=True, pil=self.pil))
# Define the optimizer
optimizer = optim.AdamW(self.model.parameters(), lr=learning_rate)
if(self.use_cuda):
self.model = self.model.to(self.device)
# Early stopping
if early_stopping:
val_max = float('inf')
train_max = float('inf')
tollerance = 0
for epoch in range(epochs):
self.model.train()
epoch_loss_train = 0
epoch_loss_val = 0
print('Epoch: '+str(epoch))
for i, data in enumerate(tqdm(trainloader)):
_, images, triplets, captions, encoded_captions, lengths, _, _, _, _ = data
images = images.to(self.device)
triplets = triplets.to(self.device)
inputs = encoded_captions[:,:-1]
lengths = [lengths-1 for lengths in lengths]
if combo:
# Combined Loss
cap_outputs, class_outputs = self.model(images, inputs, lengths, True)
class_loss = multitask_loss(nn.CrossEntropyLoss(), class_outputs, triplets).mean()
cap_loss = criterion(cap_outputs, captions, lengths, self.word2idx, encoded_captions.shape[1] , self.device)
loss = 0.5*cap_loss + 0.5*class_loss
else:
# Unique Loss
cap_outputs, _ = self.model(images, captions, inputs, lengths, True)
cap_loss = criterion(cap_outputs, captions, lengths, self.word2idx, encoded_captions.shape[1], self.device)
loss = cap_loss
optimizer.zero_grad()
loss.backward()
optimizer.step()
epoch_loss_train+=loss.item()
# print("\nFirst cicle done!")
# exit(0)
with torch.no_grad():
self.model.eval()
for j, data in enumerate(tqdm(valloader)):
_, images, triplets, captions, encoded_captions, lengths, _, _, _, _ = data
images = images.to(self.device)
triplets = triplets.to(self.device)
if combo:
# Combined Loss
try:
cap_outputs, class_outputs = self.model(images)
except:
cap_outputs, class_outputs = self.model(images, captions, encoded_captions, lengths, training=False)
class_loss = multitask_loss(nn.CrossEntropyLoss(), class_outputs, triplets).mean()
cap_loss = criterion(cap_outputs, captions, lengths, self.word2idx, encoded_captions.shape[1] , self.device)
loss = 0.5*cap_loss + 0.5*class_loss
else:
# Unified Loss
try:
cap_outputs, _ = self.model(images)
except:
cap_outputs, _ = self.model(images, captions, encoded_captions, lengths, training=False)
cap_loss = criterion(cap_outputs, captions, lengths, self.word2idx, encoded_captions.shape[1] , self.device)
loss = cap_loss
epoch_loss_val+=loss.item()
print('Training loss: {:.3f}'.format(epoch_loss_train/i))
print('Validation loss: {:.3f}'.format(epoch_loss_val/j))
# Saving the losses for plotting purposes
if plot:
train_losses.append(epoch_loss_train/i)
val_losses.append(epoch_loss_val/j)
# Early stopping algorithm
if early_stopping:
if ((epoch_loss_val/j) < val_max) and ((epoch_loss_train/i < train_max)) and tollerance<tol_threshold :
val_max = epoch_loss_val/j
train_max = epoch_loss_train/i
best_model=self.model
else:
tollerance+=1
if tollerance>tol_threshold:
print("Stopped training due to overfit")
break
# Restart from the best checkpoint
self.model = best_model
if early_stopping:
torch.save(best_model,self.save_path)
if plot:
return train_losses, val_losses
else:
torch.save(self.model,self.save_path)
if plot:
return train_losses, val_losses
class enc_finetuning():
'''
Class to train full pipeline on a dataset.
The dataset should return the image as well as the ground truth triplets which are in the image
'''
def __init__(self, model, dataset_train, dataset_val, collate_fn, word2idx, max_capt_length, save_path, use_cuda=True, device = None):
self.model = model
self.dataset_train = dataset_train
self.dataset_val = dataset_val
self.save_path = save_path
self.collate_fn = collate_fn
self.word2idx = word2idx
self.max_capt_length = max_capt_length
self.use_cuda = use_cuda
if device is None:
# Take default cuda:0
device = torch.device("cuda:0")
self.device = device
def fit(self, epochs, learning_rate, batch_size, criterion, early_stopping=False, tol_threshold=5):
# Define dataloader
trainloader = DataLoader(self.dataset_train,batch_size=batch_size,shuffle=True,collate_fn=partial(self.collate_fn,triplet_to_idx=self.dataset_train.triplet_to_idx, word2idx=self.word2idx, training=True))
valloader = DataLoader(self.dataset_val,batch_size=1,shuffle=False,collate_fn=partial(self.collate_fn,triplet_to_idx=self.dataset_train.triplet_to_idx, word2idx=self.word2idx, training=True))
# Define the optimizer
final_layer_weights = []
rest_of_the_net_weights = []
# final_names = []
# rest_names = []
# we will iterate through the layers of the network
for name, param in self.model.named_parameters():
if not name.startswith('feature_encoder'):
if name.startswith('tripl_classifier') and 'fc' in name:
final_layer_weights.append(param)
# final_names.append(name)
else:
rest_of_the_net_weights.append(param)
# rest_names.append(name)
# so now we have divided the network weights into two groups.
# We will train the final_layer_weights with learning_rate = lr
# and rest_of_the_net_weights with learning_rate = lr / 10
optimizer = torch.optim.AdamW([
{'params': rest_of_the_net_weights},
{'params': final_layer_weights, 'lr': learning_rate}
], lr=learning_rate / 10)
if(self.use_cuda):
self.model = self.model.to(self.device)
# Early stopping
if early_stopping:
val_max = float('inf')
train_max = float('inf')
tollerance = 0
# crit = nn.CrossEntropyLoss()
for epoch in range(epochs):
self.model.train()
epoch_loss_train = 0
epoch_loss_val = 0
print('Epoch: '+str(epoch))
for i, data in enumerate(tqdm(trainloader)):
_, images, triplets, captions, encoded_captions, _, _, _, _ = data
images = images.to(self.device)
cap_outputs, class_outputs = self.model(images)
# Loss for both tasks
triplets = triplets.to(self.device)
class_loss = multitask_loss(nn.CrossEntropyLoss(), class_outputs, triplets).mean()
# class_loss = crit(class_outputs, triplets)
cap_loss = criterion(cap_outputs, captions, self.word2idx, encoded_captions.size(1), self.device)
loss = 0.5*cap_loss + 0.5*class_loss
optimizer.zero_grad()
loss.backward()
optimizer.step()
epoch_loss_train+=loss.item()
with torch.no_grad():
self.model.eval()
for j, data in enumerate(tqdm(valloader)):
_, images, triplets, captions, encoded_captions, _, _, _, _ = data
images = images.to(self.device)
cap_outputs, class_outputs = self.model(images)
triplets = triplets.to(self.device)
class_loss = multitask_loss(nn.CrossEntropyLoss(), class_outputs, triplets).mean()
# class_loss = crit(class_outputs, triplets)
cap_loss = criterion(cap_outputs, captions, self.word2idx, encoded_captions.size(1), self.device)
loss = 0.5*cap_loss + 0.5*class_loss
epoch_loss_val+=loss.item()
print('Training loss: {:.3f}'.format(epoch_loss_train/i))
print('Validation loss: {:.3f}'.format(epoch_loss_val/j))
if early_stopping:
if ((epoch_loss_val/j) < val_max) and ((epoch_loss_train/i < train_max)) and tollerance<tol_threshold :
val_max = epoch_loss_val/j
train_max = epoch_loss_train/i
best_model=self.model
else:
tollerance+=1
if tollerance>tol_threshold:
print("Stopped training due to overfit")
break
# Restart from the best checkpoint
self.model = best_model
if early_stopping:
torch.save(best_model,self.save_path)
else:
torch.save(self.model,self.save_path)
class waterfall_trainer():
'''
Class to train the Waterfall pipeline using a caption generator pre-trained on UCM.
The dataset should return the graphs, captions, max_sequence_length and word2idx dictionary
'''
def __init__(self, model, dataset_train, dataset_val, collate_fn, word2idx, max_capt_length, save_path, use_cuda=True, device = None, pil=False):
self.pil = pil
self.model = model
self.feature_encoder = BertModel.from_pretrained("bert-base-uncased")
self.tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
self.dataset_train = dataset_train
self.dataset_val = dataset_val
self.save_path = save_path
self.collate_fn = collate_fn
self.use_cuda = use_cuda
self.word2idx = word2idx
self.max_capt_length = max_capt_length
if device is None:
# Take default cuda:0
device = torch.device("cuda:0")
self.device = device
def fit(self, epochs, learning_rate, batch_size, criterion, early_stopping=False, tol_threshold=5, plot=False):
# For plotting purposes
if plot:
train_losses = []
val_losses = []
# Define dataloader
trainloader = DataLoader(self.dataset_train, batch_size=batch_size, shuffle=True, collate_fn=partial(self.collate_fn, word2idx=self.word2idx, training=True, pil=self.pil))
valloader = DataLoader(self.dataset_val,batch_size=1,shuffle=False,collate_fn=partial(self.collate_fn, word2idx=self.word2idx, training=True, pil=self.pil))
# Define the optimizer
optimizer = optim.AdamW(self.model.parameters(), lr=learning_rate)
if(self.use_cuda):
self.model = self.model.to(self.device)
if early_stopping:
val_max = float('inf')
train_max = float('inf')
tollerance = 0
for epoch in range(epochs):
self.model.train()
epoch_loss_train = 0
epoch_loss_val = 0
print('Epoch: '+str(epoch))
for i, data in enumerate(tqdm(trainloader)):
imgid, img, triplets, captions, encoded_captions, lengths = data
graphs, graph_feats = tripl2graphw(triplets, self.feature_encoder, self.tokenizer)
graphs, graph_feats = graphs.to(self.device), graph_feats.to(self.device)
outputs = self.model(graphs, graph_feats, encoded_captions, lengths, training=True)
optimizer.zero_grad()
loss = criterion(outputs, captions, lengths, self.word2idx, encoded_captions.size(1), self.device)
loss.backward()
optimizer.step()
epoch_loss_train+=loss.item()
if self.dataset_val!='':
with torch.no_grad():
self.model.eval()
for j, data in enumerate(tqdm(valloader)):
imgid, img, triplets, captions, encoded_captions, lengths = data
graphs, graph_feats = tripl2graphw(triplets, self.feature_encoder, self.tokenizer)
graphs, graph_feats = graphs.to(self.device), graph_feats.to(self.device)
# img = img.to(self.device)
outputs = self.model(graphs, graph_feats, encoded_captions, lengths, training=False)
loss = criterion(outputs, captions, lengths, self.word2idx, encoded_captions.size(1), self.device)
epoch_loss_val+=loss.item()
print('Training loss: {:.3f}'.format(epoch_loss_train/i))
print('Validation loss: {:.3f}'.format(epoch_loss_val/j))
# Saving the losses for plotting purposes
if plot:
train_losses.append(epoch_loss_train/i)
val_losses.append(epoch_loss_val/j)
if early_stopping:
if ((epoch_loss_val/j) < val_max) and ((epoch_loss_train/i < train_max)) and tollerance<tol_threshold :
val_max = epoch_loss_val/j
train_max = epoch_loss_train/i
best_model=self.model
else:
tollerance+=1
if tollerance>tol_threshold:
print("Stopped training due to overfit")
break
# Restart from the best checkpoint
self.model = best_model
if early_stopping:
torch.save(best_model,self.save_path)
else:
torch.save(self.model,self.save_path)
if plot:
return train_losses, val_losses