-
Notifications
You must be signed in to change notification settings - Fork 0
/
trainer.py
217 lines (171 loc) · 8.39 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
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
import os
import math
import torch
import torch.nn as nn
import torch.nn.init as init
import networks
from utils import get_model_list
class Trainer(nn.Module):
def __init__(self, conf):
super(Trainer, self).__init__()
self.lr_dis = conf['lr_dis']
self.lr_gen = conf['lr_gen']
self.model = getattr(networks, conf['model'])(conf)
if 'VGG' in conf['model']:
for param in self.model.gen.encoder.parameters():
param.requires_grad = False
dis_params = list(self.model.dis.parameters())
gen_params = list(self.model.gen.parameters())
self.dis_opt = torch.optim.Adam(
[p for p in dis_params if p.requires_grad],
lr=conf['lr_dis'], weight_decay=conf['weight_decay'])
self.gen_opt = torch.optim.Adam(
[p for p in gen_params if p.requires_grad],
lr=conf['lr_gen'], weight_decay=conf['weight_decay'])
self.apply(weights_init(conf['init']))
def gen_update(self, xs, y, it):
self.gen_opt.zero_grad()
losses = self.model(xs, y, it, 'gen_update')
for item in losses.keys():
self.__setattr__(item, losses[item])
self.gen_opt.step()
def dis_update(self, xs, y, it):
self.dis_opt.zero_grad()
losses = self.model(xs, y, it, 'dis_update')
for item in losses.keys():
self.__setattr__(item, losses[item])
self.dis_opt.step()
def resume(self, checkpoint_dir):
last_model_name = get_model_list(checkpoint_dir, "gen")
state_dict = torch.load(last_model_name)
self.model.gen.load_state_dict(state_dict)
iterations = int(last_model_name[-11:-3])
last_model_name = get_model_list(checkpoint_dir, "dis")
state_dict = torch.load(last_model_name)
self.model.dis.load_state_dict(state_dict)
state_dict = torch.load(os.path.join(checkpoint_dir, 'optimizer.pt'))
self.dis_opt.load_state_dict(state_dict['dis'])
self.gen_opt.load_state_dict(state_dict['gen'])
print('Resume from iteration %d' % iterations)
return iterations
def resume_best_checkpoint(self, checkpoint_dir, gen_model_path, dis_model_path):
state_dict = torch.load(gen_model_path)
self.model.gen.load_state_dict(state_dict)
iterations = int(gen_model_path[-11:-3])
state_dict = torch.load(dis_model_path)
self.model.dis.load_state_dict(state_dict)
state_dict = torch.load(os.path.join(checkpoint_dir, 'optimizer.pt'))
self.dis_opt.load_state_dict(state_dict['dis'])
self.gen_opt.load_state_dict(state_dict['gen'])
print('Resume from iteration %d' % iterations)
return iterations
def save(self, snapshot_dir, iterations, multigpus=False):
this_model = self.model.module if multigpus else self.model
# Save generators, discriminators, and optimizers
gen_name = os.path.join(snapshot_dir, 'gen_%08d.pt' % (iterations + 1))
dis_name = os.path.join(snapshot_dir, 'dis_%08d.pt' % (iterations + 1))
opt_name = os.path.join(snapshot_dir, 'optimizer.pt')
torch.save(this_model.gen.state_dict(), gen_name)
torch.save(this_model.dis.state_dict(), dis_name)
torch.save({'gen': self.gen_opt.state_dict(), 'dis': self.dis_opt.state_dict()}, opt_name)
def load_ckpt(self, ckpt_name):
print('Load checkpoint')
print("\tPath: %s" % ckpt_name)
state_dict = torch.load(ckpt_name)
self.model.gen.load_state_dict(state_dict)
print('Load success')
def generate(self, xs, alphas = None, base_index = None, noise = None):
return self.model.generate(xs, alphas, base_index, noise)
def update_lr(self, iterations, max_iter):
if iterations > (max_iter // 4):
self.gen_opt.param_groups[0]['lr'] -= (self.lr_gen / (3*max_iter / 4))
self.dis_opt.param_groups[0]['lr'] -= (self.lr_dis / (3*max_iter / 4))
#if self.gen_opt.param_groups[0]['lr'] > 0.00001:
# self.gen_opt.param_groups[0]['lr'] *= 0.99998
# self.dis_opt.param_groups[0]['lr'] *= 0.99998
class CrossTrainer(nn.Module):
def __init__(self, conf):
super(CrossTrainer, self).__init__()
self.lr_dis = conf['lr_dis']
self.lr_gen = conf['lr_gen']
self.model = getattr(networks, conf['model'])(conf)
dis_params = list(self.model.dis.parameters())
gen_params = list(self.model.gen.parameters())
self.dis_opt = torch.optim.Adam(
[p for p in dis_params if p.requires_grad],
lr=conf['lr_dis'], weight_decay=conf['weight_decay'])
self.gen_opt = torch.optim.Adam(
[p for p in gen_params if p.requires_grad],
lr=conf['lr_gen'], weight_decay=conf['weight_decay'])
self.apply(weights_init(conf['init']))
def gen_update(self, xs, ss, y):
self.gen_opt.zero_grad()
losses = self.model(xs, ss, y, 'gen_update')
for item in losses.keys():
self.__setattr__(item, losses[item])
self.gen_opt.step()
def dis_update(self, xs, ss, y):
self.dis_opt.zero_grad()
losses = self.model(xs, ss, y, 'dis_update')
for item in losses.keys():
self.__setattr__(item, losses[item])
self.dis_opt.step()
def resume(self, checkpoint_dir):
last_model_name = get_model_list(checkpoint_dir, "gen")
state_dict = torch.load(last_model_name)
self.model.gen.load_state_dict(state_dict['gen'])
iterations = int(last_model_name[-11:-3])
last_model_name = get_model_list(checkpoint_dir, "dis")
state_dict = torch.load(last_model_name)
self.model.dis.load_state_dict(state_dict['dis'])
state_dict = torch.load(os.path.join(checkpoint_dir, 'optimizer.pt'))
self.dis_opt.load_state_dict(state_dict['dis'])
self.gen_opt.load_state_dict(state_dict['gen'])
print('Resume from iteration %d' % iterations)
def save(self, snapshot_dir, iterations, multigpus=False):
this_model = self.model.module if multigpus else self.model
# Save generators, discriminators, and optimizers
gen_name = os.path.join(snapshot_dir, 'gen_%08d.pt' % (iterations + 1))
dis_name = os.path.join(snapshot_dir, 'dis_%08d.pt' % (iterations + 1))
opt_name = os.path.join(snapshot_dir, 'optimizer.pt')
torch.save(this_model.gen.state_dict(), gen_name)
torch.save(this_model.dis.state_dict(), dis_name)
torch.save({'gen': self.gen_opt.state_dict(), 'dis': self.dis_opt.state_dict()}, opt_name)
def load_ckpt(self, ckpt_name):
print('Load checkpoint')
print("\tPath: %s" % ckpt_name)
state_dict = torch.load(ckpt_name)
self.model.gen.load_state_dict(state_dict)
print('Load success')
def generate(self, xs, ss):
return self.model.generate(xs, ss)
def update_lr(self, iterations, max_iter):
x0 = max_iter // 4
lr_gen = self.lr_gen - self.lr_gen*((iterations-x0)/(max_iter-x0))
lr_dis = self.lr_dis - self.lr_dis*((iterations-x0)/(max_iter-x0))
if iterations > x0:
self.gen_opt.param_groups[0]['lr'] = lr_gen#-= (self.lr_gen / (3*max_iter / 4))
self.dis_opt.param_groups[0]['lr'] = lr_dis#-= (self.lr_dis / (3*max_iter / 4))
#if self.gen_opt.param_groups[0]['lr'] > 0.00001:
# self.gen_opt.param_groups[0]['lr'] *= 0.99998
# self.dis_opt.param_groups[0]['lr'] *= 0.99998
def weights_init(init_type='gaussian'):
def init_fun(m):
classname = m.__class__.__name__
if (classname.find('Conv') == 0 or classname.find(
'Linear') == 0) and hasattr(m, 'weight'):
if init_type == 'gaussian':
init.normal_(m.weight.data, 0.0, 0.02)
elif init_type == 'xavier':
init.xavier_normal_(m.weight.data, gain=math.sqrt(2))
elif init_type == 'kaiming':
init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
elif init_type == 'orthogonal':
init.orthogonal_(m.weight.data, gain=math.sqrt(2))
elif init_type == 'default':
pass
else:
assert 0, "Unsupported initialization: {}".format(init_type)
if hasattr(m, 'bias') and m.bias is not None:
init.constant_(m.bias.data, 0.0)
return init_fun