forked from hyh9335/CS766_Project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
378 lines (282 loc) · 13.7 KB
/
model.py
File metadata and controls
378 lines (282 loc) · 13.7 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# most comes from github.com/knazeri/edge-informed-sisr, with modification to optimizer steps
import torch
from torch import nn
import torch.nn.functional as F
from torch import optim
from networks import DCGANGenerator, PatchGANDiscriminator
from loss import AdversarialLoss, StyleContentLoss
import numpy as np
import os
class EdgeModel(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
# generator input: [rgb(3) + edge(1)]
# discriminator input: (rgb(3) + edge(1))
generator = DCGANGenerator(use_spectral_norm=True, net_type="edge")
discriminator = PatchGANDiscriminator(in_channels=4, use_sigmoid= config.GAN_LOSS != 'hinge')
l1_loss = nn.L1Loss()
adversarial_loss = AdversarialLoss(type=config.GAN_LOSS) #???
self.add_module('generator', generator)
self.add_module('discriminator', discriminator)
self.add_module('l1_loss', l1_loss)
self.add_module('adversarial_loss', adversarial_loss)
self.gen_optimizer = optim.Adam(
params=generator.parameters(),
lr=float(config.LR),
betas=(config.BETA1, config.BETA2)
)
self.dis_optimizer = optim.Adam(
params=discriminator.parameters(),
lr=float(config.LR),
betas=(config.BETA1, config.BETA2)
)
def dis_step(self, outputs, lr_images, hr_images, lr_edges, hr_edges):
## Update discriminator
self.dis_optimizer.zero_grad()
dis_loss = 0
# process outputs from generator
dis_input_real = torch.cat((hr_images, hr_edges), dim=1)
dis_input_fake = torch.cat((hr_images, outputs.detach()), dim=1)
dis_real, dis_real_feat = self.discriminator(dis_input_real) # in: (rgb(3) + edge(1))
dis_fake, dis_fake_feat = self.discriminator(dis_input_fake) # in: (rgb(3) + edge(1))
#discriminator loss
dis_real_loss = self.adversarial_loss(dis_real, True, True) # loss=1~0 if dis_real=0~1;
dis_fake_loss = self.adversarial_loss(dis_fake, False, True) # loss=1~2 if dis_real=0~1;
dis_loss += (dis_real_loss + dis_fake_loss) / 2
#logs
logs = {
"l_dis": dis_loss.item(),
"dis_fake_loss": dis_fake_loss.item(),
"dis_real_loss": dis_real_loss.item()}
#backward and update
dis_loss.backward()
self.dis_optimizer.step()
return dis_loss.item(), logs
def gen_step(self, outputs, lr_images, hr_images, lr_edges, hr_edges):
## Update generator
self.gen_optimizer.zero_grad()
gen_loss = 0
# process outputs from generator
#Use the same output, since generator hasn't been updated yet
# process outputs from updated discriminator
gen_input_fake = torch.cat((hr_images, outputs), dim=1)
gen_fake, gen_fake_feat = self.discriminator(gen_input_fake) # in: (rgb(3) + edge(1))
"""
We cannot detach these two, because outputs lay behind them
"""
#generator gan loss
gen_gan_loss = self.adversarial_loss(gen_fake, True, False) * self.config.ADV_LOSS_WEIGHT1
gen_loss += gen_gan_loss
# generator feature matching loss #loss=0~-1 if gen_fake=0~1;
# using ground true, process outputs from updated discriminator
dis_input_real = torch.cat((hr_images, hr_edges), dim=1)
dis_real, dis_real_feat = self.discriminator(dis_input_real) # in: (rgb(3) + edge(1))
gen_fm_loss = 0
for i in range(len(dis_real_feat)):
gen_fm_loss += self.l1_loss(gen_fake_feat[i], dis_real_feat[i].detach())
gen_fm_loss = gen_fm_loss * self.config.FM_LOSS_WEIGHT
gen_loss += gen_fm_loss
# create logs
logs = {"l_gen": gen_gan_loss.item(),
"l_fm": gen_fm_loss.item(),
"l_gen_total": gen_loss.item()}
#backward and update
gen_loss.backward()
self.gen_optimizer.step()
return gen_loss.item(), logs
def process(self, lr_images, hr_images, lr_edges, hr_edges):
# process outputs from generator
outputs = self(lr_images, lr_edges)
logs = {}
dis_loss, dlogs = self.dis_step(outputs, lr_images, hr_images, lr_edges, hr_edges)
gen_loss, glogs = self.gen_step(outputs, lr_images, hr_images, lr_edges, hr_edges)
logs.update(dlogs)
logs.update(glogs)
return outputs, gen_loss, dis_loss, logs
def forward(self, lr_images, lr_edges):
hr_images = F.interpolate(lr_images, scale_factor=self.config.SCALE)
hr_edges = F.interpolate(lr_edges, scale_factor=self.config.SCALE)
inputs = torch.cat((hr_images, hr_edges), dim=1)
outputs = self.generator(inputs)
return outputs
class SRModel(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
# generator input: [rgb(3) + edge(1)]
# discriminator input: rgb(3)
self.generator = DCGANGenerator(use_spectral_norm=False, net_type="sr")
self.discriminator = PatchGANDiscriminator(in_channels=3, use_sigmoid= config.GAN_LOSS != 'hinge')
self.l1_loss = nn.L1Loss()
self.adversarial_loss = AdversarialLoss(type=config.GAN_LOSS)
self.style_content_loss = StyleContentLoss()
kernel = np.zeros((self.config.SCALE, self.config.SCALE))
kernel[0, 0] = 1
# (out_channels, in_channels/groups, height, width)
scale_kernel = torch.FloatTensor(np.tile(kernel, (3, 1, 1, 1,)))
self.register_buffer('scale_kernel', scale_kernel)
self.gen_optimizer = optim.Adam(
params=self.generator.parameters(),
lr=float(config.LR),
betas=(config.BETA1, config.BETA2)
)
self.dis_optimizer = optim.Adam(
params=self.discriminator.parameters(),
lr=float(config.LR),
betas=(config.BETA1, config.BETA2)
)
def dis_step(self, outputs, lr_images, hr_images, hr_edges):
## Update discriminator
self.dis_optimizer.zero_grad()
dis_loss = 0
# process outputs from generator
dis_input_fake = outputs.detach()
dis_real, _ = self.discriminator(hr_images)
dis_fake, _ = self.discriminator(dis_input_fake)
#discriminator loss
dis_real_loss = self.adversarial_loss(dis_real, True, True) # loss=1~0 if dis_real=0~1;
dis_fake_loss = self.adversarial_loss(dis_fake, False, True) # loss=1~2 if dis_real=0~1;
dis_loss += (dis_real_loss + dis_fake_loss) / 2
#backward and update
dis_loss.backward()
self.dis_optimizer.step()
return dis_loss.item(), dict([("l_dis", dis_loss.item())])
def gen_step(self, outputs, lr_images, hr_images, hr_edges):
## Update generator
self.gen_optimizer.zero_grad()
gen_loss = 0
# process outputs from generator
#Use the same output, since generator hasn't been updated yet
# process outputs from updated discriminator
gen_input_fake = outputs
gen_fake, gen_fake_feat = self.discriminator(gen_input_fake)
#generator gan loss
gen_gan_loss = self.adversarial_loss(gen_fake, True, False) * self.config.ADV_LOSS_WEIGHT2
gen_loss += gen_gan_loss
# generator l1 loss
gen_l1_loss = self.l1_loss(outputs, hr_images) * self.config.L1_LOSS_WEIGHT
gen_loss += gen_l1_loss
# generator content & style loss
gen_style_loss, gen_content_loss = self.style_content_loss(outputs, hr_images)
gen_content_loss = gen_content_loss * self.config.CONTENT_LOSS_WEIGHT
gen_style_loss = gen_style_loss * self.config.STYLE_LOSS_WEIGHT
gen_loss += gen_content_loss
gen_loss += gen_style_loss
'''
# using ground true, process outputs from updated discriminator
dis_input_real = hr_images
dis_real, dis_real_feat = self.discriminator(dis_input_real)
gen_fm_loss = 0
for i in range(len(dis_real_feat)):
gen_fm_loss += self.l1_loss(gen_fake_feat[i], dis_real_feat[i].detach())
gen_fm_loss = gen_fm_loss * self.config.FM_LOSS_WEIGHT
gen_loss += gen_fm_loss
'''
# create logs
logs = [
("l_gen", gen_gan_loss.item()),
("l_l1", gen_l1_loss.item()),
("l_content", gen_content_loss.item()),
("l_style", gen_style_loss.item())]
# ("l_fm", gen_fm_loss.item())
logs = dict(logs)
gen_loss.backward()
self.gen_optimizer.step()
return gen_loss.item(), logs
def process(self, lr_images, hr_images, hr_edges):
# process outputs from generator
outputs = self(lr_images, hr_edges)
logs = {}
dis_loss, dlogs = self.dis_step(outputs, lr_images, hr_images, hr_edges)
gen_loss, glogs = self.gen_step(outputs, lr_images, hr_images, hr_edges)
logs.update(dlogs)
logs.update(glogs)
return outputs, dis_loss, gen_loss, logs
def forward(self, lr_images, hr_edges):
hr_images = F.conv_transpose2d(lr_images, self.scale_kernel, stride=self.config.SCALE, groups=3)
inputs = torch.cat((hr_images, hr_edges), dim=1)
outputs = self.generator(inputs)
return outputs
class FullModel(nn.Module):
def __init__(self, config, load=True):
super().__init__()
self.config = config
self.edge_model = EdgeModel(config)
self.sr_model = SRModel(config)
scale = config.SCALE
if load:
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")
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)
self.sr_model.generator.load_state_dict(data['generator'])
data = torch.load(sr_disc_path)
self.sr_model.discriminator.load_state_dict(data['discriminator'])
data = torch.load(edge_gen_path)
self.edge_model.generator.load_state_dict(data['generator'])
data = torch.load(edge_disc_path)
self.edge_model.discriminator.load_state_dict(data['discriminator'])
except Exception:
# cannot read checkpoint, reraise the exception
print("Cannot find the SR model!")
raise
def forward(self, lr_images, lr_edges):
hr_edges = self.edge_model(lr_images, lr_edges)
outputs = self.sr_model(lr_images, hr_edges)
return outputs
class EdgeCNN(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
# generator input: [rgb(3) + edge(1)]
# discriminator input: (rgb(3) + edge(1))
generator = DCGANGenerator(use_spectral_norm=True, net_type="edge")
l1_loss = nn.L1Loss()
l2_loss = nn.MSELoss()
self.add_module('generator', generator)
self.add_module('l2_loss', l2_loss)
self.gen_optimizer = optim.Adam(
params=generator.parameters(),
lr=float(config.LR),
betas=(config.BETA1, config.BETA2)
)
def gen_step(self, outputs, lr_images, hr_images, lr_edges, hr_edges):
## Update generator
self.gen_optimizer.zero_grad()
gen_loss = 0
# process outputs from generator
#Use the same output, since generator hasn't been updated yet
# process outputs from updated discriminator
"""
We cannot detach these two, because outputs lay behind them
"""
#generator gan loss
# generator feature matching loss #loss=0~-1 if gen_fake=0~1;
# using ground true, process outputs from updated discriminator
gen_loss += self.l2_loss(outputs, hr_edges)
# create logs
logs = {"l_gen": gen_loss.item()}
#backward and update
gen_loss.backward()
self.gen_optimizer.step()
return gen_loss.item(), logs
def process(self, lr_images, hr_images, lr_edges, hr_edges):
# process outputs from generator
outputs = self(lr_images, lr_edges)
logs = {}
gen_loss, glogs = self.gen_step(outputs, lr_images, hr_images, lr_edges, hr_edges)
logs.update(glogs)
return outputs, gen_loss, 'dis_loss', logs
def forward(self, lr_images, lr_edges):
hr_images = F.interpolate(lr_images, scale_factor=self.config.SCALE)
hr_edges = F.interpolate(lr_edges, scale_factor=self.config.SCALE)
inputs = torch.cat((hr_images, hr_edges), dim=1)
outputs = self.generator(inputs)
return outputs