-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathCNNModules.py
306 lines (238 loc) · 12.7 KB
/
CNNModules.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
import torch.nn as nn
import torch.nn.functional as F
from debug_tools import *
# ------------------------------------------------------------------------------
class ResNetBlock(nn.Module):
def __init__(self,
in_channels, # Number of input channels.
kernel_size=3):
super(ResNetBlock, self).__init__()
self.in_channels = in_channels
self.kernel_size = kernel_size
self.cont_conv = nn.Conv2d(in_channels=self.in_channels, out_channels=self.in_channels,
kernel_size=self.kernel_size, stride=1,
padding=((kernel_size - 1) // 2, (kernel_size - 1) // 2))
self.sigma = F.leaky_relu
# conv = torch.nn.Conv2d(in_channels, in_channels, kernel_size, 1, 1)
# bn = torch.nn.InstanceNorm2d(num_features)
# relu = torch.nn.ReLU(True)
# relu = torch.nn.GELU()
# self.resnet_block = torch.nn.Sequential(
# cont_conv,
# conv)
def forward(self, x):
# out = self.cont_conv(x)
# out = self.sigma(out)
p = 0.1
return self.cont_conv(self.sigma(x)) * p + (1 - p) * x
class Conv2D(nn.Module):
def __init__(self,
in_channels, # Number of input channels.
N_layers, # Number of layers in the network
N_res,
kernel_size=3,
multiply=32
): # Number of ResNet Blocks
super(Conv2D, self).__init__()
assert N_layers % 2 == 0, "Number of layers myst be even number."
self.N_layers = N_layers
#######################################################################################
self.channel_multiplier = multiply
in_size = 33
self.in_size = 33
self.feature_maps = [in_channels]
for i in range(0, self.N_layers // 2):
self.feature_maps.append(2 ** i * self.channel_multiplier)
for i in range(self.N_layers // 2 - 2, -1, -1):
self.feature_maps.append(2 ** i * self.channel_multiplier)
self.feature_maps.append(1)
# Define the size of the data for each layer (note that we downsample/usample)
self.size = []
for i in range(0, self.N_layers // 2 + 1):
self.size.append(in_size // (2 ** i))
for i in range(self.N_layers // 2 - 1, -1, -1):
self.size.append(in_size // (2 ** i))
# Define the sizes & number of channels for layers where you x2 upsample and x2 downsample
# Note: no changing in the sampling rate in the end of this operation
# Note: we call this operation size_invariant
# Note: the size and # of feature maps is the same as before, but we define them for convenience
self.size_inv = self.size[:-1]
self.feature_maps_invariant = self.feature_maps[:-1]
print("size: ", self.size)
print("channels: ", self.feature_maps)
assert len(self.feature_maps) == self.N_layers + 1
self.kernel_size = kernel_size
self.cont_conv_layers = nn.ModuleList([nn.Conv2d(self.feature_maps[i],
self.feature_maps[i + 1],
kernel_size=self.kernel_size, stride=1,
padding=((kernel_size - 1) // 2, (kernel_size - 1) // 2))
for i in range(N_layers)])
self.cont_conv_layers_invariant = nn.ModuleList([nn.Conv2d(self.feature_maps_invariant[i],
self.feature_maps_invariant[i],
kernel_size=self.kernel_size, stride=1,
padding=((kernel_size - 1) // 2, (kernel_size - 1) // 2))
for i in range(N_layers)])
self.sigma = F.leaky_relu
"""
self.cont_conv_layers_invariant = nn.ModuleList([(SynthesisLayer(w_dim=1,
is_torgb=False,
is_critically_sampled=False,
use_fp16=False,
# Input & output specifications.
in_channels=self.feature_maps_invariant[i],
out_channels=self.feature_maps_invariant[i],
in_size=self.size_inv[i],
out_size=self.size_inv[i],
in_sampling_rate=self.size_inv[i],
out_sampling_rate=self.size_inv[i],
in_cutoff=self.size_inv[i] // cutoff_den,
out_cutoff=self.size_inv[i] // cutoff_den,
in_half_width=in_half_width,
out_half_width=out_half_width))
for i in range(N_layers)])
"""
# Define the resnet block --> ##### TO BE DISCUSSED ######
self.resnet_blocks = []
# print(self.feature_maps[self.N_layers // 2], )
for i in range(N_res):
self.resnet_blocks.append(ResNetBlock(in_channels=self.feature_maps[self.N_layers // 2]))
self.resnet_blocks = nn.Sequential(*self.resnet_blocks)
self.N_res = N_res
self.upsample4 = nn.Upsample(scale_factor=4)
self.upsample2 = nn.Upsample(scale_factor=2)
self.downsample2 = nn.AvgPool2d(2, stride=2, padding=0)
self.downsample4 = nn.AvgPool2d(4, stride=4, padding=1)
self.last = nn.Upsample(size=in_size)
def forward(self, x):
# Execute the left part of the network
# print("")
for i in range(self.N_layers // 2):
# print("BEFORE I1",x.shape)
y = self.cont_conv_layers_invariant[i](x)
# print("After I1",y.shape)
y = self.sigma(self.upsample2(y))
# print("After US1",y.shape)
x = self.downsample2(y)
# print("AFTER IS1",x.shape)
# print("INV DONE")
y = (self.cont_conv_layers[i](x))
# print("AFTER CONTCONV", y.shape)
y = self.upsample2(y)
# print("AFTER UP", y.shape)
x = self.downsample4(self.sigma(y))
# print("AFTER IS2",x.shape)
for i in range(self.N_res):
x = self.resnet_blocks[i](x)
# print("RES",x.shape)
# Execute the right part of the network
for i in range(self.N_layers // 2, self.N_layers):
x = self.downsample2(self.sigma(self.upsample2(self.cont_conv_layers_invariant[i](x))))
# print("AFTER INV",x.shape)
x = self.downsample2(self.sigma(self.upsample4(self.cont_conv_layers[i](x))))
# print("AFTER CONTC",x.shape)
# print(x.shape[2])
# print("BEFORE LAST",x.shape)
# print("-------------")
# print(" ")
return self.last(x)
def get_n_params(self):
pp = 0
for p in list(self.parameters()):
nn = 1
for s in list(p.size()):
nn = nn * s
pp += nn
return pp
def print_size(self):
nparams = 0
nbytes = 0
for param in self.parameters():
nparams += param.numel()*(param.is_complex() + 1)
nbytes += param.data.element_size() * param.numel()
print(f'Total number of model parameters: {nparams} (~{format_tensor_size(nbytes)})')
return nparams
class ConvBranch2D(nn.Module):
def __init__(self,
in_channels, # Number of input channels.
N_layers, # Number of layers in the network
N_res,
out_channel=1,
kernel_size=3,
multiply=32,
print_bool=False
): # Number of ResNet Blocks
super(ConvBranch2D, self).__init__()
assert N_layers % 2 == 0, "Number of layers myst be even number."
self.N_layers = N_layers
self.print_bool = print_bool
self.channel_multiplier = multiply
self.feature_maps = [in_channels]
for i in range(0, self.N_layers):
self.feature_maps.append(2 ** i * self.channel_multiplier)
self.feature_maps_invariant = self.feature_maps
print("channels: ", self.feature_maps)
assert len(self.feature_maps) == self.N_layers + 1
self.kernel_size = kernel_size
self.cont_conv_layers = nn.ModuleList([nn.Conv2d(self.feature_maps[i],
self.feature_maps[i + 1],
kernel_size=self.kernel_size, stride=1,
padding=((kernel_size - 1) // 2, (kernel_size - 1) // 2))
for i in range(N_layers)])
self.cont_conv_layers_invariant = nn.ModuleList([nn.Conv2d(self.feature_maps_invariant[i],
self.feature_maps_invariant[i],
kernel_size=self.kernel_size, stride=1,
padding=((kernel_size - 1) // 2, (kernel_size - 1) // 2))
for i in range(N_layers)])
self.sigma = F.leaky_relu
self.resnet_blocks = []
for i in range(N_res):
self.resnet_blocks.append(ResNetBlock(in_channels=self.feature_maps[self.N_layers]))
self.resnet_blocks = nn.Sequential(*self.resnet_blocks)
self.N_res = N_res
self.upsample4 = nn.Upsample(scale_factor=4)
self.upsample2 = nn.Upsample(scale_factor=2)
self.downsample2 = nn.AvgPool2d(2, stride=2, padding=0)
self.downsample4 = nn.AvgPool2d(4, stride=4, padding=1)
self.flatten_layer = nn.Flatten()
self.lazy_linear = nn.LazyLinear(out_channel)
def forward(self, x):
for i in range(self.N_layers):
if self.print_bool: print("BEFORE I1", x.shape)
y = self.cont_conv_layers_invariant[i](x)
if self.print_bool: print("After I1", y.shape)
y = self.sigma(self.upsample2(y))
if self.print_bool: print("After US1", y.shape)
x = self.downsample2(y)
if self.print_bool: print("AFTER IS1", x.shape)
if self.print_bool: print("INV DONE")
y = self.cont_conv_layers[i](x)
if self.print_bool: print("AFTER CONTCONV", y.shape)
y = self.upsample2(y)
if self.print_bool: print("AFTER UP", y.shape)
x = self.downsample4(self.sigma(y))
if self.print_bool: print("AFTER IS2", x.shape)
for i in range(self.N_res):
x = self.resnet_blocks[i](x)
if self.print_bool: print("RES", x.shape)
x = self.flatten_layer(x)
if self.print_bool: print("Flattened", x.shape)
x = self.lazy_linear(x)
if self.print_bool: print("Linearized", x.shape)
if self.print_bool: quit()
return x
def get_n_params(self):
pp = 0
for p in list(self.parameters()):
nn = 1
for s in list(p.size()):
nn = nn * s
pp += nn
return pp
def print_size(self):
nparams = 0
nbytes = 0
for param in self.parameters():
nparams += param.numel()*(param.is_complex() + 1)
nbytes += param.data.element_size() * param.numel()
print(f'Total number of model parameters: {nparams} (~{format_tensor_size(nbytes)})')
return nparams