-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
84 lines (60 loc) · 1.95 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
import config
import utils
import torch.nn as nn
import torch.optim as optim
import numpy as np
from tqdm import tqdm
from torch.utils.data import DataLoader
from dataset import CollateDataset
def train_epoch(loader, model, optimizer, loss_fn, epoch):
model.train()
losses = []
loader = tqdm(loader)
for img, captions in loader:
img = img.to(config.DEVICE)
captions = captions.to(config.DEVICE)
output = model(img, captions)
loss = loss_fn(
output.reshape(-1, output.shape[2]),
captions[:, 1:].reshape(-1)
)
optimizer.zero_grad()
loss.backward()
optimizer.step()
loader.set_postfix(loss=loss.item())
losses.append(loss.item())
if config.SAVE_MODEL:
utils.save_checkpoint({
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
'epoch': epoch,
'loss': np.mean(losses)
})
print(f'Epoch[{epoch}]: Loss {np.mean(losses)}')
def main():
all_dataset = utils.load_dataset()
train_dataset, _ = utils.train_test_split(dataset=all_dataset)
train_loader = DataLoader(
dataset=train_dataset,
batch_size=config.BATCH_SIZE,
pin_memory=config.PIN_MEMORY,
drop_last=False,
shuffle=True,
collate_fn=CollateDataset(pad_idx=all_dataset.vocab.stoi['<PAD>']),
)
model = utils.get_model_instance(all_dataset.vocab)
optimizer = optim.Adam(model.parameters(), lr=config.LEARNING_RATE)
loss_fn = nn.CrossEntropyLoss(ignore_index=all_dataset.vocab.stoi['<PAD>'])
starting_epoch = 1
if utils.can_load_checkpoint():
starting_epoch = utils.load_checkpoint(model, optimizer)
for epoch in range(starting_epoch, config.EPOCHS):
train_epoch(
train_loader,
model,
optimizer,
loss_fn,
epoch
)
if __name__ == '__main__':
main()