-
Notifications
You must be signed in to change notification settings - Fork 13
/
original_models.py
executable file
·334 lines (268 loc) · 13.3 KB
/
original_models.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
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn import functional as F
import torchvision
from torchvision import models
import pytorch_lightning as pl
class LeakySoftplus(nn.Module):
def __init__(self,negative_slope: float = 0.01 ):
super().__init__()
self.negative_slope=negative_slope
def forward(self,input):
return F.softplus(input)+F.logsigmoid(input)*self.negative_slope
grelu = nn.LeakyReLU(0.2)
#grelu = nn.Softplus()
#grelu = LeakySoftplus(0.2)
#####
# Currently default generator we use
# conv0 -> conv1 -> conv2 -> resnet_blocks -> upconv2 -> upconv1 -> conv_11 -> (conv_11_a)* -> conv_12 -> (Tanh)*
# there are 2 conv layers inside conv_11_a
# * means is optional, model uses skip-connections
class Generator(pl.LightningModule):
def __init__(self, norm_layer='batch_norm', use_bias=False, resnet_blocks=7, tanh=True,
filters=[32, 64, 128, 128, 128, 64], input_channels=3, output_channels=3, append_smoothers=False):
super().__init__()
assert norm_layer in [None, 'batch_norm', 'instance_norm'], \
"norm_layer should be None, 'batch_norm' or 'instance_norm', not {}".format(
norm_layer)
self.norm_layer = None
if norm_layer == 'batch_norm':
self.norm_layer = nn.BatchNorm2d
elif norm_layer == 'instance_norm':
self.norm_layer = nn.InstanceNorm2d
# filters = [f//3 for f in filters]
self.use_bias = use_bias
self.resnet_blocks = resnet_blocks
self.append_smoothers = append_smoothers
stride1 = 2
stride2 = 2
self.conv0 = self.relu_layer(in_filters=input_channels, out_filters=filters[0],
kernel_size=7, stride=1, padding=3,
bias=self.use_bias,
norm_layer=self.norm_layer,
nonlinearity=grelu)
self.conv1 = self.relu_layer(in_filters=filters[0],
out_filters=filters[1],
kernel_size=3, stride=stride1, padding=1,
bias=self.use_bias,
norm_layer=self.norm_layer,
nonlinearity=grelu)
self.conv2 = self.relu_layer(in_filters=filters[1],
out_filters=filters[2],
kernel_size=3, stride=stride2, padding=1,
bias=self.use_bias,
norm_layer=self.norm_layer,
nonlinearity=grelu)
self.resnets = nn.ModuleList()
for i in range(self.resnet_blocks):
self.resnets.append(
self.resnet_block(in_filters=filters[2],
out_filters=filters[2],
kernel_size=3, stride=1, padding=1,
bias=self.use_bias,
norm_layer=self.norm_layer,
nonlinearity=grelu))
self.upconv2 = self.upconv_layer_upsample_and_conv(in_filters=filters[3] + filters[2],
# in_filters=filters[3], # disable skip-connections
out_filters=filters[4],
scale_factor=stride2,
kernel_size=3, stride=1, padding=1,
bias=self.use_bias,
norm_layer=self.norm_layer,
nonlinearity=grelu)
self.upconv1 = self.upconv_layer_upsample_and_conv(in_filters=filters[4] + filters[1],
# in_filters=filters[4], # disable skip-connections
out_filters=filters[4],
scale_factor=stride1,
kernel_size=3, stride=1, padding=1,
bias=self.use_bias,
norm_layer=self.norm_layer,
nonlinearity=grelu)
self.conv_11 = nn.Sequential(
nn.Conv2d(in_channels=filters[0] + filters[4] + input_channels,
# in_channels=filters[4], # disable skip-connections
out_channels=filters[5],
kernel_size=7, stride=1, padding=3, bias=self.use_bias, padding_mode='zeros'),
grelu
)
if self.append_smoothers:
self.conv_11_a = nn.Sequential(
nn.Conv2d(filters[5], filters[5], kernel_size=3,
bias=self.use_bias, padding=1, padding_mode='zeros'),
grelu,
# replace with variable
nn.BatchNorm2d(num_features=filters[5]),
nn.Conv2d(filters[5], filters[5], kernel_size=3,
bias=self.use_bias, padding=1, padding_mode='zeros'),
grelu
)
if tanh:
self.conv_12 = nn.Sequential(nn.Conv2d(filters[5], output_channels,
kernel_size=1, stride=1,
padding=0, bias=True, padding_mode='zeros'),
#torchvision.transforms.Grayscale(num_output_channels=3),
nn.Sigmoid())
else:
self.conv_12 = nn.Conv2d(filters[5], output_channels, kernel_size=1, stride=1,
padding=0, bias=True, padding_mode='zeros')
def log_tensors(self, logger, tag, img_tensor):
logger.experiment.add_images(tag, img_tensor)
def forward(self, input, logger=None, **kwargs):
output_d0 = self.conv0(input)
output_d1 = self.conv1(output_d0)
# comment to disable skip-connections
output_d2 = self.conv2(output_d1)
output = output_d2
for layer in self.resnets:
output = layer(output) + output
output_u2 = self.upconv2(torch.cat((output, output_d2), dim=1))
output_u1 = self.upconv1(torch.cat((output_u2, output_d1), dim=1))
output = torch.cat(
(output_u1, output_d0, input), dim=1)
output_11 = self.conv_11(output)
if self.append_smoothers:
output_11_a = self.conv_11_a(output_11)
else:
output_11_a = output_11
output_12 = self.conv_12(output_11_a)
output = output_12
return output
def relu_layer(self, in_filters, out_filters, kernel_size, stride, padding, bias,
norm_layer, nonlinearity):
out = nn.Sequential()
out.add_module('conv', nn.Conv2d(in_channels=in_filters,
out_channels=out_filters,
kernel_size=kernel_size, stride=stride,
padding=padding, bias=bias, padding_mode='zeros'))
if norm_layer:
out.add_module('normalization',
norm_layer(num_features=out_filters))
if nonlinearity:
out.add_module('nonlinearity', nonlinearity)
# out.add_module('dropout', nn.Dropout2d(0.25))
return out
def resnet_block(self, in_filters, out_filters, kernel_size, stride, padding, bias,
norm_layer, nonlinearity):
out = nn.Sequential()
if nonlinearity:
out.add_module('nonlinearity_0', nonlinearity)
out.add_module('conv_0', nn.Conv2d(in_channels=in_filters,
out_channels=out_filters,
kernel_size=kernel_size, stride=stride,
padding=padding, bias=bias, padding_mode='zeros'))
if norm_layer:
out.add_module('normalization',
norm_layer(num_features=out_filters))
if nonlinearity:
out.add_module('nonlinearity_1', nonlinearity)
out.add_module('conv_1', nn.Conv2d(in_channels=in_filters,
out_channels=out_filters,
kernel_size=kernel_size, stride=stride,
padding=padding, bias=bias, padding_mode='zeros'))
return out
def upconv_layer_upsample_and_conv(self, in_filters, out_filters, scale_factor, kernel_size, stride, padding, bias,
norm_layer, nonlinearity):
parts = [nn.Upsample(scale_factor=scale_factor),
nn.Conv2d(in_filters, out_filters, kernel_size,
stride, padding=padding, bias=False, padding_mode='zeros')
]
if norm_layer:
parts.append(norm_layer(num_features=out_filters))
if nonlinearity:
parts.append(nonlinearity)
return nn.Sequential(*parts)
relu = grelu
#####
# Default discriminator
#####
relu = nn.LeakyReLU(0.2)
class Discriminator(nn.Module):
def __init__(self, num_filters=12, input_channels=3, n_layers=2,
norm_layer='instance_norm', use_bias=True):
super().__init__()
self.num_filters = num_filters
self.input_channels = input_channels
self.use_bias = use_bias
if norm_layer == 'batch_norm':
self.norm_layer = nn.BatchNorm2d
else:
self.norm_layer = nn.InstanceNorm2d
self.net = self.make_net(
n_layers, self.input_channels, 1, 4, 2, self.use_bias)
def make_net(self, n, flt_in, flt_out=1, k=4, stride=2, bias=True):
padding = 1
model = nn.Sequential()
model.add_module('conv0', self.make_block(
flt_in, self.num_filters, k, stride, padding, bias, None, relu))
flt_mult, flt_mult_prev = 1, 1
# n - 1 blocks
for l in range(1, n):
flt_mult_prev = flt_mult
flt_mult = min(2**(l), 8)
model.add_module('conv_%d' % (l), self.make_block(self.num_filters * flt_mult_prev, self.num_filters * flt_mult,
k, stride, padding, bias, self.norm_layer, relu))
flt_mult_prev = flt_mult
flt_mult = min(2**n, 8)
model.add_module('conv_%d' % (n), self.make_block(self.num_filters * flt_mult_prev, self.num_filters * flt_mult,
k, 1, padding, bias, self.norm_layer, relu))
model.add_module('conv_out', self.make_block(
self.num_filters * flt_mult, 1, k, 1, padding, bias, None, None))
return model
def make_block(self, flt_in, flt_out, k, stride, padding, bias, norm, relu):
m = nn.Sequential()
m.add_module('conv', nn.Conv2d(flt_in, flt_out, k,
stride=stride, padding=padding, bias=bias, padding_mode='zeros'))
if norm is not None:
m.add_module('norm', norm(flt_out))
if relu is not None:
m.add_module('relu', relu)
return m
def forward(self, x):
output = self.net(x)
# output = output.mean((2, 3), True)
# output = output.squeeze(-1).squeeze(-1)
# output = output.mean(dim=(-1,-2))
return output
#####
# Perception VGG19 loss
#####
class PerceptualVGG19(nn.Module):
def __init__(self, feature_layers=[0, 3, 5], use_normalization=False):
super().__init__()
# model = models.vgg19(pretrained=True)
model = models.squeezenet1_1(pretrained=True)
model.float()
model.eval()
self.model = model
self.feature_layers = feature_layers
self.mean = torch.FloatTensor([0.485, 0.456, 0.406])
self.mean_tensor = None
self.std = torch.FloatTensor([0.229, 0.224, 0.225])
self.std_tensor = None
self.use_normalization = use_normalization
for param in self.parameters():
param.requires_grad = False
def normalize(self, x):
if not self.use_normalization:
return x
if self.mean_tensor is None:
self.mean_tensor = Variable(
self.mean.view(1, 3, 1, 1).expand(x.shape),
requires_grad=False)
self.std_tensor = Variable(
self.std.view(1, 3, 1, 1).expand(x.shape), requires_grad=False)
x = (x + 1) / 2
return (x - self.mean_tensor) / self.std_tensor
def run(self, x):
features = []
h = x
for f in range(max(self.feature_layers) + 1):
h = self.model.features[f](h)
if f in self.feature_layers:
not_normed_features = h.clone().view(h.size(0), -1)
features.append(not_normed_features)
return torch.cat(features, dim=1)
def forward(self, x):
h = self.normalize(x)
return self.run(h)