-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbegan.py
232 lines (192 loc) · 7.63 KB
/
began.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
import torch
import torch.nn as nn
from .helper import View
class ConvBlock(nn.Module):
"""
All convs are created with:
conv(in_channel, out_channel, kernel, stride, pad, bias)
"""
def __init__(self, in_ch, out_ch, k, s, p, b):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(in_ch,
out_ch,
kernel_size=k,
stride=s,
padding=p,
bias=b), nn.ELU())
def forward(self, x):
return self.net(x)
class Generator128(nn.Module):
rescale = False
def __init__(self, latent_dim):
super().__init__()
self.latent_dim = latent_dim
self.ch = 128
self.initial_size = 8
self.image_size = 128
self.layers = nn.ModuleList([
nn.Sequential(
nn.Linear(self.latent_dim,
self.initial_size**2 * self.ch,
bias=False),
View((-1, self.ch, self.initial_size, self.initial_size))),
# First conv
# want z1 = 128 x 8 x 8, z2 = 128 x 8 x 8
nn.Upsample(scale_factor=2, mode='nearest'),
ConvBlock(self.ch, self.ch, 3, 1, 1, False),
ConvBlock(self.ch, self.ch, 3, 1, 1, False),
# Second block
nn.Upsample(scale_factor=2, mode='nearest'),
ConvBlock(2 * self.ch, self.ch, 3, 1, 1, False),
ConvBlock(self.ch, self.ch, 3, 1, 1, False),
# Third block
nn.Upsample(scale_factor=2, mode='nearest'),
ConvBlock(2 * self.ch, self.ch, 3, 1, 1, False),
ConvBlock(self.ch, self.ch, 3, 1, 1, False),
# Final conv
nn.Upsample(scale_factor=2, mode='nearest'),
ConvBlock(2 * self.ch, self.ch, 3, 1, 1, False),
ConvBlock(self.ch, self.ch, 3, 1, 1, False),
ConvBlock(self.ch, 3, 3, 1, 1, False),
])
self.skips = nn.ModuleList([
nn.Upsample(scale_factor=2, mode='nearest'),
nn.Upsample(scale_factor=4, mode='nearest'),
nn.Upsample(scale_factor=8, mode='nearest'),
])
self.input_shapes = [
# Raw input shape
((self.latent_dim, ), ()),
# Skip Linear+View()
((128, 8, 8), ()),
# First conv
((128, 16, 16), (128, 8, 8)),
((128, 16, 16), (128, 8, 8)),
((128, 16, 16), (128, 8, 8)),
# Second conv
((128, 32, 32), (128, 8, 8)),
((128, 32, 32), (128, 8, 8)),
((128, 32, 32), (128, 8, 8)),
# Third conv
((128, 64, 64), (128, 8, 8)),
((128, 64, 64), (128, 8, 8)),
((128, 64, 64), (128, 8, 8)),
# Final conv
((128, 128, 128), (128, 8, 8)),
((128, 128, 128), (128, 8, 8)),
((128, 128, 128), (128, 8, 8)),
# Skip entire net
((3, 128, 128), ()),
]
# self._check_input_shapes()
def _check_input_shapes(self):
for n_cuts, (x1_shape, x2_shape) in enumerate(self.input_shapes):
print(n_cuts)
x1 = torch.randn(1, *x1_shape)
if n_cuts <= 1:
x2 = None
else:
x2 = torch.randn(1, *x2_shape)
res = self.forward(x1, x2, n_cuts)
print(x1.shape, () if n_cuts <= 1 else x2.shape, res.shape[1:])
def forward(self, x1, x2=None, n_cuts=0, end=None):
"""
Skip inputs are provided to layers with python index 4, 7, 10
If n_cuts <= 1, we will use skip connections (same as in training)
Else we will provide a second input x2 that goes through skip
connections as needed
x2: either None, or B x 128 x 8 x 8
Consider network with blocks B1, B2, B3:
z_0 -B1-> z_1 -B2-> z_2 -B3-> img
If we run .forward(n_cuts=0), we do:
z_0 -B1-> z_1 -B2-> z_2 -B3-> img
If we run .forward(n_cuts=1), we do:
z_1 -B2-> z_2 -B3-> img
"""
if n_cuts <= 1:
assert x2 is None
else:
assert x2 is not None
upsample_layer_idx = [4, 7, 10]
conv256_layer_idx = [5, 8, 11]
skip_counter = [1, 1, 1]
if end is None:
end = len(self.layers)
for i in range(n_cuts, end):
layer = self.layers[i]
if i == 1:
x2 = x1
# i in upsample: use skip directly after self.skips[idx]
# i in conv256: if upsample hasn't been used; upsample and use skip
if i in upsample_layer_idx:
idx = upsample_layer_idx.index(i)
x_skip = self.skips[idx](x2)
x1 = layer(torch.cat((x1, x_skip), dim=1))
skip_counter[idx] -= 1
elif i in conv256_layer_idx:
idx = conv256_layer_idx.index(i)
# Need to check if it was upsampled already from previous layer
if skip_counter[idx] > 0:
# Need to pass an extra upsample
x_skip = nn.Upsample(scale_factor=2, mode='nearest')(x2)
x_skip = self.skips[idx](x_skip)
x1 = layer(torch.cat((x1, x_skip), dim=1))
skip_counter[idx] -= 1
else:
# No skipping occurs
x1 = layer(x1)
else:
# No skipping occurs
x1 = layer(x1)
return x1
def __str__(self):
return f'Began.Gen128.latent_dim={self.latent_dim}'
class Discriminator128(nn.Module):
def __init__(self, latent_dim):
super().__init__()
self.latent_dim = latent_dim
self.ch = 128
self.initial_size = 8
self.image_size = 128
self.encoder = nn.Sequential(
ConvBlock(3, self.ch, 3, 1, 1, True),
ConvBlock(self.ch, self.ch, 3, 1, 1, False),
ConvBlock(self.ch, self.ch * 2, 3, 2, 1, False),
ConvBlock(self.ch * 2, self.ch * 2, 3, 1, 1, False),
ConvBlock(self.ch * 2, self.ch * 3, 3, 2, 1, False),
ConvBlock(self.ch * 3, self.ch * 3, 3, 1, 1, False),
ConvBlock(self.ch * 3, self.ch * 4, 3, 2, 1, False),
ConvBlock(self.ch * 4, self.ch * 4, 3, 1, 1, False),
ConvBlock(self.ch * 4, self.ch * 5, 3, 2, 1, False),
)
self.linear = nn.Sequential(
nn.Flatten(),
nn.Linear(self.ch * 5 * self.initial_size**2,
self.latent_dim,
bias=False),
)
self.decoder = Generator128(self.latent_dim)
self._create_input_shapes()
def _create_input_shapes(self):
self.encoder_input_shapes = []
x = torch.randn(1, 3, self.image_size, self.image_size)
self.encoder_input_shapes.append(tuple(x.shape[1:]))
for i, next_layer in enumerate(self.encoder):
x = next_layer(x)
self.encoder_input_shapes.append(tuple(x.shape[1:]))
self.linear_input_shapes = []
self.linear_input_shapes.append(tuple(x.shape[1:]))
x = self.linear(x)
self.linear_input_shapes.append(tuple(x.shape[1:]))
self.decoder_input_shapes = [
x1_shape for x1_shape, _ in self.decoder.input_shapes
]
assert self.decoder_input_shapes[-1] == self.encoder_input_shapes[0]
def forward(self, x):
x = self.encoder(x)
x = self.linear(x)
x = self.decoder(x)
return x
def __str__(self):
return f'Began.Disc128.latent_dim={self.latent_dim}'