-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmodel.py
258 lines (209 loc) · 10.4 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
# -*- coding: utf-8 -*-
from ops import *
def g_conv(input_x, in_channels, out_channels, kernel_size, padding, nonlinearity, init, param=None,
to_sequential=True, use_wscale=True, use_batchnorm=False, use_pixelnorm=True):
layer = input_x
layer +=[nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1, padding=padding)]
# he kaiming's initializer
# he_init(layer, nonlinearity='conv2d', param=None)
he_init(layer[-1], init, param)
if use_wscale:
layer += [w_scale_layer(layer[-1])]
#layer += [nonlinearity]
if use_batchnorm:
layer += [nn.BatchNorm2d(out_channels)]
layer += [nonlinearity]
if use_pixelnorm:
layer += [pixel_norm_layer()]
if to_sequential:
return nn.Sequential(*layer)
# what does * mean here
else:
return layer
def to_from_rgb(input_x, in_channels, out_channels, nonlinearity, init, param=None, use_wscale=True, to_sequential=True):
layer = input_x
layer += [nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0)]
he_init(layer[-1], init, param)
if use_wscale:
layer += [w_scale_layer(layer[-1])]
if not(nonlinearity=='linear'):
layer += [nonlinearity]
if to_sequential:
return nn.Sequential(*layer)
else:
return layer
class generator(nn.Module):
def __init__(self,
num_channels = 3, # Overridden based on dataset.
resolution = 32, # Overridden based on dataset.
#label_size = 0, # Overridden based on dataset.
feature_map_base = 4096,
feature_map_decay = 1.0,
feature_map_max = 512,
latent_size = None,
normalize_latents = True,
use_wscale = True,
use_pixelnorm = True,
use_leakyrelu = True,
use_batchnorm = False,
tanh_at_end = None
):
super(generator, self).__init__()
self.num_channels = num_channels
self.resolution = resolution
self.feature_map_base = feature_map_base
self.feature_map_decay = feature_map_decay
self.feature_map_max = feature_map_max
self.latent_size = latent_size
self.normalize_latents = normalize_latents
self.use_wscale = use_wscale
self.use_pixelnorm = use_pixelnorm
self.use_leakyrelu = use_leakyrelu
self.use_batchnorm = use_batchnorm
self.tanh_at_end = tanh_at_end
R = int(np.log2(resolution))
if self.latent_size is None:
# self.latent_size = self.feature_map_max
self.latent_size = self.get_num_fmaps(0)
slope = 0.2
act = nn.LeakyReLU(negative_slope=slope) if self.use_leakyrelu else nn.ReLU()
init_act = 'leaky_relu' if self.use_leakyrelu else 'relu'
output_act = nn.Tanh() if self.tanh_at_end else 'linear'
output_init_act = 'tanh' if self.tanh_at_end else 'linear'
pre = None
net_layers = nn.ModuleList()
rgb_layer = nn.ModuleList()
layer = []
if self.normalize_latents:
pre = pixel_norm_layer()
#if self.label_size:
# layer += [concate_layer()]
# first block
layer += [reshape_layer([self.latent_size, 1, 1])]
"""g_conv(input_x,
in_channels,
out_channels,
kernel_size,
padding,
nonlinearity,
init,
param=None,
to_sequential=True,
use_wscale=True,
use_batchnorm=False,
use_pixelnorm==True):
"""
layer = g_conv(layer, self.latent_size, self.get_num_fmaps(1), 4, 3, act, init_act, slope, False, self.use_wscale, self.use_batchnorm, self.use_pixelnorm)
net = g_conv(layer, latent_size, self.get_num_fmaps(1), 3, 1, act, init_act, slope, True, self.use_wscale, self.use_batchnorm, self.use_pixelnorm)
net_layers.append(net)
# to_rgb layer
rgb_layer.append(to_from_rgb([], self.get_num_fmaps(1), self.num_channels, output_act, output_init_act, None, True, self.use_wscale))
for r in range(2, R): # following blocks
in_channels = self.get_num_fmaps(r-1)
out_channels = self.get_num_fmaps(r)
# upsample
layer = [nn.Upsample(scale_factor=2, mode='nearest')]
#layer = [nn.UpsamplingNearest2d(scale_factor=2)]
layer = g_conv(layer, in_channels, out_channels, 3, 1, act, init_act, slope, False, self.use_wscale, self.use_batchnorm, self.use_pixelnorm)
net = g_conv(layer, out_channels, out_channels, 3, 1, act, init_act, slope, True, self.use_wscale, self.use_batchnorm, self.use_pixelnorm)
net_layers.append(net)
# to_rgb layer
rgb_layer.append(to_from_rgb([], out_channels, self.num_channels, output_act, output_init_act, None, True, self.use_wscale))
self.output_layer = g_select_layer(pre, net_layers, rgb_layer)
def get_num_fmaps(self, stage):
return min(int(self.feature_map_base / (2.0 ** (stage * self.feature_map_decay))), self.feature_map_max)
def forward(self, input_x, input_y=None, cur_level=None, insert_y_at=None):
return self.output_layer(input_x, input_y, cur_level, insert_y_at)
def d_conv(input_x, in_channels, out_channels, kernel_size, padding, nonlinearity, init, param=None,to_sequential=True, use_wscale=True, use_gdrop=True, use_instance_norm=False, gdrop_param=dict()):
layer = input_x
if use_gdrop:
layer += [g_drop_layer(**gdrop_param)]
layer += [nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1, padding=padding)]
he_init(layer[-1], init, param)
if use_wscale:
layer += [w_scale_layer(layer[-1])]
layer += [nonlinearity]
if use_instance_norm:
layer += [instance_norm_layer()]
#layer += [nonlinearity]
if to_sequential:
return nn.Sequential(*layer)
else:
return layer
class discriminator(nn.Module):
def __init__(self,
num_channels = 3, # Overridden based on dataset.
resolution = 32, # Overridden based on dataset.
feature_map_base = 4096,
feature_map_decay = 1.0,
feature_map_max = 256,
mbstat_avg = 'all',
mbdisc_kernels = None,
use_wscale = True,
use_gdrop = True,
use_layernorm = False,
sigmoid_at_end = False):
super(discriminator, self).__init__()
self.num_channels = num_channels
self.resolution = resolution
self.feature_map_base = feature_map_base
self.feature_map_decay = feature_map_decay
self.feature_map_max = feature_map_max
self.mbstat_avg = mbstat_avg
self.mbdisc_kernels = mbdisc_kernels
self.use_wscale = use_wscale
self.use_gdrop = use_gdrop
self.use_layernorm = use_layernorm
self.sigmoid_at_end = sigmoid_at_end
R = int(np.log2(resolution))
slope = 0.2
act = nn.LeakyReLU(negative_slope = slope)
init_act = 'leaky_relu'
output_act = nn.Sigmoid() if self.sigmoid_at_end else 'linear'
output_init_act = 'sigmoid' if self.sigmoid_at_end else 'linear'
gdrop_strength = 0.0
gdrop_param = {'mode': 'prop', 'strength': gdrop_strength}
net_layers = nn.ModuleList()
rgb_layer = nn.ModuleList()
pre = None
layer = []
rgb_layer.append(to_from_rgb([], self.num_channels, self.get_num_fmaps(R-1), act, init_act, slope, True, self.use_wscale))
for r in range(R-1, 1, -1):
in_channels = self.get_num_fmaps(r)
out_channels = self.get_num_fmaps(r-1)
layer = d_conv([], in_channels, in_channels, 3, 1, act, init_act, slope, False,
self.use_wscale, self.use_gdrop, self.use_layernorm, gdrop_param)
layer = d_conv(layer, in_channels, out_channels, 3, 1, act, init_act, slope, False,
self.use_wscale, self.use_gdrop, self.use_layernorm, gdrop_param)
layer += [nn.AvgPool2d(kernel_size=2, stride=2, ceil_mode=False, count_include_pad=False)]
net_layers.append(nn.Sequential(*layer))
# nin = [nn.AvgPool2d(kernel_size=2, stride=2, ceil_mode=False, count_include_pad=False)]
rgb_layer_ = to_from_rgb([], self.num_channels, out_channels, act, init_act, slope, True, self.use_wscale)
rgb_layer.append(rgb_layer_)
layer = []
in_channels = self.get_num_fmaps(1)
out_channels = self.get_num_fmaps(1)
if self.mbstat_avg is not None:
layer += [minibatch_stddev_concatlayer(averaging=self.mbstat_avg)]
in_channels += 1
layer = d_conv(layer, in_channels, out_channels, 3, 1, act, init_act, slope, False,
self.use_wscale, self.use_gdrop, self.use_layernorm, gdrop_param)
layer = d_conv(layer, out_channels, self.get_num_fmaps(0), 4, 0, act, init_act, slope, False,
self.use_wscale, self.use_gdrop, self.use_layernorm, gdrop_param)
#if self.mbdisc_kernels:
# layer += [MinibatchDiscriminationLayer(num_kernels=self.mbdisc_kernels)]
net_layers.append(to_from_rgb(layer, self.get_num_fmaps(0), out_channels, output_act, output_init_act, None, True, self.use_wscale))
self.output_layer = d_select_layer(pre, net_layers, rgb_layer)
def get_num_fmaps(self, stage):
return min(int(self.feature_map_base / (2.0 ** (stage * self.feature_map_decay))), self.feature_map_max)
def forward(self, input_x, input_y=None, cur_level=None, insert_y_at=None, gdrop_strength=0.0):
for module in self.modules():
if hasattr(module, 'strength'):
module.strength = gdrop_strength
return self.output_layer(input_x, input_y, cur_level, insert_y_at)
if __name__=='__main__':
print('test in model')
G = generator(latent_size=512)
D = discriminator()
print(G)
print(D)