forked from zsef123/MixNet-PyTorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathema_runner.py
150 lines (123 loc) · 5.01 KB
/
ema_runner.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
import os
import copy
import time
from glob import glob
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class EMARunner:
def __init__(self, model_type, save_dir, epochs, net, optim, device, loss, logger, scheduler=None):
self.save_dir = save_dir
self.model_type = model_type
self.epochs = epochs
self.logger = logger
self.device = device
self.ema = copy.deepcopy(net.module.cpu())
self.ema.eval()
for p in self.ema.parameters():
p.requires_grad_(False)
self.ema_decay = 0.999
self.net = net.to(device)
self.loss = loss
self.optim = optim
self.scheduler = scheduler
self.start_epoch = 0
self.best_metric = -1
self.load()
def save(self, epoch, filename="train"):
"""Save current epoch model
Save Elements:
model_type : arg.model
start_epoch : current epoch
network : network parameters
optimizer: optimizer parameters
best_metric : current best score
Parameters:
epoch : current epoch
filename : model save file name
"""
torch.save({"model_type": self.model_type,
"start_epoch": epoch + 1,
"network": self.net.module.state_dict(),
"ema": self.ema.state_dict(),
"optimizer": self.optim.state_dict(),
"best_metric": self.best_metric
}, self.save_dir + "/%s.pth.tar" % (filename))
print("Model saved %d epoch" % (epoch))
def load(self, filename=""):
""" Model load. same with save"""
if filename == "":
# load last epoch model
filenames = sorted(glob(self.save_dir + "/*.pth.tar"))
if len(filenames) == 0:
print("Not Load")
return
else:
filename = os.path.basename(filenames[-1])
file_path = self.save_dir + "/" + filename
if os.path.exists(file_path) is True:
print("Load %s to %s File" % (self.save_dir, filename))
ckpoint = torch.load(file_path)
if ckpoint["model_type"] != self.model_type:
raise ValueError("Ckpoint Model Type is %s" %
(ckpoint["model_type"]))
self.net.module.load_state_dict(ckpoint['network'])
self.ema.load_state_dict(ckpoint['ema'])
self.optim.load_state_dict(ckpoint['optimizer'])
self.start_epoch = ckpoint['start_epoch']
self.best_metric = ckpoint["best_metric"]
print("Load Model Type : %s, epoch : %d acc : %f" %
(ckpoint["model_type"], self.start_epoch, self.best_metric))
else:
print("Load Failed, not exists file")
@torch.no_grad()
def update_ema(self):
net_state = self.net.module.state_dict()
ema_state = self.ema.state_dict()
for k, v in ema_state.items():
net_v = net_state[k].detach().cpu()
v.copy_(v * self.ema_decay + net_v * (1 - self.ema_decay))
def train(self, train_loader, val_loader=None):
print("\nStart Train len :", len(train_loader.dataset))
for epoch in range(self.start_epoch, self.epochs):
self.net.train()
for i, (input_, target_) in enumerate(train_loader):
target_ = target_.to(self.device, non_blocking=True)
input_ = input_.to(self.device)
if self.scheduler:
self.scheduler.step()
out = self.net(input_)
loss = self.loss(out, target_)
self.optim.zero_grad()
loss.backward()
self.optim.step()
self.update_ema()
if (i % 50) == 0:
self.logger.log_write("train", epoch=epoch, loss=loss.item())
if val_loader is not None:
self.valid(epoch, val_loader)
def _get_acc(self, loader):
correct = 0
with torch.no_grad():
self.net.eval()
for input_, target_ in loader:
out = self.ema(input_)
out = F.softmax(out, dim=1).cpu()
_, idx = out.max(dim=1)
correct += (target_ == idx).sum().item()
return correct / len(loader.dataset)
def valid(self, epoch, val_loader):
acc = self._get_acc(val_loader)
self.logger.log_write("valid", epoch=epoch, acc=acc)
if acc > self.best_metric:
self.best_metric = acc
self.save(epoch, "epoch[%05d]_acc[%.4f]" % (
epoch, acc))
def test(self, train_loader, val_loader):
print("\n Start Test")
self.load()
train_acc = self._get_acc(train_loader)
valid_acc = self._get_acc(val_loader)
self.logger.log_write("test", fname="test", train_acc=train_acc, valid_acc=valid_acc)
return train_acc, valid_acc