-
Notifications
You must be signed in to change notification settings - Fork 15
/
model.py
378 lines (307 loc) · 14 KB
/
model.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
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
import sys
import torch
import torch.nn as nn
from option import args
from collections import OrderedDict
# ------helper functions------ #
def pad(pad_type, padding):
pad_type = pad_type.lower()
if padding == 0:
return None
def get_valid_padding(kernel_size, dilation):
kernel_size = kernel_size + (kernel_size - 1) * (dilation - 1)
padding = (kernel_size - 1) // 2
return padding
def activation(act_type=args.act_type, slope=0.2, n_prelu=1):
act_type = act_type.lower()
if act_type == 'prelu':
layer = nn.PReLU(num_parameters=n_prelu, init=slope)
else:
raise NotImplementedError('[ERROR] Activation layer [%s] is not implemented!' % act_type)
return layer
def norm(n_feature, norm_type='bn'):
norm_type = norm_type.lower()
layer = None
if norm_type == 'bn':
layer = nn.BatchNorm2d(n_feature)
else:
raise NotImplementedError('[ERROR] Normalization layer [%s] is not implemented!' % norm_type)
return layer
def sequential(*args):
if len(args) == 1:
if isinstance(args[0], OrderedDict):
raise NotImplementedError('[ERROR] %s.sequential() does not support OrderedDict' % sys.modules[__name__])
else:
return args[0]
modules = []
for module in args:
if isinstance(module, nn.Sequential):
for submodule in module:
modules.append(submodule)
elif isinstance(module, nn.Module):
modules.append(module)
return nn.Sequential(*modules)
# ------build blocks------ #
def ConvBlock(in_channels, out_channels, kernel_size, stride=1, dilation=1, bias=True, valid_padding=True, padding=0,
act_type='prelu', norm_type='bn', pad_type='zero'):
if valid_padding:
padding = get_valid_padding(kernel_size, dilation)
else:
pass
p = pad(pad_type, padding) if pad_type and pad_type != 'zero' else None
conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, dilation=dilation,
bias=bias)
act = activation(act_type) if act_type else None
n = norm(out_channels, norm_type) if norm_type else None
return sequential(p, conv, n, act)
def DeconvBlock(in_channels, out_channels, kernel_size, stride=1, dilation=1, bias=True, padding=0, act_type='relu',
norm_type='bn', pad_type='zero'):
p = pad(pad_type, padding) if pad_type and pad_type != 'zero' else None
deconv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding, dilation=dilation, bias=bias)
act = activation(act_type) if act_type else None
n = norm(out_channels, norm_type) if norm_type else None
return sequential(p, deconv, n, act)
# ------build SRB ------ #
class SRB(nn.Module):
def __init__(self, norm_type):
super(SRB, self).__init__()
upscale_factor = args.scale
if upscale_factor == 2:
stride = 2
padding = 2
kernel_size = 6
elif upscale_factor == 4:
stride = 4
padding = 2
kernel_size = 8
self.num_groups = args.num_groups
num_features = args.num_features
act_type = args.act_type
self.compress_in = ConvBlock(num_features, num_features, kernel_size=1, act_type=act_type, norm_type=norm_type)
self.upBlocks = nn.ModuleList()
self.downBlocks = nn.ModuleList()
self.uptranBlocks = nn.ModuleList()
self.downtranBlocks = nn.ModuleList()
for idx in range(self.num_groups):
self.upBlocks.append(
DeconvBlock(num_features, num_features, kernel_size=kernel_size, stride=stride, padding=padding,
act_type=act_type, norm_type=norm_type))
self.downBlocks.append(
ConvBlock(num_features, num_features, kernel_size=kernel_size, stride=stride, padding=padding,
act_type=act_type, norm_type=norm_type, valid_padding=False))
if idx > 0:
self.uptranBlocks.append(
ConvBlock(num_features * (idx + 1), num_features, kernel_size=1, stride=1, act_type=act_type,
norm_type=norm_type))
self.downtranBlocks.append(
ConvBlock(num_features * (idx + 1), num_features, kernel_size=1, stride=1, act_type=act_type,
norm_type=norm_type))
self.compress_out = ConvBlock(self.num_groups * num_features, num_features, kernel_size=1, act_type=act_type,
norm_type=norm_type)
self.last_hidden = None
def forward(self, f_in):
# use cuda
f = torch.zeros(f_in.size()).cuda()
f.copy_(f_in)
f = self.compress_in(f)
lr_features = []
hr_features = []
lr_features.append(f)
for idx in range(self.num_groups):
LD_L = torch.cat(tuple(lr_features), 1)
if idx > 0:
LD_L = self.uptranBlocks[idx - 1](LD_L)
LD_H = self.upBlocks[idx](LD_L)
hr_features.append(LD_H)
LD_H = torch.cat(tuple(hr_features), 1)
if idx > 0:
LD_H = self.downtranBlocks[idx - 1](LD_H)
LD_L = self.downBlocks[idx](LD_H)
lr_features.append(LD_L)
del hr_features
g = torch.cat(tuple(lr_features[1:]), 1)
g = self.compress_out(g)
return g
# ------build CFB ------ #
class CFB(nn.Module):
def __init__(self, norm_type):
super(CFB, self).__init__()
upscale_factor = args.scale
if upscale_factor == 2:
stride = 2
padding = 2
kernel_size = 6
elif upscale_factor == 4:
stride = 4
padding = 2
kernel_size = 8
self.num_groups = args.num_groups
num_features = args.num_features
act_type = args.act_type
self.compress_in = ConvBlock(3 * num_features, num_features, kernel_size=1, act_type=act_type,
norm_type=norm_type)
self.upBlocks = nn.ModuleList()
self.downBlocks = nn.ModuleList()
self.uptranBlocks = nn.ModuleList()
self.downtranBlocks = nn.ModuleList()
self.re_guide = ConvBlock(2 * num_features, num_features, kernel_size=1, act_type=act_type,
norm_type=norm_type)
for idx in range(self.num_groups):
self.upBlocks.append(
DeconvBlock(num_features, num_features, kernel_size=kernel_size, stride=stride, padding=padding,
act_type=act_type, norm_type=norm_type))
self.downBlocks.append(
ConvBlock(num_features, num_features, kernel_size=kernel_size, stride=stride, padding=padding,
act_type=act_type, norm_type=norm_type, valid_padding=False))
if idx > 0:
self.uptranBlocks.append(
ConvBlock(num_features * (idx + 1), num_features, kernel_size=1, stride=1, act_type=act_type,
norm_type=norm_type))
self.downtranBlocks.append(
ConvBlock(num_features * (idx + 1), num_features, kernel_size=1, stride=1, act_type=act_type,
norm_type=norm_type))
self.compress_out = ConvBlock(self.num_groups * num_features, num_features, kernel_size=1, act_type=act_type,
norm_type=norm_type)
def forward(self, f_in, g1, g2):
x = torch.cat((f_in, g1), dim=1)
x = torch.cat((x, g2), dim=1)
x = self.compress_in(x)
lr_features = []
hr_features = []
lr_features.append(x)
for idx in range(self.num_groups):
LD_L = torch.cat(tuple(lr_features), 1)
if idx > 0:
LD_L = self.uptranBlocks[idx - 1](LD_L)
LD_H = self.upBlocks[idx](LD_L)
hr_features.append(LD_H)
LD_H = torch.cat(tuple(hr_features), 1)
if idx > 0:
LD_H = self.downtranBlocks[idx - 1](LD_H)
LD_L = self.downBlocks[idx](LD_H)
if idx == 2:
x_mid = torch.cat((LD_L, g2), dim=1)
LD_L = self.re_guide(x_mid)
lr_features.append(LD_L)
del hr_features
output = torch.cat(tuple(lr_features[1:]), 1)
output = self.compress_out(output)
return output
# ------build CFNet ------ #
class CFNet(nn.Module):
def __init__(self, in_channels=args.in_channels, out_channels=args.out_channels, num_features=args.num_features,
num_steps=args.num_steps, upscale_factor=args.scale,
act_type=args.act_type,
norm_type=None,
num_cfbs=args.num_cfbs):
super(CFNet, self).__init__()
if upscale_factor == 2:
stride = 2
padding = 2
kernel_size = 6
elif upscale_factor == 4:
stride = 4
padding = 2
kernel_size = 8
self.num_steps = num_steps
self.num_features = num_features
self.upscale_factor = upscale_factor
self.num_cfbs = num_cfbs
# upscale_1
self.upsample_over = nn.Upsample(scale_factor=upscale_factor, mode='bilinear', align_corners=False)
# FEB_1
self.conv_in_over = ConvBlock(in_channels, 4 * num_features, kernel_size=3, act_type=act_type,
norm_type=norm_type)
self.feat_in_over = ConvBlock(4 * num_features, num_features, kernel_size=1, act_type=act_type,
norm_type=norm_type)
# SRB_1
self.srb_1 = SRB(norm_type)
# REC_1
self.out_over = DeconvBlock(num_features, num_features, kernel_size=kernel_size, stride=stride, padding=padding,
act_type='prelu', norm_type=norm_type)
self.conv_out_over = ConvBlock(num_features, out_channels, kernel_size=3, act_type=None, norm_type=norm_type)
# upscale_2
self.upsample_under = nn.Upsample(scale_factor=upscale_factor, mode='bilinear', align_corners=False)
# FEB_2
self.conv_in_under = ConvBlock(in_channels, 4 * num_features, kernel_size=3, act_type=None, norm_type=norm_type)
self.feat_in_under = ConvBlock(4 * num_features, num_features, kernel_size=1, act_type=act_type,
norm_type=norm_type)
# SRB_2
self.srb_2 = SRB(norm_type)
# REC_2
self.out_under = DeconvBlock(num_features, num_features, kernel_size=kernel_size, stride=stride,
padding=padding,
act_type=args.act_type, norm_type=norm_type)
self.conv_out_under = ConvBlock(num_features, out_channels, kernel_size=3, act_type=None, norm_type=norm_type)
# CFBs and RECs
self.CFBs_1 = []
self.CFBs_2 = []
self.out_1 = nn.ModuleList()
self.conv_out_1 = nn.ModuleList()
self.out_2 = nn.ModuleList()
self.conv_out_2 = nn.ModuleList()
for i in range(self.num_cfbs):
cfb_over = 'cfb_over{}'.format(i)
cfb_under = 'cfb_under{}'.format(i)
cfb_1 = CFB(norm_type).cuda()
cfb_2 = CFB(norm_type).cuda()
setattr(self, cfb_over, cfb_1)
self.CFBs_1.append(getattr(self, cfb_over))
setattr(self, cfb_under, cfb_2)
self.CFBs_2.append(getattr(self, cfb_under))
self.out_1.append(
DeconvBlock(num_features, num_features, kernel_size=kernel_size, stride=stride, padding=padding,
act_type=args.act_type, norm_type=norm_type))
self.conv_out_1.append(
ConvBlock(num_features, out_channels, kernel_size=3, act_type=None, norm_type=norm_type))
self.out_2.append(
DeconvBlock(num_features, num_features, kernel_size=kernel_size, stride=stride, padding=padding,
act_type=args.act_type, norm_type=norm_type))
self.conv_out_2.append(
ConvBlock(num_features, out_channels, kernel_size=3, act_type=None, norm_type=norm_type))
# def forward(self, lr_over, lr_under):
def forward(self, lr_over, lr_under):
# upsampled version of input pairs
up_over = self.upsample_over(lr_over)
up_under = self.upsample_under(lr_under)
# Feature extraction block
f_in_over = self.conv_in_over(lr_over)
f_in_over = self.feat_in_over(f_in_over)
f_in_under = self.conv_in_under(lr_under)
f_in_under = self.feat_in_under(f_in_under)
# Super-resolution block
g_over = self.srb_1(f_in_over)
g_under = self.srb_2(f_in_under)
# Coupled feedback block
g_1 = [g_over]
g_2 = [g_under]
for i in range(self.num_cfbs):
g_1.append(self.CFBs_1[i](f_in_over, g_1[i], g_2[i]))
g_2.append(self.CFBs_2[i](f_in_under, g_2[i], g_1[i]))
# Reconstruction
res_1 = []
res_2 = []
res_over = self.out_over(g_over)
res_over = self.conv_out_over(res_over)
res_1.append(res_over)
res_under = self.out_under(g_under)
res_under = self.conv_out_under(res_under)
res_2.append(res_under)
for j in range(self.num_cfbs):
res_o = self.out_1[j](g_1[j + 1])
res_u = self.out_2[j](g_2[j + 1])
res_1.append(self.conv_out_1[j](res_o))
res_2.append(self.conv_out_2[j](res_u))
# Output
sr_over = []
sr_under = []
for k in range(self.num_cfbs + 1):
image_over = torch.add(res_1[k], up_over)
image_over = torch.clamp(image_over, -1.0, 1.0)
image_over = (image_over + 1) * 127.5
image_under = torch.add(res_2[k], up_under)
image_under = torch.clamp(image_under, -1.0, 1.0)
image_under = (image_under + 1) * 127.5
sr_over.append(image_over)
sr_under.append(image_under)
return sr_over, sr_under