Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
POSTECH-CVLab
GitHub Repository: POSTECH-CVLab/PyTorch-StudioGAN
Path: blob/master/src/models/stylegan2.py
809 views
1
"""
2
this code is borrowed from https://github.com/NVlabs/stylegan2-ada-pytorch with few modifications
3
4
Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
5
6
NVIDIA CORPORATION and its licensors retain all intellectual property
7
and proprietary rights in and to this software, related documentation
8
and any modifications thereto. Any use, reproduction, disclosure or
9
distribution of this software and related documentation without an express
10
license agreement from NVIDIA CORPORATION is strictly prohibited.
11
"""
12
13
import torch
14
import torch.nn.functional as F
15
import numpy as np
16
17
import utils.style_misc as misc
18
from utils.style_ops import conv2d_resample
19
from utils.style_ops import upfirdn2d
20
from utils.style_ops import bias_act
21
from utils.style_ops import fma
22
23
24
def normalize_2nd_moment(x, dim=1, eps=1e-8):
25
return x * (x.square().mean(dim=dim, keepdim=True) + eps).rsqrt()
26
27
28
def modulated_conv2d(
29
x, # Input tensor of shape [batch_size, in_channels, in_height, in_width].
30
weight, # Weight tensor of shape [out_channels, in_channels, kernel_height, kernel_width].
31
styles, # Modulation coefficients of shape [batch_size, in_channels].
32
noise=None, # Optional noise tensor to add to the output activations.
33
up=1, # Integer upsampling factor.
34
down=1, # Integer downsampling factor.
35
padding=0, # Padding with respect to the upsampled image.
36
resample_filter=None, # Low-pass filter to apply when resampling activations. Must be prepared beforehand by calling upfirdn2d.setup_filter().
37
demodulate=True, # Apply weight demodulation?
38
flip_weight=True, # False = convolution, True = correlation (matches torch.nn.functional.conv2d).
39
fused_modconv=True, # Perform modulation, convolution, and demodulation as a single fused operation?
40
):
41
batch_size = x.shape[0]
42
out_channels, in_channels, kh, kw = weight.shape
43
misc.assert_shape(weight, [out_channels, in_channels, kh, kw]) # [OIkk]
44
misc.assert_shape(x, [batch_size, in_channels, None, None]) # [NIHW]
45
misc.assert_shape(styles, [batch_size, in_channels]) # [NI]
46
47
# Pre-normalize inputs to avoid FP16 overflow.
48
if x.dtype == torch.float16 and demodulate:
49
weight = weight * (1 / np.sqrt(in_channels * kh * kw) / weight.norm(float("inf"), dim=[1, 2, 3], keepdim=True)) # max_Ikk
50
styles = styles / styles.norm(float("inf"), dim=1, keepdim=True) # max_I
51
52
# Calculate per-sample weights and demodulation coefficients.
53
w = None
54
dcoefs = None
55
if demodulate or fused_modconv:
56
w = weight.unsqueeze(0) # [NOIkk]
57
w = w * styles.reshape(batch_size, 1, -1, 1, 1) # [NOIkk]
58
if demodulate:
59
dcoefs = (w.square().sum(dim=[2, 3, 4]) + 1e-8).rsqrt() # [NO]
60
if demodulate and fused_modconv:
61
w = w * dcoefs.reshape(batch_size, -1, 1, 1, 1) # [NOIkk]
62
63
# Execute by scaling the activations before and after the convolution.
64
if not fused_modconv:
65
x = x * styles.to(x.dtype).reshape(batch_size, -1, 1, 1)
66
x = conv2d_resample.conv2d_resample(x=x,
67
w=weight.to(x.dtype),
68
f=resample_filter,
69
up=up,
70
down=down,
71
padding=padding,
72
flip_weight=flip_weight)
73
if demodulate and noise is not None:
74
x = fma.fma(x, dcoefs.to(x.dtype).reshape(batch_size, -1, 1, 1), noise.to(x.dtype))
75
elif demodulate:
76
x = x * dcoefs.to(x.dtype).reshape(batch_size, -1, 1, 1)
77
elif noise is not None:
78
x = x.add_(noise.to(x.dtype))
79
return x
80
81
# Execute as one fused op using grouped convolution.
82
with misc.suppress_tracer_warnings(): # this value will be treated as a constant
83
batch_size = int(batch_size)
84
misc.assert_shape(x, [batch_size, in_channels, None, None])
85
x = x.reshape(1, -1, *x.shape[2:])
86
w = w.reshape(-1, in_channels, kh, kw)
87
x = conv2d_resample.conv2d_resample(x=x,
88
w=w.to(x.dtype),
89
f=resample_filter,
90
up=up,
91
down=down,
92
padding=padding,
93
groups=batch_size,
94
flip_weight=flip_weight)
95
x = x.reshape(batch_size, -1, *x.shape[2:])
96
if noise is not None:
97
x = x.add_(noise)
98
return x
99
100
101
class FullyConnectedLayer(torch.nn.Module):
102
def __init__(
103
self,
104
in_features, # Number of input features.
105
out_features, # Number of output features.
106
bias=True, # Apply additive bias before the activation function?
107
activation="linear", # Activation function: "relu", "lrelu", etc.
108
lr_multiplier=1, # Learning rate multiplier.
109
bias_init=0, # Initial value for the additive bias.
110
):
111
super().__init__()
112
self.activation = activation
113
self.weight = torch.nn.Parameter(torch.randn([out_features, in_features]) / lr_multiplier)
114
self.bias = torch.nn.Parameter(torch.full([out_features], np.float32(bias_init))) if bias else None
115
self.weight_gain = lr_multiplier / np.sqrt(in_features)
116
self.bias_gain = lr_multiplier
117
118
def forward(self, x):
119
w = self.weight.to(x.dtype) * self.weight_gain
120
b = self.bias
121
if b is not None:
122
b = b.to(x.dtype)
123
if self.bias_gain != 1:
124
b = b * self.bias_gain
125
126
if self.activation == "linear" and b is not None:
127
x = torch.addmm(b.unsqueeze(0), x, w.t())
128
else:
129
x = x.matmul(w.t())
130
x = bias_act.bias_act(x, b, act=self.activation)
131
return x
132
133
134
class Conv2dLayer(torch.nn.Module):
135
def __init__(
136
self,
137
in_channels, # Number of input channels.
138
out_channels, # Number of output channels.
139
kernel_size, # Width and height of the convolution kernel.
140
bias=True, # Apply additive bias before the activation function?
141
activation="linear", # Activation function: "relu", "lrelu", etc.
142
up=1, # Integer upsampling factor.
143
down=1, # Integer downsampling factor.
144
resample_filter=[1, 3, 3, 1], # Low-pass filter to apply when resampling activations.
145
conv_clamp=None, # Clamp the output to +-X, None = disable clamping.
146
channels_last=False, # Expect the input to have memory_format=channels_last?
147
trainable=True, # Update the weights of this layer during training?
148
):
149
super().__init__()
150
self.activation = activation
151
self.up = up
152
self.down = down
153
self.conv_clamp = conv_clamp
154
self.register_buffer("resample_filter", upfirdn2d.setup_filter(resample_filter))
155
self.padding = kernel_size // 2
156
self.weight_gain = 1 / np.sqrt(in_channels * (kernel_size**2))
157
self.act_gain = bias_act.activation_funcs[activation].def_gain
158
159
memory_format = torch.channels_last if channels_last else torch.contiguous_format
160
weight = torch.randn([out_channels, in_channels, kernel_size, kernel_size]).to(memory_format=memory_format)
161
bias = torch.zeros([out_channels]) if bias else None
162
if trainable:
163
self.weight = torch.nn.Parameter(weight)
164
self.bias = torch.nn.Parameter(bias) if bias is not None else None
165
else:
166
self.register_buffer("weight", weight)
167
if bias is not None:
168
self.register_buffer("bias", bias)
169
else:
170
self.bias = None
171
172
def forward(self, x, gain=1):
173
w = self.weight * self.weight_gain
174
b = self.bias.to(x.dtype) if self.bias is not None else None
175
flip_weight = (self.up == 1) # slightly faster
176
x = conv2d_resample.conv2d_resample(x=x,
177
w=w.to(x.dtype),
178
f=self.resample_filter,
179
up=self.up,
180
down=self.down,
181
padding=self.padding,
182
flip_weight=flip_weight)
183
184
act_gain = self.act_gain * gain
185
act_clamp = self.conv_clamp * gain if self.conv_clamp is not None else None
186
x = bias_act.bias_act(x, b, act=self.activation, gain=act_gain, clamp=act_clamp)
187
return x
188
189
190
class MappingNetwork(torch.nn.Module):
191
def __init__(
192
self,
193
z_dim, # Input latent (Z) dimensionality, 0 = no latent.
194
c_dim, # Conditioning label (C) dimensionality, 0 = no label.
195
w_dim, # Intermediate latent (W) dimensionality.
196
num_ws, # Number of intermediate latents to output, None = do not broadcast.
197
num_layers=8, # Number of mapping layers.
198
embed_features=None, # Label embedding dimensionality, None = same as w_dim.
199
layer_features=None, # Number of intermediate features in the mapping layers, None = same as w_dim.
200
activation="lrelu", # Activation function: "relu", "lrelu", etc.
201
lr_multiplier=0.01, # Learning rate multiplier for the mapping layers.
202
w_avg_beta=0.998, # Decay for tracking the moving average of W during training, None = do not track.
203
):
204
super().__init__()
205
self.z_dim = z_dim
206
self.c_dim = c_dim
207
self.w_dim = w_dim
208
self.num_ws = num_ws
209
self.num_layers = num_layers
210
self.w_avg_beta = w_avg_beta
211
212
if embed_features is None:
213
embed_features = w_dim
214
if c_dim == 0:
215
embed_features = 0
216
if layer_features is None:
217
layer_features = w_dim
218
features_list = [z_dim + embed_features] + [layer_features] * (num_layers - 1) + [w_dim]
219
220
if c_dim > 0:
221
self.embed = FullyConnectedLayer(c_dim, embed_features)
222
for idx in range(num_layers):
223
in_features = features_list[idx]
224
out_features = features_list[idx + 1]
225
layer = FullyConnectedLayer(in_features, out_features, activation=activation, lr_multiplier=lr_multiplier)
226
setattr(self, f"fc{idx}", layer)
227
228
if num_ws is not None and w_avg_beta is not None:
229
self.register_buffer("w_avg", torch.zeros([w_dim]))
230
231
def forward(self, z, c, truncation_psi=1, truncation_cutoff=None, update_emas=False):
232
# Embed, normalize, and concat inputs.
233
x = None
234
if self.z_dim > 0:
235
misc.assert_shape(z, [None, self.z_dim])
236
x = normalize_2nd_moment(z.to(torch.float32))
237
if self.c_dim > 0:
238
misc.assert_shape(c, [None, self.c_dim])
239
y = normalize_2nd_moment(self.embed(c.to(torch.float32)))
240
x = torch.cat([x, y], dim=1) if x is not None else y
241
242
# Main layers.
243
for idx in range(self.num_layers):
244
layer = getattr(self, f"fc{idx}")
245
x = layer(x)
246
247
# Update moving average of W.
248
if update_emas and self.w_avg_beta is not None:
249
self.w_avg.copy_(x.detach().mean(dim=0).lerp(self.w_avg, self.w_avg_beta))
250
251
# Broadcast.
252
if self.num_ws is not None:
253
x = x.unsqueeze(1).repeat([1, self.num_ws, 1])
254
255
# Apply truncation.
256
if truncation_psi != 1:
257
assert self.w_avg_beta is not None
258
if self.num_ws is None or truncation_cutoff is None:
259
x = self.w_avg.lerp(x, truncation_psi)
260
else:
261
x[:, :truncation_cutoff] = self.w_avg.lerp(x[:, :truncation_cutoff], truncation_psi)
262
return x
263
264
265
class SynthesisLayer(torch.nn.Module):
266
def __init__(
267
self,
268
in_channels, # Number of input channels.
269
out_channels, # Number of output channels.
270
w_dim, # Intermediate latent (W) dimensionality.
271
resolution, # Resolution of this layer.
272
kernel_size=3, # Convolution kernel size.
273
up=1, # Integer upsampling factor.
274
use_noise=True, # Enable noise input?
275
activation="lrelu", # Activation function: "relu", "lrelu", etc.
276
resample_filter=[1, 3, 3, 1], # Low-pass filter to apply when resampling activations.
277
conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping.
278
channels_last=False, # Use channels_last format for the weights?
279
):
280
super().__init__()
281
self.resolution = resolution
282
self.up = up
283
self.use_noise = use_noise
284
self.activation = activation
285
self.conv_clamp = conv_clamp
286
self.register_buffer("resample_filter", upfirdn2d.setup_filter(resample_filter))
287
self.padding = kernel_size // 2
288
self.act_gain = bias_act.activation_funcs[activation].def_gain
289
290
self.affine = FullyConnectedLayer(w_dim, in_channels, bias_init=1)
291
memory_format = torch.channels_last if channels_last else torch.contiguous_format
292
self.weight = torch.nn.Parameter(torch.randn([out_channels, in_channels, kernel_size, kernel_size]).to(memory_format=memory_format))
293
if use_noise:
294
self.register_buffer("noise_const", torch.randn([resolution, resolution]))
295
self.noise_strength = torch.nn.Parameter(torch.zeros([]))
296
self.bias = torch.nn.Parameter(torch.zeros([out_channels]))
297
298
def forward(self, x, w, noise_mode="random", fused_modconv=True, gain=1):
299
assert noise_mode in ["random", "const", "none"]
300
in_resolution = self.resolution // self.up
301
misc.assert_shape(x, [None, self.weight.shape[1], in_resolution, in_resolution])
302
styles = self.affine(w)
303
304
noise = None
305
if self.use_noise and noise_mode == "random":
306
noise = torch.randn([x.shape[0], 1, self.resolution, self.resolution], device=x.device) * self.noise_strength
307
if self.use_noise and noise_mode == "const":
308
noise = self.noise_const * self.noise_strength
309
310
flip_weight = (self.up == 1) # slightly faster
311
x = modulated_conv2d(x=x,
312
weight=self.weight,
313
styles=styles,
314
noise=noise,
315
up=self.up,
316
padding=self.padding,
317
resample_filter=self.resample_filter,
318
flip_weight=flip_weight,
319
fused_modconv=fused_modconv)
320
321
act_gain = self.act_gain * gain
322
act_clamp = self.conv_clamp * gain if self.conv_clamp is not None else None
323
x = bias_act.bias_act(x, self.bias.to(x.dtype), act=self.activation, gain=act_gain, clamp=act_clamp)
324
return x
325
326
327
class ToRGBLayer(torch.nn.Module):
328
def __init__(self, in_channels, out_channels, w_dim, kernel_size=1, conv_clamp=None, channels_last=False):
329
super().__init__()
330
self.conv_clamp = conv_clamp
331
self.affine = FullyConnectedLayer(w_dim, in_channels, bias_init=1)
332
memory_format = torch.channels_last if channels_last else torch.contiguous_format
333
self.weight = torch.nn.Parameter(torch.randn([out_channels, in_channels, kernel_size, kernel_size]).to(memory_format=memory_format))
334
self.bias = torch.nn.Parameter(torch.zeros([out_channels]))
335
self.weight_gain = 1 / np.sqrt(in_channels * (kernel_size**2))
336
337
def forward(self, x, w, fused_modconv=True):
338
styles = self.affine(w) * self.weight_gain
339
x = modulated_conv2d(x=x, weight=self.weight, styles=styles, demodulate=False, fused_modconv=fused_modconv)
340
x = bias_act.bias_act(x, self.bias.to(x.dtype), clamp=self.conv_clamp)
341
return x
342
343
344
class SynthesisBlock(torch.nn.Module):
345
def __init__(
346
self,
347
in_channels, # Number of input channels, 0 = first block.
348
out_channels, # Number of output channels.
349
w_dim, # Intermediate latent (W) dimensionality.
350
resolution, # Resolution of this block.
351
img_channels, # Number of output color channels.
352
is_last, # Is this the last block?
353
architecture="skip", # Architecture: "orig", "skip", "resnet".
354
resample_filter=[1, 3, 3, 1], # Low-pass filter to apply when resampling activations.
355
conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping.
356
use_fp16=False, # Use FP16 for this block?
357
fp16_channels_last=False, # Use channels-last memory format with FP16?
358
**layer_kwargs, # Arguments for SynthesisLayer.
359
):
360
assert architecture in ["orig", "skip", "resnet"]
361
super().__init__()
362
self.in_channels = in_channels
363
self.w_dim = w_dim
364
self.resolution = resolution
365
self.img_channels = img_channels
366
self.is_last = is_last
367
self.architecture = architecture
368
self.use_fp16 = use_fp16
369
self.channels_last = (use_fp16 and fp16_channels_last)
370
self.register_buffer("resample_filter", upfirdn2d.setup_filter(resample_filter))
371
self.num_conv = 0
372
self.num_torgb = 0
373
374
if in_channels == 0:
375
self.const = torch.nn.Parameter(torch.randn([out_channels, resolution, resolution]))
376
377
if in_channels != 0:
378
self.conv0 = SynthesisLayer(in_channels,
379
out_channels,
380
w_dim=w_dim,
381
resolution=resolution,
382
up=2,
383
resample_filter=resample_filter,
384
conv_clamp=conv_clamp,
385
channels_last=self.channels_last,
386
**layer_kwargs)
387
self.num_conv += 1
388
389
self.conv1 = SynthesisLayer(out_channels,
390
out_channels,
391
w_dim=w_dim,
392
resolution=resolution,
393
conv_clamp=conv_clamp,
394
channels_last=self.channels_last,
395
**layer_kwargs)
396
self.num_conv += 1
397
398
if is_last or architecture == "skip":
399
self.torgb = ToRGBLayer(out_channels, img_channels, w_dim=w_dim, conv_clamp=conv_clamp, channels_last=self.channels_last)
400
self.num_torgb += 1
401
402
if in_channels != 0 and architecture == "resnet":
403
self.skip = Conv2dLayer(in_channels,
404
out_channels,
405
kernel_size=1,
406
bias=False,
407
up=2,
408
resample_filter=resample_filter,
409
channels_last=self.channels_last)
410
411
def forward(self, x, img, ws, force_fp32=False, fused_modconv=None, update_emas=False, **layer_kwargs):
412
_ = update_emas # unused
413
misc.assert_shape(ws, [None, self.num_conv + self.num_torgb, self.w_dim])
414
w_iter = iter(ws.unbind(dim=1))
415
dtype = torch.float16 if self.use_fp16 and not force_fp32 else torch.float32
416
memory_format = torch.channels_last if self.channels_last and not force_fp32 else torch.contiguous_format
417
if fused_modconv is None:
418
with misc.suppress_tracer_warnings(): # this value will be treated as a constant
419
fused_modconv = (not self.training) and (dtype == torch.float32 or int(x.shape[0]) == 1)
420
421
# Input.
422
if self.in_channels == 0:
423
x = self.const.to(dtype=dtype, memory_format=memory_format)
424
x = x.unsqueeze(0).repeat([ws.shape[0], 1, 1, 1])
425
else:
426
misc.assert_shape(x, [None, self.in_channels, self.resolution // 2, self.resolution // 2])
427
x = x.to(dtype=dtype, memory_format=memory_format)
428
429
# Main layers.
430
if self.in_channels == 0:
431
x = self.conv1(x, next(w_iter), fused_modconv=fused_modconv, **layer_kwargs)
432
elif self.architecture == "resnet":
433
y = self.skip(x, gain=np.sqrt(0.5))
434
x = self.conv0(x, next(w_iter), fused_modconv=fused_modconv, **layer_kwargs)
435
x = self.conv1(x, next(w_iter), fused_modconv=fused_modconv, gain=np.sqrt(0.5), **layer_kwargs)
436
x = y.add_(x)
437
else:
438
x = self.conv0(x, next(w_iter), fused_modconv=fused_modconv, **layer_kwargs)
439
x = self.conv1(x, next(w_iter), fused_modconv=fused_modconv, **layer_kwargs)
440
441
# ToRGB.
442
if img is not None:
443
misc.assert_shape(img, [None, self.img_channels, self.resolution // 2, self.resolution // 2])
444
img = upfirdn2d.upsample2d(img, self.resample_filter)
445
if self.is_last or self.architecture == "skip":
446
y = self.torgb(x, next(w_iter), fused_modconv=fused_modconv)
447
y = y.to(dtype=torch.float32, memory_format=torch.contiguous_format)
448
img = img.add_(y) if img is not None else y
449
450
assert x.dtype == dtype
451
assert img is None or img.dtype == torch.float32
452
return x, img
453
454
455
class SynthesisNetwork(torch.nn.Module):
456
def __init__(
457
self,
458
w_dim, # Intermediate latent (W) dimensionality.
459
img_resolution, # Output image resolution.
460
img_channels, # Number of color channels.
461
channel_base=32768, # Overall multiplier for the number of channels.
462
channel_max=512, # Maximum number of channels in any layer.
463
num_fp16_res=0, # Use FP16 for the N highest resolutions.
464
**block_kwargs, # Arguments for SynthesisBlock.
465
):
466
assert img_resolution >= 4 and img_resolution & (img_resolution - 1) == 0
467
super().__init__()
468
self.w_dim = w_dim
469
self.img_resolution = img_resolution
470
self.img_resolution_log2 = int(np.log2(img_resolution))
471
self.img_channels = img_channels
472
self.block_resolutions = [2**i for i in range(2, self.img_resolution_log2 + 1)]
473
channels_dict = {res: min(channel_base // res, channel_max) for res in self.block_resolutions}
474
fp16_resolution = max(2**(self.img_resolution_log2 + 1 - num_fp16_res), 8)
475
476
self.num_ws = 0
477
for res in self.block_resolutions:
478
in_channels = channels_dict[res // 2] if res > 4 else 0
479
out_channels = channels_dict[res]
480
use_fp16 = (res >= fp16_resolution)
481
is_last = (res == self.img_resolution)
482
block = SynthesisBlock(in_channels,
483
out_channels,
484
w_dim=w_dim,
485
resolution=res,
486
img_channels=img_channels,
487
is_last=is_last,
488
use_fp16=use_fp16,
489
**block_kwargs)
490
self.num_ws += block.num_conv
491
if is_last:
492
self.num_ws += block.num_torgb
493
setattr(self, f"b{res}", block)
494
495
def forward(self, ws, **block_kwargs):
496
block_ws = []
497
misc.assert_shape(ws, [None, self.num_ws, self.w_dim])
498
ws = ws.to(torch.float32)
499
w_idx = 0
500
for res in self.block_resolutions:
501
block = getattr(self, f"b{res}")
502
block_ws.append(ws.narrow(1, w_idx, block.num_conv + block.num_torgb))
503
w_idx += block.num_conv
504
505
x = img = None
506
for res, cur_ws in zip(self.block_resolutions, block_ws):
507
block = getattr(self, f"b{res}")
508
x, img = block(x, img, cur_ws, **block_kwargs)
509
return img
510
511
512
class Generator(torch.nn.Module):
513
def __init__(
514
self,
515
z_dim, # Input latent (Z) dimensionality.
516
c_dim, # Conditioning label (C) dimensionality.
517
w_dim, # Intermediate latent (W) dimensionality.
518
img_resolution, # Output resolution.
519
img_channels, # Number of output color channels.
520
MODEL, # MODEL config required for applying infoGAN
521
mapping_kwargs={}, # Arguments for MappingNetwork.
522
synthesis_kwargs={}, # Arguments for SynthesisNetwork.
523
):
524
super().__init__()
525
self.z_dim = z_dim
526
self.c_dim = c_dim
527
self.w_dim = w_dim
528
self.MODEL = MODEL
529
self.img_resolution = img_resolution
530
self.img_channels = img_channels
531
532
z_extra_dim = 0
533
if self.MODEL.info_type in ["discrete", "both"]:
534
z_extra_dim += self.MODEL.info_num_discrete_c*self.MODEL.info_dim_discrete_c
535
if self.MODEL.info_type in ["continuous", "both"]:
536
z_extra_dim += self.MODEL.info_num_conti_c
537
538
if self.MODEL.info_type != "N/A":
539
self.z_dim += z_extra_dim
540
541
self.synthesis = SynthesisNetwork(w_dim=w_dim, img_resolution=img_resolution, img_channels=img_channels, **synthesis_kwargs)
542
self.num_ws = self.synthesis.num_ws
543
self.mapping = MappingNetwork(z_dim=self.z_dim, c_dim=c_dim, w_dim=w_dim, num_ws=self.num_ws, **mapping_kwargs)
544
545
def forward(self, z, c, eval=False, truncation_psi=1, truncation_cutoff=None, update_emas=False, **synthesis_kwargs):
546
ws = self.mapping(z, c, truncation_psi=truncation_psi, truncation_cutoff=truncation_cutoff, update_emas=update_emas)
547
img = self.synthesis(ws, update_emas=update_emas, **synthesis_kwargs)
548
return img
549
550
551
class DiscriminatorBlock(torch.nn.Module):
552
def __init__(
553
self,
554
in_channels, # Number of input channels, 0 = first block.
555
tmp_channels, # Number of intermediate channels.
556
out_channels, # Number of output channels.
557
resolution, # Resolution of this block.
558
img_channels, # Number of input color channels.
559
first_layer_idx, # Index of the first layer.
560
architecture="resnet", # Architecture: "orig", "skip", "resnet".
561
activation="lrelu", # Activation function: "relu", "lrelu", etc.
562
resample_filter=[1, 3, 3, 1], # Low-pass filter to apply when resampling activations.
563
conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping.
564
use_fp16=False, # Use FP16 for this block?
565
fp16_channels_last=False, # Use channels-last memory format with FP16?
566
freeze_layers=0, # Freeze-D: Number of layers to freeze.
567
):
568
assert in_channels in [0, tmp_channels]
569
assert architecture in ["orig", "skip", "resnet"]
570
super().__init__()
571
self.in_channels = in_channels
572
self.resolution = resolution
573
self.img_channels = img_channels
574
self.first_layer_idx = first_layer_idx
575
self.architecture = architecture
576
self.use_fp16 = use_fp16
577
self.channels_last = (use_fp16 and fp16_channels_last)
578
self.register_buffer("resample_filter", upfirdn2d.setup_filter(resample_filter))
579
580
self.num_layers = 0
581
582
def trainable_gen():
583
while True:
584
layer_idx = self.first_layer_idx + self.num_layers
585
trainable = (layer_idx >= freeze_layers)
586
self.num_layers += 1
587
yield trainable
588
589
trainable_iter = trainable_gen()
590
591
if in_channels == 0 or architecture == "skip":
592
self.fromrgb = Conv2dLayer(img_channels,
593
tmp_channels,
594
kernel_size=1,
595
activation=activation,
596
trainable=next(trainable_iter),
597
conv_clamp=conv_clamp,
598
channels_last=self.channels_last)
599
600
self.conv0 = Conv2dLayer(tmp_channels,
601
tmp_channels,
602
kernel_size=3,
603
activation=activation,
604
trainable=next(trainable_iter),
605
conv_clamp=conv_clamp,
606
channels_last=self.channels_last)
607
608
self.conv1 = Conv2dLayer(tmp_channels,
609
out_channels,
610
kernel_size=3,
611
activation=activation,
612
down=2,
613
trainable=next(trainable_iter),
614
resample_filter=resample_filter,
615
conv_clamp=conv_clamp,
616
channels_last=self.channels_last)
617
618
if architecture == "resnet":
619
self.skip = Conv2dLayer(tmp_channels,
620
out_channels,
621
kernel_size=1,
622
bias=False,
623
down=2,
624
trainable=next(trainable_iter),
625
resample_filter=resample_filter,
626
channels_last=self.channels_last)
627
628
def forward(self, x, img, force_fp32=False):
629
dtype = torch.float16 if self.use_fp16 and not force_fp32 else torch.float32
630
memory_format = torch.channels_last if self.channels_last and not force_fp32 else torch.contiguous_format
631
632
# Input.
633
if x is not None:
634
misc.assert_shape(x, [None, self.in_channels, self.resolution, self.resolution])
635
x = x.to(dtype=dtype, memory_format=memory_format)
636
637
# FromRGB.
638
if self.in_channels == 0 or self.architecture == "skip":
639
misc.assert_shape(img, [None, self.img_channels, self.resolution, self.resolution])
640
img = img.to(dtype=dtype, memory_format=memory_format)
641
y = self.fromrgb(img)
642
x = x + y if x is not None else y
643
img = upfirdn2d.downsample2d(img, self.resample_filter) if self.architecture == "skip" else None
644
645
# Main layers.
646
if self.architecture == "resnet":
647
y = self.skip(x, gain=np.sqrt(0.5))
648
x = self.conv0(x)
649
x = self.conv1(x, gain=np.sqrt(0.5))
650
x = y.add_(x)
651
else:
652
x = self.conv0(x)
653
x = self.conv1(x)
654
655
assert x.dtype == dtype
656
return x, img
657
658
659
class MinibatchStdLayer(torch.nn.Module):
660
def __init__(self, group_size, num_channels=1):
661
super().__init__()
662
self.group_size = group_size
663
self.num_channels = num_channels
664
665
def forward(self, x):
666
N, C, H, W = x.shape
667
with misc.suppress_tracer_warnings(): # as_tensor results are registered as constants
668
G = torch.min(torch.as_tensor(self.group_size), torch.as_tensor(N)) if self.group_size is not None else N
669
F = self.num_channels
670
c = C // F
671
672
y = x.reshape(G, -1, F, c, H, W) # [GnFcHW] Split minibatch N into n groups of size G, and channels C into F groups of size c.
673
y = y - y.mean(dim=0) # [GnFcHW] Subtract mean over group.
674
y = y.square().mean(dim=0) # [nFcHW] Calc variance over group.
675
y = (y + 1e-8).sqrt() # [nFcHW] Calc stddev over group.
676
y = y.mean(dim=[2, 3, 4]) # [nF] Take average over channels and pixels.
677
y = y.reshape(-1, F, 1, 1) # [nF11] Add missing dimensions.
678
y = y.repeat(G, 1, H, W) # [NFHW] Replicate over group and pixels.
679
x = torch.cat([x, y], dim=1) # [NCHW] Append to input as new channels.
680
return x
681
682
683
class DiscriminatorEpilogue(torch.nn.Module):
684
def __init__(
685
self,
686
in_channels, # Number of input channels.
687
cmap_dim, # Dimensionality of mapped conditioning label, 0 = no label.
688
resolution, # Resolution of this block.
689
img_channels, # Number of input color channels.
690
architecture="resnet", # Architecture: "orig", "skip", "resnet".
691
mbstd_group_size=4, # Group size for the minibatch standard deviation layer, None = entire minibatch.
692
mbstd_num_channels=1, # Number of features for the minibatch standard deviation layer, 0 = disable.
693
activation="lrelu", # Activation function: "relu", "lrelu", etc.
694
conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping.
695
):
696
assert architecture in ["orig", "skip", "resnet"]
697
super().__init__()
698
self.in_channels = in_channels
699
self.cmap_dim = cmap_dim
700
self.resolution = resolution
701
self.img_channels = img_channels
702
self.architecture = architecture
703
704
if architecture == "skip":
705
self.fromrgb = Conv2dLayer(img_channels, in_channels, kernel_size=1, activation=activation)
706
self.mbstd = MinibatchStdLayer(group_size=mbstd_group_size, num_channels=mbstd_num_channels) if mbstd_num_channels > 0 else None
707
self.conv = Conv2dLayer(in_channels + mbstd_num_channels, in_channels, kernel_size=3, activation=activation, conv_clamp=conv_clamp)
708
self.fc = FullyConnectedLayer(in_channels * (resolution**2), in_channels, activation=activation)
709
# self.out = FullyConnectedLayer(in_channels, 1 if cmap_dim == 0 else cmap_dim)
710
711
def forward(self, x, img, force_fp32=False):
712
misc.assert_shape(x, [None, self.in_channels, self.resolution, self.resolution]) # [NCHW]
713
_ = force_fp32 # unused
714
dtype = torch.float32
715
memory_format = torch.contiguous_format
716
717
# FromRGB.
718
x = x.to(dtype=dtype, memory_format=memory_format)
719
if self.architecture == "skip":
720
misc.assert_shape(img, [None, self.img_channels, self.resolution, self.resolution])
721
img = img.to(dtype=dtype, memory_format=memory_format)
722
x = x + self.fromrgb(img)
723
724
# Main layers.
725
if self.mbstd is not None:
726
x = self.mbstd(x)
727
x = self.conv(x)
728
x = self.fc(x.flatten(1))
729
# x = self.out(x)
730
731
return x
732
733
734
class Discriminator(torch.nn.Module):
735
def __init__(
736
self,
737
c_dim, # Conditioning label (C) dimensionality.
738
img_resolution, # Input resolution.
739
img_channels, # Number of input color channels.
740
architecture="resnet", # Architecture: "orig", "skip", "resnet".
741
channel_base=32768, # Overall multiplier for the number of channels.
742
channel_max=512, # Maximum number of channels in any layer.
743
num_fp16_res=0, # Use FP16 for the N highest resolutions.
744
conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping.
745
cmap_dim=None, # Dimensionality of mapped conditioning label, None = default.
746
d_cond_mtd=None, # conditioning method of the discriminator
747
aux_cls_type=None, # type of auxiliary classifier
748
d_embed_dim=None, # dimension of feature maps after convolution operations
749
num_classes=None, # number of classes
750
normalize_d_embed=None, # whether to normalize the feature maps or not
751
block_kwargs={}, # Arguments for DiscriminatorBlock.
752
mapping_kwargs={}, # Arguments for MappingNetwork.
753
epilogue_kwargs={}, # Arguments for DiscriminatorEpilogue.
754
MODEL=None, # needed to check options for infoGAN
755
):
756
super().__init__()
757
self.c_dim = c_dim
758
self.img_resolution = img_resolution
759
self.img_channels = img_channels
760
self.cmap_dim = cmap_dim
761
self.d_cond_mtd = d_cond_mtd
762
self.aux_cls_type = aux_cls_type
763
self.num_classes = num_classes
764
self.normalize_d_embed = normalize_d_embed
765
self.img_resolution_log2 = int(np.log2(img_resolution))
766
self.block_resolutions = [2**i for i in range(self.img_resolution_log2, 2, -1)]
767
self.MODEL = MODEL
768
channels_dict = {res: min(channel_base // res, channel_max) for res in self.block_resolutions + [4]}
769
fp16_resolution = max(2**(self.img_resolution_log2 + 1 - num_fp16_res), 8)
770
771
if self.cmap_dim is None:
772
self.cmap_dim = channels_dict[4]
773
if c_dim == 0:
774
self.cmap_dim = 0
775
776
common_kwargs = dict(img_channels=img_channels, architecture=architecture, conv_clamp=conv_clamp)
777
cur_layer_idx = 0
778
for res in self.block_resolutions:
779
in_channels = channels_dict[res] if res < img_resolution else 0
780
tmp_channels = channels_dict[res]
781
out_channels = channels_dict[res // 2]
782
use_fp16 = (res >= fp16_resolution)
783
block = DiscriminatorBlock(in_channels,
784
tmp_channels,
785
out_channels,
786
resolution=res,
787
first_layer_idx=cur_layer_idx,
788
use_fp16=use_fp16,
789
**block_kwargs,
790
**common_kwargs)
791
setattr(self, f"b{res}", block)
792
cur_layer_idx += block.num_layers
793
794
self.b4 = DiscriminatorEpilogue(channels_dict[4], cmap_dim=self.cmap_dim, resolution=4, **epilogue_kwargs, **common_kwargs)
795
796
# linear layer for adversarial training
797
if self.d_cond_mtd == "MH":
798
self.linear1 = FullyConnectedLayer(channels_dict[4], 1 + self.num_classes, bias=True)
799
elif self.d_cond_mtd == "MD":
800
self.linear1 = FullyConnectedLayer(channels_dict[4], self.num_classes, bias=True)
801
elif self.d_cond_mtd == "SPD":
802
self.linear1 = FullyConnectedLayer(channels_dict[4], 1 if self.cmap_dim == 0 else self.cmap_dim, bias=True)
803
else:
804
self.linear1 = FullyConnectedLayer(channels_dict[4], 1, bias=True)
805
806
# double num_classes for Auxiliary Discriminative Classifier
807
if self.aux_cls_type == "ADC":
808
num_classes, c_dim = num_classes * 2, c_dim * 2
809
810
# linear and embedding layers for discriminator conditioning
811
if self.d_cond_mtd == "AC":
812
self.linear2 = FullyConnectedLayer(channels_dict[4], num_classes, bias=False)
813
elif self.d_cond_mtd == "PD":
814
self.linear2 = FullyConnectedLayer(channels_dict[4], self.cmap_dim, bias=True)
815
elif self.d_cond_mtd == "SPD":
816
self.mapping = MappingNetwork(z_dim=0, c_dim=c_dim, w_dim=self.cmap_dim, num_ws=None, w_avg_beta=None, **mapping_kwargs)
817
elif self.d_cond_mtd in ["2C", "D2DCE"]:
818
self.linear2 = FullyConnectedLayer(channels_dict[4], d_embed_dim, bias=True)
819
self.embedding = MappingNetwork(z_dim=0, c_dim=c_dim, w_dim=d_embed_dim, num_ws=None, w_avg_beta=None, num_layers=1, **mapping_kwargs)
820
else:
821
pass
822
823
# linear and embedding layers for evolved classifier-based GAN
824
if self.aux_cls_type == "TAC":
825
if self.d_cond_mtd == "AC":
826
self.linear_mi = FullyConnectedLayer(channels_dict[4], num_classes, bias=False)
827
elif self.d_cond_mtd in ["2C", "D2DCE"]:
828
self.linear_mi = FullyConnectedLayer(channels_dict[4], d_embed_dim, bias=True)
829
self.embedding_mi = MappingNetwork(z_dim=0, c_dim=c_dim, w_dim=d_embed_dim, num_ws=None, w_avg_beta=None, num_layers=1, **mapping_kwargs)
830
else:
831
raise NotImplementedError
832
833
# Q head network for infoGAN
834
if self.MODEL.info_type in ["discrete", "both"]:
835
out_features = self.MODEL.info_num_discrete_c*self.MODEL.info_dim_discrete_c
836
self.info_discrete_linear = FullyConnectedLayer(in_features=channels_dict[4], out_features=out_features, bias=False)
837
if self.MODEL.info_type in ["continuous", "both"]:
838
out_features = self.MODEL.info_num_conti_c
839
self.info_conti_mu_linear = FullyConnectedLayer(in_features=channels_dict[4], out_features=out_features, bias=False)
840
self.info_conti_var_linear = FullyConnectedLayer(in_features=channels_dict[4], out_features=out_features, bias=False)
841
842
def forward(self, img, label, eval=False, adc_fake=False, update_emas=False, **block_kwargs):
843
_ = update_emas # unused
844
x, embed, proxy, cls_output = None, None, None, None
845
mi_embed, mi_proxy, mi_cls_output = None, None, None
846
info_discrete_c_logits, info_conti_mu, info_conti_var = None, None, None
847
for res in self.block_resolutions:
848
block = getattr(self, f"b{res}")
849
x, img = block(x, img, **block_kwargs)
850
h = self.b4(x, img)
851
852
# adversarial training
853
if self.d_cond_mtd != "SPD":
854
adv_output = torch.squeeze(self.linear1(h))
855
856
# make class labels odd (for fake) or even (for real) for ADC
857
if self.aux_cls_type == "ADC":
858
if adc_fake:
859
label = label*2 + 1
860
else:
861
label = label*2
862
oh_label = F.one_hot(label, self.num_classes * 2 if self.aux_cls_type=="ADC" else self.num_classes)
863
864
# forward pass through InfoGAN Q head
865
if self.MODEL.info_type in ["discrete", "both"]:
866
info_discrete_c_logits = self.info_discrete_linear(h)
867
if self.MODEL.info_type in ["continuous", "both"]:
868
info_conti_mu = self.info_conti_mu_linear(h)
869
info_conti_var = torch.exp(self.info_conti_var_linear(h))
870
871
# class conditioning
872
if self.d_cond_mtd == "AC":
873
if self.normalize_d_embed:
874
for W in self.linear2.parameters():
875
W = F.normalize(W, dim=1)
876
h = F.normalize(h, dim=1)
877
cls_output = self.linear2(h)
878
elif self.d_cond_mtd == "PD":
879
adv_output = adv_output + torch.sum(torch.mul(self.embedding(None, oh_label), h), 1)
880
elif self.d_cond_mtd == "SPD":
881
embed = self.linear1(h)
882
cmap = self.mapping(None, oh_label)
883
adv_output = (embed * cmap).sum(dim=1, keepdim=True) * (1 / np.sqrt(self.cmap_dim))
884
elif self.d_cond_mtd in ["2C", "D2DCE"]:
885
embed = self.linear2(h)
886
proxy = self.embedding(None, oh_label)
887
if self.normalize_d_embed:
888
embed = F.normalize(embed, dim=1)
889
proxy = F.normalize(proxy, dim=1)
890
elif self.d_cond_mtd == "MD":
891
idx = torch.LongTensor(range(label.size(0))).to(label.device)
892
adv_output = adv_output[idx, label]
893
elif self.d_cond_mtd in ["W/O", "MH"]:
894
pass
895
else:
896
raise NotImplementedError
897
898
# extra conditioning for TACGAN and ADCGAN
899
if self.aux_cls_type == "TAC":
900
if self.d_cond_mtd == "AC":
901
if self.normalize_d_embed:
902
for W in self.linear_mi.parameters():
903
W = F.normalize(W, dim=1)
904
mi_cls_output = self.linear_mi(h)
905
elif self.d_cond_mtd in ["2C", "D2DCE"]:
906
mi_embed = self.linear_mi(h)
907
mi_proxy = self.embedding_mi(None, oh_label)
908
if self.normalize_d_embed:
909
mi_embed = F.normalize(mi_embed, dim=1)
910
mi_proxy = F.normalize(mi_proxy, dim=1)
911
return {
912
"h": h,
913
"adv_output": adv_output,
914
"embed": embed,
915
"proxy": proxy,
916
"cls_output": cls_output,
917
"label": label,
918
"mi_embed": mi_embed,
919
"mi_proxy": mi_proxy,
920
"mi_cls_output": mi_cls_output,
921
"info_discrete_c_logits": info_discrete_c_logits,
922
"info_conti_mu": info_conti_mu,
923
"info_conti_var": info_conti_var
924
}
925
926