forked from hyh9335/CS766_Project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
218 lines (169 loc) · 7.48 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
#!/usr/bin/env python
# coding: utf-8
import os
import sys
import torch
from util.SRDataset import SRDataset
from model import EdgeModel, SRModel
from util.config import Config
from util.metric import PSNR, EdgeAccuracy
from pytorch_msssim import ssim
from util.config import Config
from model import SRModel
import time
import torch
from torch.utils.data import DataLoader
def train(model_type, config):
'''The process of training
type: the network to be trained, 'edge' means only the edge model,
'sr' means only the sr model, or 'both',
raise a ValueError if it is incorrect
model_type: the configuration, including the dataset, batch size, etc,
should be of type util.Config
A typical setup:
config = Config()
config.BATCH_SIZE = 8
config.DATAPATH = ('dataset', 'celeba-hq')
config.SCALE = 2
train('both', config)
'''
if type(config) is not Config:
raise TypeError('Expect `config` to be of type `util.Config`, got ', type(config), ' instead')
if model_type == 'edge':
train_edge(config)
elif model_type == 'sr':
train_sr(config)
elif model_type == 'generate_edge':
generate_edges(config)
elif model_type == 'both':
train_edge(config)
generate_edges(config)
train_sr(config)
else:
raise ValueError('Expect model_type to be one of `edge`, `sr` and `both`, ', 'got ', model_type)
def generate_edges(config):
scale = config.SCALE
edge_gen_path = os.path.join(*config.MODEL_PATH, "-".join(config.DATAPATH) + "_{0}x_".format(scale)
+ "edge_gen_weights_path.pth")
edge_disc_path = os.path.join(*config.MODEL_PATH, "-".join(config.DATAPATH) + "_{0}x_".format(scale)
+ "edge_disc_weights_path.pth")
model = EdgeModel(config).cuda()
data = torch.load(edge_gen_path)
model.generator.load_state_dict(data['generator'])
data = torch.load(edge_disc_path)
model.discriminator.load_state_dict(data['discriminator'])
data = SRDataset(os.path.join(*config.DATAPATH),
["hr", "lr{0}x".format(scale), "edge"])
data.generate_image('pred_edge_lr{0}x'.format(scale), idx='all', model=model)
def train_edge(config):
model = EdgeModel(config)
edgeacc=EdgeAccuracy()
scale = config.SCALE
edge_gen_path = os.path.join(*config.MODEL_PATH, "-".join(config.DATAPATH) + "_{0}x_".format(scale)
+ "edge_gen_weights_path.pth")
edge_disc_path = os.path.join(*config.MODEL_PATH, "-".join(config.DATAPATH) + "_{0}x_".format(scale)
+ "edge_disc_weights_path.pth")
try:
data = torch.load(edge_gen_path)
model.generator.load_state_dict(data['generator'])
data = torch.load(edge_disc_path)
model.discriminator.load_state_dict(data['discriminator'])
print("Loading checkpoint")
except Exception:
# cannot read checkpoint
print("cannot read checkpoint")
pass
model.cuda()
edgeacc.cuda()
iterations = 1
epochs = 10
data = SRDataset(os.path.join(*config.DATAPATH),
["lr{0}x".format(scale), "hr", "edge_lr{0}x".format(scale), "edge"],
img_list="train.csv")
train_loader = DataLoader(data, batch_size=config.BATCH_SIZE, shuffle=True, num_workers=8, pin_memory=True)
for t in range(epochs):
print('\n\nTraining epoch: %d' % t)
batch = 1
time_start = time.time()
for items in train_loader:
#lr_images, hr_images, lr_edges, hr_edges=items
lr_images, hr_images, lr_edges, hr_edges = (
item.cuda(non_blocking=True) for item in items)
hr_edges_pred, gen_loss, dis_loss, logs = model.process(
lr_images, hr_images, lr_edges, hr_edges)
if batch % 10 == 0:
precision, recall = edgeacc(hr_edges, hr_edges_pred)
logs.update({"precision:": precision.item(), "recall": recall.item()})
time_end = time.time()
logs.update ({"epoch:": t, "iter": batch,
'time cost': time_end - time_start})
with open("-".join(config.DATAPATH) + "_{0}x_".format(scale)
+ "edge_logs.txt", "a", encoding='UTF-8') as f:
f.write("\n"+"\t".join(i for i in sorted(logs)))
f.write("\n"+"\t".join(str(round(logs[i],5)) for i in sorted(logs)))
time_start = time.time()
if iterations % config.SAVE_INTERVAL == 0:
torch.save({'generator': model.generator.state_dict()}, edge_gen_path)
torch.save({'discriminator': model.discriminator.state_dict()}, edge_disc_path)
iterations += 1
batch += 1
print("Done!")
def train_sr(config):
model = SRModel(config)
scale = config.SCALE
sr_gen_path = os.path.join(*config.MODEL_PATH, "-".join(config.DATAPATH) + "_{0}x_".format(scale)
+ "sr_gen_weights_path.pth")
sr_disc_path = os.path.join(*config.MODEL_PATH, "-".join(config.DATAPATH) + "_{0}x_".format(scale)
+ "sr_disc_weights_path.pth")
try:
data = torch.load(sr_gen_path)
model.generator.load_state_dict(data['generator'])
data = torch.load(sr_disc_path)
model.discriminator.load_state_dict(data['discriminator'])
except Exception:
# cannot read checkpoint
pass
# maximum value of the picture is 1
psnr=PSNR(1.)
epochs = 10
data = SRDataset(os.path.join(*config.DATAPATH),
["hr", "lr{0}x".format(scale),
"pred_edge_lr{0}x".format(scale)],
img_list="train.csv")
# num_workers=2 because colab only has 2
train_loader = DataLoader(data, batch_size=config.BATCH_SIZE, shuffle=True, num_workers=config.BATCH_SIZE, pin_memory=True)
iterations = 0
model.cuda()
psnr.cuda()
for t in range(epochs):
print('\n\nTraining epoch: %d' % t)
batch = 1
time_start = time.time()
for items in train_loader:
hr_images, lr_images, hr_edges = (
item.cuda(non_blocking=True) for item in items)
hr_images_pred, gen_loss, dis_loss, logs = model.process(
lr_images, hr_images, hr_edges)
if batch % 10 == 0:
with torch.no_grad():
psnr_val = psnr(hr_images, hr_images_pred)
logs.update({'psnr': psnr_val.item()})
# ssim_val = ssim(hr_images, hr_images_pred, data_range=1.)
# logs.update({"ssim": ssim_val.item()})
time_end = time.time()
logs.update({
"epoch": t,
"iter": batch,
"time cost": time_end - time_start
})
with open("-".join(config.DATAPATH) + "_{0}x_".format(scale)
+ "sr_logs.txt", "a", encoding='UTF-8') as f:
f.write("\n"+"\t".join(i for i in sorted(logs)))
f.write("\n"+"\t".join(str(round(logs[i],5)) for i in sorted(logs)))
time_start = time.time()
batch += 1
iterations += 1
if iterations % config.SAVE_INTERVAL == 0:
torch.save({'generator': model.generator.state_dict()}, sr_gen_path)
torch.save({'discriminator': model.discriminator.state_dict()}, sr_disc_path)
print("Done!")