-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrainer.py
166 lines (145 loc) · 6.77 KB
/
trainer.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
import os
import os.path as osp
import torch
import torch.nn as nn
import torch.nn.functional as F
import glob
from torch.optim import Adam, SGD
from torch.optim.lr_scheduler import StepLR, MultiStepLR
import numpy as np
import random
import tqdm
from modules.fsl_query import make_fsl
from dataloader import make_dataloader
from utils import mean_confidence_interval, AverageMeter, set_seed
class trainer(object):
def __init__(self, cfg, checkpoint_dir):
self.n_way = cfg.n_way # 5
self.k_shot = cfg.k_shot # 5
self.train_query_per_class = cfg.train.query_per_class_per_episode # 10
self.val_query_per_class = cfg.test.query_per_class_per_episode # 15
self.train_episode_per_epoch = cfg.train.episode_per_epoch
self.prefix = osp.basename(checkpoint_dir)
self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
self.checkpoint_dir = checkpoint_dir
self.epochs = cfg.train.epochs
self.fsl = make_fsl(cfg).to(self.device)
self.lr = cfg.train.learning_rate
self.lr_decay = cfg.train.lr_decay
self.lr_decay_epoch = cfg.train.lr_decay_epoch
if cfg.train.optim == "Adam":
self.optim = Adam(self.fsl.parameters(),lr=cfg.train.learning_rate, betas=cfg.train.adam_betas)
elif cfg.train.optim == "SGD":
self.optim = SGD(
self.fsl.parameters(),
lr=cfg.train.learning_rate,
momentum=cfg.train.sgd_mom,
weight_decay=cfg.train.sgd_weight_decay,
nesterov=True
)
else:
raise NotImplementedError
self.val_episode = cfg.val.episode
pths = [osp.basename(f) for f in glob.glob(osp.join(checkpoint_dir, "*.pth"))]
if pths:
pths_epoch = [''.join(filter(str.isdigit, f[:f.find('_')])) for f in pths]
pths = [p for p, e in zip(pths, pths_epoch) if e]
pths_epoch = [int(e) for e in pths_epoch if e]
self.train_start_epoch = max(pths_epoch)
c = osp.join(checkpoint_dir, pths[pths_epoch.index(self.train_start_epoch)])
state_dict = torch.load(c)
self.fsl.load_state_dict(state_dict["fsl"], strict=False)
print("[*] Continue training from checkpoints: {}".format(c))
lr_scheduler_last_epoch = self.train_start_epoch
if "optimizer" in state_dict and state_dict["optimizer"] is not None:
self.optim.load_state_dict(state_dict["optimizer"])
else:
self.train_start_epoch = 0
lr_scheduler_last_epoch = -1
if cfg.train.lr_decay_milestones:
self.lr_scheduler = MultiStepLR(self.optim, milestones=cfg.train.lr_decay_milestones,gamma=self.lr_decay)
else:
self.lr_scheduler = StepLR(self.optim, step_size=self.lr_decay_epoch, gamma=self.lr_decay)
self.cfg = cfg
def fix_bn(self):
for module in self.fsl.modules():
if isinstance(module, torch.nn.modules.BatchNorm2d):
module.eval()
if isinstance(module, torch.nn.modules.SyncBatchNorm):
module.eval()
def validate(self, dataloader):
accuracies = []
tqdm_gen = tqdm.tqdm(dataloader)
acc = AverageMeter()
for episode, (support_x, support_y, query_x, query_y) in enumerate(tqdm_gen):
support_x = support_x.to(self.device)
support_y = support_y.to(self.device)
query_x = query_x.to(self.device)
query_y = query_y.to(self.device)
rewards = self.fsl(support_x, support_y, query_x, query_y)
total_rewards = np.sum(rewards)
accuracy = total_rewards / (query_y.numel())
acc.update(total_rewards / query_y.numel(), 1)
mesg = "Val: acc={:.3f}".format(
acc.avg
)
tqdm_gen.set_description(mesg)
accuracies.append(accuracy)
test_accuracy, h = mean_confidence_interval(accuracies)
return test_accuracy, h
def save_model(self, prefix, accuracy, h, epoch, final_epoch=False):
filename = osp.join(self.checkpoint_dir, "e{}_{}way_{}shot.pth".format(prefix, self.n_way, self.k_shot))
recordname = osp.join(self.checkpoint_dir, "e{}_{}way_{}shot.txt".format(prefix, self.n_way, self.k_shot))
state = {
'episode': prefix,
'fsl': self.fsl.state_dict(),
'epoch': epoch,
"optimizer": None if not final_epoch else self.optim.state_dict()
}
with open(recordname, 'w') as f:
f.write("prefix: {}\nepoch: {}\naccuracy: {}\nh: {}\n".format(prefix, epoch, accuracy, h))
torch.save(state, filename)
def train(self, dataloader, epoch):
losses = AverageMeter()
tqdm_gen = tqdm.tqdm(dataloader)
self.optim.zero_grad()
for episode, (support_x, support_y, query_x, query_y) in enumerate(tqdm_gen):
support_x = support_x.to(self.device)
support_y = support_y.to(self.device)
query_x = query_x.to(self.device)
query_y = query_y.to(self.device)
loss = self.fsl(support_x, support_y, query_x, query_y)
loss_sum = sum(loss.values())
self.optim.zero_grad()
loss_sum.backward()
self.optim.step()
losses.update(loss_sum.item(), len(query_x))
mesg = "epoch {}, loss={:.3f}".format(
epoch,
losses.avg
)
tqdm_gen.set_description(mesg)
def run(self):
print("[={}=]".format(self.prefix))
best_accuracy = 0.0
set_seed(1)
val_dataloader = make_dataloader(self.cfg, phase="val", batch_size=self.cfg.test.batch_size)
for epoch in range(self.train_start_epoch, self.epochs):
train_dataloader = make_dataloader(
self.cfg, phase="train",
batch_size=self.cfg.train.batch_size
)
self.train(train_dataloader, epoch + 1)
self.fsl.eval()
with torch.no_grad():
val_accuracy, h = self.validate(val_dataloader)
if val_accuracy > best_accuracy:
best_accuracy = val_accuracy
self.save_model("best", val_accuracy, h, epoch + 1, True)
mesg = "\t Testing epoch {} validation accuracy: {:.3f}, h: {:.3f}".format(epoch + 1, val_accuracy, h)
print(mesg)
self.lr_scheduler.step()
#self.save_model(epoch + 1, val_accuracy, h, epoch + 1, epoch == (self.epochs - 1))
self.fsl.train()
if self.cfg.train.fix_bn:
self.fix_bn()