-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.py
246 lines (223 loc) · 6.79 KB
/
generator.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
from typing import List, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from cam import CAMAttention
from normalization import ILN
from resnet import ResnetBlock
class FromRGB(nn.Sequential):
def __init__(self, ngf: int, in_channels: int = 3):
super().__init__(
nn.ReflectionPad2d(3),
nn.Conv2d(
in_channels=in_channels,
out_channels=ngf,
kernel_size=7,
stride=1,
padding=0,
bias=False
),
nn.InstanceNorm2d(ngf),
nn.ReLU(True)
)
class ToRGB(nn.Sequential):
def __init__(self, in_channels: int, out_channels: int = 3):
super().__init__(
nn.ReflectionPad2d(3),
nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=7,
stride=1,
padding=0,
bias=False
),
nn.Tanh()
)
class DownsampleBlock(nn.Sequential):
def __init__(self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int,
reflection_padding: int,
padding: int,
bias: bool
):
super().__init__(
nn.ReflectionPad2d(reflection_padding),
nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=bias
),
nn.InstanceNorm2d(out_channels),
nn.ReLU(True)
)
class UpsampleBlock(nn.Sequential):
def __init__(self,
in_channels: int,
out_channels: int,
scale_factor: int,
kernel_size: int,
stride: int,
reflection_padding: int,
padding: int,
bias: bool,
activation: nn.Module
):
super().__init__(
nn.Upsample(scale_factor=scale_factor, mode='nearest'),
nn.ReflectionPad2d(reflection_padding),
nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=bias
),
ILN(out_channels),
activation
)
class AdaNormParamsInferenceNet(nn.Module):
def __init__(self, ngf: int, mult: int):
super(AdaNormParamsInferenceNet, self).__init__()
self.fc = nn.Sequential(
nn.Linear(ngf * mult, ngf * mult, bias=False),
nn.ReLU(True),
nn.Linear(ngf * mult, ngf * mult, bias=False),
nn.ReLU(True)
)
self.gamma = nn.Linear(ngf * mult, ngf * mult, bias=False)
self.beta = nn.Linear(ngf * mult, ngf * mult, bias=False)
def forward(self, x: torch.Tensor):
batch_size, _, _, _ = x.shape
x_ = F.adaptive_avg_pool2d(x, 1)
x_ = x_.view(batch_size, -1)
x_ = self.fc(x_)
return self.gamma(x_), self.beta(x_)
class ResnetGenerator(nn.Module):
def __init__(self,
in_channels: int = 3,
out_channels: int = 3,
ngf=64,
num_bottleneck_blocks=9,
num_downsampling_blocks=2,
nce_layers_indices: List[int] = [],
):
super(ResnetGenerator, self).__init__()
self.in_channels = in_channels
self.output_nc = out_channels
self.ngf = ngf
self.num_resnet_blocks = num_bottleneck_blocks
self.num_resnet_enc_blocks = num_bottleneck_blocks // 2
self.num_resnet_dec_blocks = num_bottleneck_blocks // 2
if num_bottleneck_blocks % 2:
self.num_resnet_enc_blocks += 1
self.nce_layers_indices = nce_layers_indices
# encoder downsampling
self.enc_down = nn.ModuleList([
nn.Identity(), # For easier NCE indexing.
FromRGB(in_channels=in_channels, ngf=ngf),
])
for i in range(num_downsampling_blocks):
mult = 2**i
self.enc_down += [
DownsampleBlock(
reflection_padding=1,
in_channels=ngf * mult,
out_channels=ngf * mult * 2,
kernel_size=3,
stride=2,
padding=0,
bias=False
)
]
# encoder bottleneck
mult = 2**num_downsampling_blocks
self.enc_bottleneck = nn.ModuleList([
ResnetBlock(
channels=ngf * mult,
bias=False,
adaptive_norm=False
)
for _ in range(self.num_resnet_enc_blocks)
])
# CAM
self.cam = CAMAttention(channels=ngf * mult, act=nn.ReLU(True))
# AdaLIN params
self.ada_norm_params_infer = AdaNormParamsInferenceNet(ngf, mult)
# decoder bottleneck
self.dec_bottleneck = nn.ModuleList([
ResnetBlock(
channels=ngf * mult,
bias=False,
adaptive_norm=True
)
for _ in range(self.num_resnet_dec_blocks)
])
# decoder upsampling
self.dec_up = nn.ModuleList([])
for i in range(num_downsampling_blocks):
mult = 2**(num_downsampling_blocks - i)
self.dec_up += [
UpsampleBlock(
reflection_padding=1,
in_channels=ngf * mult,
out_channels=int(ngf * mult / 2),
scale_factor=2,
kernel_size=3,
stride=1,
padding=0,
bias=False,
activation=nn.ReLU(True)
)
]
self.dec_up += [ToRGB(in_channels=ngf, out_channels=out_channels)]
# layer index
self.layers = dict(
enumerate(
self.enc_down +
self.enc_bottleneck +
[self.cam] +
[self.ada_norm_params_infer] +
self.dec_bottleneck +
self.dec_up
)
)
def encode(self, x: torch.Tensor):
assert self.nce_layers_indices
nce_layers = [
self.layers[layer_idx]
for layer_idx in self.nce_layers_indices
]
final_nce_layer = nce_layers[-1] if nce_layers else None
nce_layers_outs = []
for layer in (self.enc_down + self.enc_bottleneck):
x = layer(x)
if layer in nce_layers:
nce_layers_outs.append(x)
if layer == final_nce_layer:
return nce_layers_outs
raise ValueError(
'final nce layer must be within the encoder of the generator!'
)
def forward(self, x: torch.Tensor, cam: bool = True) -> Union[Tuple[torch.Tensor, torch.Tensor, torch.Tensor], torch.Tensor]:
for layer in self.enc_down:
x = layer(x)
for layer in self.enc_bottleneck:
x = layer(x)
x, cam_logits, heatmap = self.cam(x)
gamma, beta = self.ada_norm_params_infer(x)
for layer in self.dec_bottleneck:
x = layer(x, gamma, beta)
for layer in self.dec_up:
x = layer(x)
if cam:
return x, cam_logits, heatmap
else:
return x